Experiment No. 3a
Write a Java program to read two integers a andb.
Compute a/b and print, when b is
not zero. Raise an exception when b
is equal to zero.
importjava.util.Scanner;
classdivision
{
public static void main(String[] args)
{
inta,b,result;
Scanner input =newScanner(System.in);
System.out.println("Input
two integers");
a=input.nextInt();
b=input.nextInt();
try
{
result=a/b;
System.out.println("Result="+result);
}
catch(ArithmeticException e)
{
System.out.println("exception
caught: Divide by zero
error"+e);
}
}
Output:
Input two integers
6 2
Result=3
Input two integers
3
0
exception caught: Divide by zero errorjava.lang.ArithmeticException:
/ by zero
Java Exceptions
When executing Java code, different errors can occur: coding
errors made by the programmer, errors due to wrong input, or other
unforeseeable things.
When an error occurs, Java will normally stop and generate an
error message. The technical term for this is: Java will throw an exception (throw
an error).
Java try and catch
The try statement allows you to define a block of code to be tested
for errors while it is being executed.
The catch statement allows you to define a block of code to be
executed, if an error occurs in the try block.
The try and catch keywords come in pairs:
Syntax
try{
// Block of code to try
}
catch(Exceptione)
{
// Block of code to handle errors
}
Consider the following example:
This will generate an error, because myNumbers[10] does
not exist.
publicclass
Main
{
public
static
void
main(String[
]
args
){
int[]
myNumbers
={1,
2,
3};
System.
out
.println(myNumbers
[10]);// error!
}
}
The output will be something like this:
Exception
in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Main.main(Main.java:4)
If an error occurs, we can use try...catch
to
catch the error and execute some code to handle it:
Example
publicclass
Main
{
public
static
void
main(String[
]
args
){
try
{
int[]
myNumbers
={1,
2,
3};
System.
out
.println(myNumbers
[10]);
}
catch
(Exception
e
){
System.
out
.println("Something went wrong.");
}
}
}
The output will be:
Something
went wrong.
Finally
The finally
statement lets you execute code, after try...catch
, regardless
of the result:
Example
publicclass
Main
{
public
static
void
main(String[]
args
){
try
{
int[]
myNumbers
={1,
2,
3};
System.
out
.println(myNumbers
[10]);
}
catch
(Exception
e
){
System.
out
.println("Something went wrong.");
}
finally
{
System.
out
.println("The 'try catch' is finished.");
}
}
}
The output will be:
Something
went wrong.
The 'try
catch' is finished.
The throw
keyword
The throw
statement allows you to create a custom error.
The throw
statement is used together with an exception
type. There are many exception types available in Java: ArithmeticException
, FileNotFoundException
, ArrayIndexOutOfBoundsException
, SecurityException
, etc:
Example
Throw an exception if age is
below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":
publicclass
Main
{
static
void
checkAge(int
age
){
if
(
age
<18)
{
throw
new
ArithmeticException("Access denied - You must be at least 18 years old.");
}
else
{
System.
out
.println("Access granted - You are old enough!");
}
}
public
static
void
main(String[]
args
){
checkAge(15);
// Set age to 15 (which is below 18...)
}
}
The output will be:
Exception
in thread "main" java.lang.ArithmeticException: Access denied - You
must be at least 18 years old.
at
Main.checkAge(Main.java:4)
at
Main.main(Main.java:12)
If age was 20, you would not get
an exception:
Example
checkAge(20);
The output will be:
Access
granted - You are old enough!
Experiment
No. 3b
Write a Java program that implements
a multi-thread application that hash tree threads. First thread generates a
random integer for every 1 second; second thread computes the square of the
number and prints; third thread will print the value of cube of the number.
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. The class must define a method of no arguments called run .
This interface is designed to provide a common protocol for objects that wish
to execute code while they are active.
How
to Generate Random Number in Java
In Java programming,
we often required to generate random numbers while
we develop applications. Many applications have the feature to generate
numbers randomly, such as to verify the user many applications use
the OTP. The best example of random numbers is dice.
Because when we throw it, we get a random number between 1 to 6.
Using the Random
Class
Another
way to generate a random number is to use the Java Random class
of
the java.util package.
It generates a stream of pseudorandom numbers. We can generate a random number
of any data type, such as integer, float, double, Boolean, long. If you are
going to use this class to generate random numbers, follow the steps given
below:
- First, import the class java.lang.Random.
- Create an object of
the Random class.
- Invoke any of the following methods:
- nextInt(int
bound)
- nextInt()
- nextFloat()
- nextDouble()
- nextLong()
- nextBoolean()
All
the above methods return the next pseudorandom, homogeneously distributed value
(corresponding method) from this random number generator's sequence. The nextDouble() and nextFloat() method
generates random value between 0.0 and 1.0.
The nextInt(int
bound) method accepts a parameter bound (upper) that must be
positive. It generates a random number in the range 0 to bound-1.
1. import java.util.Random;
2. public class RandomNumberExample3
3. {
4. public static void main(String args[])
5. {
6. // creating an object of Random class
7. Random random = new Random();
8. // Generates random integers 0 to 49
9. int x = random.nextInt(50);
10. // Generates random integers 0 to 999
11. int y = random.nextInt(1000);
12. // Prints random integer values
13. System.out.println("Randomly Generated Integers Values");
14. System.out.println(x);
15. System.out.println(y);
16. // Generates Random doubles values
17. double a = random.nextDouble();
18. double b = random.nextDouble();
19. // Prints random double values
20. System.out.println("Randomly Generated Double Values");
21. System.out.println(a);
22. System.out.println(b);
23. // Generates Random float values
24. float f=random.nextFloat();
25. float i=random.nextFloat();
26. // Prints random float values
27. System.out.println("Randomly Generated Float Values");
28. System.out.println(f);
29. System.out.println(i);
30. // Generates Random Long values
31. long p = random.nextLong();
32. long q = random.nextLong();
33. // Prints random long values
34. System.out.println("Randomly Generated Long Values");
35. System.out.println(p);
36. System.out.println(q);
37. // Generates Random boolean values
38. boolean m=random.nextBoolean();
39. boolean n=random.nextBoolean();
40. // Prints random boolean values
41. System.out.println("Randomly Generated Boolean Values");
42. System.out.println(m);
43. System.out.println(n);
44. }
45. }
Output:
Randomly Generated Integers Values
23
767
Randomly Generated Double Values
0.37823814494212016
0.998058172671956
Randomly Generated Float Values
0.87804186
0.93880254
Randomly Generated Long Values
-4974823544291679198
3650240138416076693
Randomly Generated Boolean Values
false
true
Implement
Runnable vs Extend Thread in Java
As discussed in Java multi-threading article we can define a
thread in the following two ways:
·
By extending Thread class
·
By implementing Runnable interface
In the first approach, Our
class always extends Thread class. There is no chance of extending any other
class. Hence we are missing Inheritance benefits. In the second approach, while
implementing Runnable interface we can extends any other class. Hence we are
able to use the benefits of Inheritance.
Because of the above reasons, implementing Runnable interface approach is
recommended than extending Thread class.
The significant differences between extending Thread class and
implementing Runnable interface:
·
When we extend Thread class, we can’t extend
any other class even we require and When we implement Runnable, we can save a
space for our class to extend any other class in future or now.
·
When we extend Thread class, each of our
thread creates unique object and associate with it. When we implements
Runnable, it shares the same object to multiple threads.
Lets have a look on the
below programs for better understanding:
// Java program to illustrate
defining Thread
// by extending Thread class
// Here we cant extends any other
class
class Test extends Thread
{
public
void run()
{
System.out.println("Run
method executed by child Thread");
}
public
static void main(String[] args)
{
Test
t = new Test();
t.start();
System.out.println("Main
method executed by main thread");
}
}
Output:
Main
method executed by main thread
Run
method executed by child Thread
// Java program to illustrate
defining Thread
// by implements Runnable interface
class Geeks {
public
static void m1()
{
System.out.println("Hello
Visitors");
}
}
// Here we can extends any other
class
class Test extends Geeks implements
Runnable {
public
void run()
{
System.out.println("Run
method executed by child Thread");
}
public
static void main(String[] args)
{
Test
t = new Test();
t.m1();
Thread
t1 = new Thread(t);
t1.start();
System.out.println("Main
method executed by main thread");
}
}
Output:
Hello
Visitors
Main
method executed by main thread
Run
method executed by child Thread
NOTE : In the case of multithreading we cant predict the
exact order of output because it will vary from system to system or JVM to JVM.
Experiment
No. 3b
Write a Java program that implements
a multi-thread application that hash tree threads. First thread generates a
random integer for every 1 second; second thread computes the square of the
number and prints; third thread will print the value of cube of the number.
import java.util.*;
class
second
implements Runnable
{
public
int x;
public
second (int
x)
{
this.x=x;
}
public
void run()
{
System.out.println("Second
thread:Square of the number
is"+x*x);
}
}
class
third
implements Runnable
{
public
int x;
public
third(int
x)
{
this.x=x;
}
public
void run()
{
System.out.println("third
thread:Cube of the number is"+x*x*x);
}
}
class
first
extends Thread
{
public void run()
{
int
num=0;
Random r=new Random();
try
{
for(inti=0;i<5;i++)
{
num=r.nextInt(100);
System.out.println("first
thread generated number
is"+num);
Thread t2=new Thread (new second(num)); t2.start();
Thread t3=new Thread(new third(num));
t3.start();
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
public class multithread
{
public static void main(String args[])
{
first a=new first();
a.start();
}
}
OUTPUT:
first thread generated number is65
Second thread:Square of the number
is4225
thirdthread:Cube of the number
is274625
first thread generated number is33
Second thread:Square of the number
is1089
thirdthread:Cube of the number
is35937
first thread generated number is30
Second thread:Square of the number
is900
thirdthread:Cube of the number
is27000
first thread generated number is29
Second thread:Square of the number
is841
thirdthread:Cube of the number
is24389
first thread generated number is93
Second thread:Square of the number
is8649
thirdthread:Cube of the number
is804357
No comments:
Post a Comment