Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views77 pages

Unit III Exception

This document covers Exception Handling and Multithreading in Java, detailing various types of exceptions, including checked and unchecked exceptions, and the use of keywords like try, catch, finally, throw, and throws. It also explains the concept of multithreading, including thread creation, synchronization, and inter-thread communication. Additionally, it provides examples of user-defined exceptions and the Java thread model.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views77 pages

Unit III Exception

This document covers Exception Handling and Multithreading in Java, detailing various types of exceptions, including checked and unchecked exceptions, and the use of keywords like try, catch, finally, throw, and throws. It also explains the concept of multithreading, including thread creation, synchronization, and inter-thread communication. Additionally, it provides examples of user-defined exceptions and the Java thread model.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 77

UNIT III

Exception Handling and


Multithreading

Exception Handling – Multiple catch Clauses –


Nested try Statements – Java’s Built-in
Exceptions – User defined Exception.
Multithreaded Programming: Java Thread
Model–Creating a Thread and Multiple
Threads – Priorities – Synchronization – Inter
Thread Communication- Suspending –
Resuming, and Stopping Threads. Wrappers –
Auto boxing.

1. Exception Handling
Exception is an abnormal condition.
ClassNotFoundException,
IOException,
SQLException,
RemoteException, etc.
to handle the runtime errors
to maintain the normal flow of the
application

Exception may occurs due to this reason:


A user has entered an invalid data.
A file that needs to be opened cannot be
found.
A network connection has been lost in the
middle of communications or the JVM has
run out of memory.
Hierarchy of Java Exception classes

Types of Java Exceptions

There are mainly two types of exceptions:


checked and unchecked.

An error is considered as the unchecked


exception. Checked Exception
1. Unchecked Exception

2. Error

1) Checked Exception

The classes that directly inherit the


Throwable class except RuntimeException
and Error are known as checked exceptions.
For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-
time.

2) Unchecked Exception

The classes that inherit the


RuntimeException are known as unchecked
exceptions.

Example:

ArithmeticException(51/0)

NullPointerException(s=null)

ArrayIndexOutOfBoundsException,..

int a[]=new int[5];


a[10]=50;
//ArrayIndexOutOfBoundsException
Unchecked exceptions are not checked at
compile-time, but they are checked at
runtime.

3) Error

Error is irrecoverable. Some examples of


errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.

Java Exception Keywords:


Try:
The "try" keyword is used to specify a block
where we should place an exception code. It
means we can't use try block alone.
The try block must be followed by either catch
or finally.
If an exception occurs at the particular
statement in the try block, the rest of the
block code will not execute. So, it is
recommended not to keep the code in try
block that will not throw an exception.
Syntax:
try
{
//code that may throw an exception
}
○ Prints out exception description.

○ Prints the stack trace (Hierarchy of methods


where the exception occurred).

○ Causes the program to terminate.

Catch:
The "catch" block is used to handle the
exception.
It must be preceded by try block which
means we can't use catch block alone.
It can be followed by a finally block later.
Syntax:
catch(Exception e)
{
// Block of code to handle errors

Finally:
The "finally" block is used to execute the
necessary code of the program.
It is executed whether an exception is
handled or not.

Syntax:
finally(Exception e)
{
// Block of code to handle errors

Throw:
The "throw" keyword is used to throw an
exception.

Example1: Normal program


public class divison
{
public static void main(String[] args)
{
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at division.main(division.java:6)

Example2:
public class Exceptionhandle
{
public static void main(String args[])
{
try
{
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the
code...");
} }

Output:
java.lang.ArithmeticException: / by
zero
rest of the code...

Example3:
public class TryCatchExample
{
public static void main(String[] args)
{
try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw
exception
} // handling the array exception
catch(ArrayIndexOutOfBoundsException
e)
{
System.out.println(e);
}
System.out.println("rest of the code");
} }
Output:
java.lang.ArrayIndexOutOfBoundsException:
10
rest of the code
Java Multi-catch block

A try block can be followed by one or more


catch blocks. Each catch block must contain a
different exception handler. So, if you have
to perform different tasks at the occurrence
of different exceptions, use java multi-catch
block.

○ At a time only one exception occurs and


at a time only one catch block is
executed.

○ All catch blocks must be ordered from


most specific to most general, i.e. catch
for ArithmeticException must come before
catch for Exception.
Example:

public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{

int a[]=new int[5];


a[5]=30/0;

catch(ArithmeticException e)

System.out.println("Arithmetic Exception
occurs");

catch(ArrayIndexOutOfBoundsException e)

System.out.println("ArrayIndexOutOfBounds
Exception occurs");

catch(Exception e)
{

System.out.println("Parent
Exception occurs");

System.out.println("rest of the
code");

Output:

Arithmetic Exception occurs

rest of the code


Java Nested try block
In Java, using a try block inside another try
block is permitted. It is called as nested try
block. Every statement that we enter a
statement in try block, context of that
exception is pushed onto the stack.

Example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException
while the outer try block can handle the
ArithemeticException (division by zero).

Why use nested try block

Sometimes a situation may arise where a


part of a block may cause one error and the
entire block itself may cause another error.
In such cases, exception handlers have to be
nested.
Syntax:

....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}

}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
Example:
public class NestedTryBlock2
{
public static void main(String args[])
{ // outer (main) try block
try { //inner try block 1
try { // inner try block 2
try {
int arr[] = { 1, 2, 3, 4 };
//printing the array element out
of its bounds
System.out.println(arr[10]);
} // to handles
ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic
exception");
System.out.println(" inner try
block 2");
}
}

// to handle ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic
exception");
System.out.println("inner try block
1");
}
} // to handle
ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException
e4) {
System.out.print(e4);
System.out.println(" outer (main) try
block");
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main
try-block");
}
} }
Output:

public class NestedTryBlock


{
public static void main(String args[])
{ //outer try block
try
{ //inner try block 1
try
{
System.out.println("going to divide by 0");
int b =39/0;
} //catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
} //inner try block 2
try
{
int a[]=new int[5];//assigning the value out
of array bounds
a[5]=4;
} //catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
} //catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception
(outer catch)");
} System.out.println("normal flow..");
} }
Output:
Throw exception
The throw keyword is used to throw an
exception instance explicitly from a try block
to corresponding catch block.

That means it is used to transfer the control


from try block to corresponding catch block.

The throw keyword must be used inside the


try block.

When JVM encounters the throw keyword, it


stops the execution of try block and jump to
the corresponding catch block.

Note:
● Only one object can have a throwable
class or subclass.
● Only one exception can be throw
● It must follow by throwable instance

Syntax: throw instance


Example Throw exception
import java.util.Scanner;
public class Sample
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int a,b,r;
System.out.print("Enter any two numbers: ");
a= input.nextInt();
b = input.nextInt();
try
{
if(b == 0)
throw new ArithmeticException("Division by zero is not
possible");

r=a/b;
System.out.println(a+ "/" +b+ "=" +r);
}
catch(ArithmeticException ae)
{
System.out.println("Problem info: " +
ae.getMessage());
}
System.out.println("End of the program");
}
}
Output:
Enter any two numbers: 45
0
Problem info: Division by zero is not possible
End of the program

Throws Exception
The throws keyword specifies the exceptions that a
method can throw to the default handler and
does not handle itself.
It needs a method to throw an exception
automatically.
Note:
The getMessage() method of Throwable class is
used to return a detailed message of the
Throwable object which can also be null.
One can use this method to get the detail message
of exception as a string value.

Example for Throws Exception:


import java.util.Scanner;
public class ThrowsExample
{
int a,b,r;
Scanner input = new Scanner(System.in);
void division() throws ArithmeticException
{
System.out.print("Enter any two numbers: ");
a = input.nextInt();
b = input.nextInt();
r = a / b;
System.out.println(a+"/"+b +"="+r);
}
public static void main(String[] args)
{
try {
new ThrowsExample().division();
}
catch(ArithmeticException ae)
{
System.out.println("Problem info: " +
ae.getMessage());
}
System.out.println("End of the program");
}
}
Output:
Enter any two numbers: 25
0
Problem info: / by zero
End of the program

Finally Exception
The finally keyword is used to define a block that
must be executed irrespective of exception
occurence.
The basic purpose is to cleanup resources
allocated by try block, such as closing file,
closing database connection, etc.

Note:

1.Only one finally block is allowed for each try


block
2.Use of finally block is optional

Syntax: finally

{ block of codes}

Example:

import java.util.Scanner;
public class ThrowsExample
{
int a,b,r;
Scanner input = new Scanner(System.in);
void division() throws ArithmeticException
{
System.out.print("Enter any two numbers:
");
a = input.nextInt();
b = input.nextInt();
r = a / b;
System.out.println(a+"/"+b +"="+r);
}
public static void main(String[] args)
{
try {
new ThrowsExample().division();
}
catch(ArithmeticException ae)
{
System.out.println("Problem info: " +
ae.getMessage());

}
finally
{
System.out.println("finally block
execute always");
}
System.out.println("End of the
program"); }
}
Output:
Enter any two numbers: 5
0
Problem info: / by zero
finally block execute always
End of the program
Java’s Built-in Exceptions
The Java programming language has several built-
in exception classes that support exception
handling. Every exception class is suitable to
explain certain error situations at run time.
All the built-in exception classes in Java were
defined as a package java.lang.

Built-in Exception
Checked exceptions
1. ClassNotFoundException

It is thrown when the Java Virtual Machine


(JVM) tries to load a particular class and the
specified class cannot be found in the
classpath.

2. CloneNotSupportedException

Used to indicate that the clone method in


class Object has been called to clone an object,
but that the object's class does not implement
the Cloneable interface.
3. IllegalAccessException
It is thrown when one attempts to access a
method or member that visibility qualifiers do
not allow.
4. InstantiationException
It is thrown when an application tries to
create an instance of a class using the
newInstance method in class Class , but the
specified class object cannot be instantiated
because it is an interface or is an abstract
class.
5. InterruptedException
It is thrown when a thread that is sleeping,
waiting, or is occupied is interrupted.
6. NoSuchFieldException
It indicates that the class doesn't have a
field of a specified name.
7. NoSuchMethodException
It is thrown when some JAR file has a
different version at runtime that it had at
compile time, a NoSuchMethodException
occurs during reflection when we try to access
a method that does not exist.
Unchecked exceptions
1. ArithmeticException-Ex: division by zero(5/0)
2.ArrayIndexOutOfBoundsException-ilegal index
3.ArrayStoreException-invalid type of object.
4.AssertionError- an assertion has failed(true)
5.ClassCastException
6.IllegalArgumentException
7.IllegalMonitorStateException
8.IllegalStateException
9.IllegalThreadStateException
10. IndexOutOfBoundsException
11. NegativeArraySizeException
12. NullPointerException
13. NumberFormatException
14. SecurityException
15. UnsupportedOperationException
User defined Exception
To create our own exception class simply create
a class as a subclass of built-in Exception class.

● We may create a constructor in the user-


defined exception class and pass a string to
the Exception class constructor using super().
● We can use the getMessage() method to
access the string.

Example:

import java.util.Scanner;
class NotEligibleException extends Exception
{
NotEligibleException(String msg)
{
super(msg);
}
}
class VoterList
{
int age;
VoterList(int age)
{
this.age = age;
}
void checkEligibility()
{
try
{
if(age < 18)
{
throw new NotEligibleException("Error: Not
eligible for vote due to under age.");
}
System.out.println("Congrates! You are eligible for
vote.");

}
catch(NotEligibleException nee)
{
System.out.println(nee.getMessage())
;
}
}
public static void main(String args[])
{
Scanner input = new
Scanner(System.in);
System.out.println("Enter your age in
years: ");

int age = input.nextInt();


VoterList person = new VoterList(age);
person.checkEligibility();
}
}
Output1:Enter your age in years: 50
Congrates! You are eligible for vote.
Output2:Enter your age in years: 15
ERROR!
Error: Not eligible for vote due to under age.

Multithreaded Programming

To create a program that contains one or more


parts that can run simultaneously at the
same time.
This type of program is known as a
multithreading program. Each part of this
program is called a thread.
Every thread defines a separate path of execution
in java.
● A thread is a lightweight process.
● A thread is a sub part of a process that can run
individually.
Multiple threads can run at a time, which
enables the java to write multitasking
programs.
Multithreading is a specialized form of multitasking.
All modern operating systems support
multitasking. There are two types of multitasking.
● Process-based multitasking
● Thread-based multitasking

Process-based Thread-based
multitasking multitasking
It allows the It allows the
computer to run two computer to run two
or more programs or more threads
concurrently concurrently
Process is heavy Thread is a light
weight weight
It requires separate It requires same
address space address space
It cannot access over It can access over
idle time of CPU idle time of CPU
Interprocess Not expensive
communication is
expensive
Thread Life cycle
New state:
When a thread object is created using new, then
the thread is said to be the NEW state. It is also
called Born state.
Example: Thread t=new Thread();

Runnable / Ready
When a thread calls start( ) method, then the
thread is said to be in the Runnable state. This
state is also known as a Ready state.

Example: t.start();
Running
When a thread calls run( ) method, then the
thread is said to be Running.

The run( ) method of a thread called automatically


by the start( ) method.

Blocked / Waiting
A thread in the Running state may move into the
blocked state due to various reasons like sleep( )
method called, wait( ) method called, suspend( )
method called, and join( ) method called, etc.

When a thread is in the blocked or waiting state, it


may move to Runnable state due to reasons like
sleep time completed, waiting time
completed,notify() or notifyAll( ) method called,
resume( ) method called, etc.

Example:
Thread.sleep(1000);
wait(1000);
wait();
suspened();
notify();
notifyAll();

resume();

Dead / Terminated
A thread in the Running state may move into the
dead state due to either its execution completed or
the stop( ) method called. The dead state is also
known as the terminated state.

A thread is a lightweight process. Every java


program executes by a thread called the main
thread.

When a java program gets executed, the main


thread created automatically. All other threads
called from the main thread.

The java programming language provides two


methods to create threads, and they are listed
below.
● Using Thread class (by extending Thread
class)
● Uisng Runnable interface (by
implementing Runnable interface)

Extending Thread class


The java contains a built-in class Thread inside the
java.lang package. The Thread class contains all
the methods that are related to the threads.

To create a thread using Thread class, follow the


step given below.

● Step-1: Create a class as a child of the


Thread class. That means, create a class that
extends Thread class.
● Step-2: Override the run( ) method with the
code that is to be executed by the thread. The
run( ) method must be public while overriding.
● Step-3: Create the object of the newly created
class in the main( ) method.
● Step-4: Call the start( ) method on the object
created in the above step.

The Thread class has the following consructors.

● Thread( )
● Thread( String threadName )
● Thread( Runnable objectName )
● Thread( Runnable objectName, String
threadName )

Thread class contains the methods


The Thread class in java also contains methods like
stop( ), destroy( ), suspend( ), and resume( ).
But they are depricated.
Example
class SampleThread extends Thread
{
public void run()
{
System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++)
{ System.out.println("i = " + i); }
} }
class My_Thread_Test
{
public static void main(String[] args)
{
SampleThread t1 = new SampleThread();
System.out.println("Thread about to start...");
t1.start();
}
}
Output:
Thread about to start…
Thread is under Running...
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i = 10

Implementing Runnable interface


The java contains a built-in interface Runnable
inside the java.lang package.

The Runnable interface implemented by the Thread


class that contains all the methods that are
related to the threads.

To create a thread using Runnable interface, follow


the step given below.

● Step-1: Create a class that implements


Runnable interface.
● Step-2: Override the run( ) method with the
code that is to be executed by the thread.
The run( ) method must be public while
overriding.

● Step-3: Create the object of the newly created


class in the main( ) method.
● Step-4: Create the Thread class object by
passing the above created object as parameter
to the Thread class constructor.
● Step-5: Call the start( ) method on the
Thread class object created in the above step.

Example
class SampleThread implements Runnable
{
public void run()
{
System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++)
{
System.out.println("i = " + i);
}
}
}
class My_Thread_Test
{
public static void main(String[] args)
{
SampleThread threadObject = new
SampleThread();
Thread thread = new Thread(threadObject);
System.out.println("Thread about to start...");
thread.start();
}
}
OUTPUT:
Thread about to start...
Thread is under Running...
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i = 10

The Thread class has the following consructors.

● Thread( )
● Thread( String threadName )
● Thread( Runnable objectName )
● Thread( Runnable objectName, String threadName )

Return
Method Description Value

run( ) Defines actual task of the thread. void

start( ) It moves thre thread from Ready state to void


Running state by calling run( ) method.

setName(Strin Assigns a name to the thread. void


g)

getName( ) Returns the name of the thread. String


setPriority(int) Assigns priority to the thread. void

getPriority( ) Returns the priority of the thread. int

getId( ) Returns the ID of the thread. long

activeCount() Returns total number of thread under active. int

currentThread( Returns the reference of the thread that void


) currently in running state.

sleep( long ) moves the thread to blocked state till the void
specified number of milliseconds.

isAlive( ) Tests if the thread is alive. boolean

yield( ) Tells to the scheduler that the current thread void


is willing to yield its current use of a
processor.

join( ) Waits for the thread to end. void

Thread class provides two methods setPriority(int), and getPriority( ) to


handle thread priorities.
The Thread class also contains three constants that are used to set the
thread priority, and they are listed below.

● MAX_PRIORITY - It has the value 10 and indicates highest priority.


● NORM_PRIORITY - It has the value 5 and indicates normal priority.
● MIN_PRIORITY - It has the value 1 and indicates lowest priority.

Example
class SampleThread extends Thread
{
public void run()
{
System.out.println("Inside SampleThread");
System.out.println("Current Thread: " +
Thread.currentThread().getName());
}
}
class My_Thread_Test
{
public static void main(String[] args)
{
SampleThread threadObject1 = new
SampleThread();
SampleThread threadObject2 = new
SampleThread();
threadObject1.setName("first");
threadObject2.setName("second");
threadObject1.setPriority(4);
threadObject2.setPriority(Thread.MAX_PRIORITY
);
threadObject1.start();
threadObject2.start();

}
}
OUTPUT:
Inside SampleThread
Inside SampleThreadCurrent Thread: first
Current Thread: second

Synchronization in Multithreading
Wrapper Classes
A Wrapper class in Java is a class whose object
wraps or contains primitive data types.
It can convert primitive data into
corresponding objects.
When we create an object to a wrapper class, it
contains a field and in this field, it can store
primitive data types.
It can wrap a primitive value into a wrapper
class object.
Need of Wrapper Classes
They convert primitive data types into
objects. Objects are needed if you wish to modify
the arguments passed into a method (because
primitive types are passed by value).
The classes in java.util package handles only
objects and hence wrapper classes help in this
case also.
Data structures in the Collection framework,
such as ArrayList and Vector, store only objects
(reference types) and not primitive types.
An object is needed to support
synchronization in multithreading.
Advantages:-
● Collections allowed only object data.
● On object data we can call multiple
methods compareTo(), equals(), toString()
● Cloning process only objects
● Object data allowed null values.
● Serialization can allow only object data.

Primitive Data Type Wrapper Class


char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean

Wrapper class Example


class Main {
public static void main(String[] args) {

// create primitive types


int a = 5;
double b = 5.65;

//converts into wrapper objects


Integer aObj = Integer.valueOf(a);
Double bObj = Double.valueOf(b);

if(aObj instanceof Integer) {


System.out.println("An object of Integer is
created.");
}

if(bObj instanceof Double) {


System.out.println("An object of Double is
created.");
}
}
}
OUTPUT:
An object of Integer is created.
An object of Double is created.

Unwrapper class example


class Main
{
public static void main(String[] args)
{
// creates objects of wrapper class
Integer aObj = Integer.valueOf(23);
Double bObj = Double.valueOf(5.55);
// converts into primitive types
int a = aObj.intValue();
double b = bObj.doubleValue();
System.out.println("The value of a: " + a);
System.out.println("The value of b: " + b);
}
}
Output:
The value of a: 23
The value of b: 5.55

1. Autoboxing
The automatic conversion of primitive types to the
object of their corresponding wrapper classes is
known as autoboxing.
For example – conversion of int to Integer, long to
Long, double to Double, etc.
// Java program to demonstrate Autoboxing
import java.util.ArrayList;
class Autoboxing
{
public static void main(String[] args)
{
char ch = 'a';
// Autoboxing- primitive to Character object conversion

Character b = ch;
ArrayList<Integer> al= new
ArrayList<Integer>();
// Autoboxing because ArrayList stores only
objects
al.add(25);
// printing the values from object
System.out.println(al.get(0));
}
}
Output: 25

2. Unboxing
It is just the reverse process of autoboxing.
Automatically converting an object of a wrapper
class to its corresponding primitive type is known
as unboxing.
For example – conversion of Integer to int, Long
to long, Double to double, etc.
// Java program to demonstrate Unboxing
import java.util.ArrayList;
class Unboxing
{
public static void main(String[] args)
{
Character ch = 'a';
// unboxing - Character object to primitive conversion
char a = ch;
ArrayList<Integer> al= new
ArrayList<Integer>();
al.add(24);
// unboxing because get method returns an Integer object
int num = al.get(0);
// printing the values from primitive data types
System.out.println(num);
}
}
Output: 24
Q1. Which of these is a wrapper for data type int?

Integer
Long
Byte
Double
Q2. Which of the following methods is a method of wrapper
Integer for obtaining hash code for the invoking object?

int hash()
int hashcode()
int hashCode()
Integer hashcode()
Q3. Which of these methods is used to obtain the value of
invoking object as long?

long value()
long longValue()
Long longvalue()
Long Longvalue()
Q4. What will be the output of the following Java program?
class Output
{
public static void main(String args[])
{
char a[] = {'a', '5', 'A', ' '};
System.out.print(Character.isDigit(a[0]) + "
");
System.out.print(Character.isWhitespace(a
[3]) + " ");
System.out.print(Character.isUpperCase(a[
2]));
}
}
true false true
false true true
true true false
false false false

Q5. Choose a correct statement about Autoboxing in Java.

Boxing is the process of converting primitive data to its


equivalent Wrapper class type
Unboxing is the process of converting a Wrapper class
object to its equivalent primitive data type
Autoboxing is the process of converting the Primitive data
type to the Wrapper Object type automatically. Auto-
Unboxing is the process of converting a Wrapper type
object to a Primitive type automatically.
All the above
Q6. Which does autoboxing or unboxing in Java?

Compiler
Runtime
Third-party tools
None
Q7. Choose the right statement which does autoboxing in Java.

Integer temperature1 = 100;


int temperature2 = 101;
Integer temperature1 = 100;int temperature2 = 101;
All the above
Q8. Does the below Java code undergo autoboxing correctly?
long weight = 10;
Long wei = weight;
System.out.println(ch.SIZE);
Yes
No
Q9. Autoboxing or Auto-unboxing works with ___ in Java.

Ternary Operator
If-else statements
Loops and Switch
All the above
Q10. What will be the output of the following Java program?
class Output
{
public static void main(String args[])
{
Long i = new Long(256);
System.out.print(i.hashCode());
}
}

256
256.0
256.00
257.00
Answer Key & Solution
Q1 Integer
Q2 int hashCode()
Q3 long longValue()
Q4 false true true
Q5 All the above
Q6 Compiler
Q7 Integer temperature1 = 100;
Q8 Yes
Q9 All the above
Q10 256

EXAMPLE:

Write a program to explain the


concept of wrapper class with
autoboxing.
import java.util.*;
public class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
char ch ;
ch = sc.next().charAt(0);
Character chrobj = Character.valueOf(ch);
byte a ;
a = sc.nextByte();
Byte byteobj = Byte.valueOf(a);
System.out.println("Displaying values of Wrapper
class objects:");
System.out.println("Character object: " + chrobj);
System.out.println("Byte object: " + byteobj);
char chr = chrobj;
byte by = byteobj;
System.out.println("Displaying unwrapped values:
");
System.out.println("char value: " + chr);
System.out.println("byte value: " + by);
}
}

Input Format
The first input must be a character
The second input must be a byte value
Output Format
Refer sample output for the format specifications
Sample Input
w
120

Sample Output
Displaying values of Wrapper class objects:
Character object: w
Byte object: 120
Displaying unwrapped values:
char value: w
byte value: 120

Inter Thread Communication


To know about thread basic click this link

Inter-thread communication or Co-


operation is all about allowing synchronized
threads to communicate with each other.
Cooperation (Inter-thread communication) is a
mechanism in which a thread is paused running
in its critical section and another thread is
allowed to enter (or lock) in the same critical
section to be executed.
Object class:
1. wait()
2. notify()
3. notifyall()

1. Threads enter to acquire lock.

2. Lock is acquired by on thread.

3. Now the thread goes to waiting state if you call


wait() method on the object. Otherwise it
releases the lock and exits.

4. If you call notify() or notifyAll() method, the


thread moves to the notified state (runnable
state).
5. Now thread is available to acquire lock.

6. After completion of the task, thread releases


the lock and exits the monitor state of the
object.
1.public void wait()
Causes the current thread to wait until
another thread invokes the notify().
2.public void notify()
Wakes up a single thread that is
waiting on this object's monitor.
3.public void notifyAll()
Wakes up all the threads that are called
wait( ) on the same object.
Example:
class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");

try{wait();}
catch(Exception e)
{}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}
}
Output:
going to withdraw…
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed...

Compare wait() and sleep()


Suspending –Resuming, and
Stopping Threads.
1.public void suspend()
This method puts a thread in the suspended
state and can be resumed using resume()
method.
2.public void stop()
This method stops a thread completely.
3.public void resume()
This method resumes a thread, which was
suspended using suspend() method.
public final void resume()
4.public void wait()
Causes the current thread to wait until another
thread invokes the notify().
5.public void notify()
Wakes up a single thread that is waiting on this
object's monitor.
To learn more about Thread method click this link

MCQ TEST
Q1. The wait(), notify(), and notifyAll( ) methods can be called from?

All Synchronized block/method


Only Static synchronized block/method
Only Synchronized Block
Only Synchronized Method
Q2. When a thread calls the wait() method, which of the following options is valid?

The thread will immediately release the lock of that particular object and enter
into the waiting state.
Immediately the thread will enter into the waiting state without releasing any
lock.
The thread will release the lock of that object but may not immediately.
The thread will release all acquired locks and immediately enter the waiting
state.
Q3. Below “line-1” is valid or not?
Stack s1 = new Stack();
Stack s2 = new Stack();
synchronized(s2)
{
s1.wait(); // line-1
}
Valid
Invalid
Valid only in Windows OS
None of these
Q4. The wait( ) method throws which of the following Exception?

IllegalMonitorStateException
InterruptedException
It doesn’t throw any exceptions
None of these
Q5. After calling the wait() method thread went to the waiting state, and it will come out
of this waiting state on which events?

If the waiting thread got a notification


If time expires
If the waiting thread got interrupted
All of these
Q6. Find the output of the below program.
public class Test
{
public static void main(String[] args)
{
MyThread t = new MyThread();
t.start();
synchronized(t)
{
System.out.print("A");
try
{
t.wait();
} catch (InterruptedException e) { }
System.out.print("B");
System.out.print(t.total);
}
}
}
class MyThread extends Thread
{
int total = 0;
public void run()
{
synchronized (this)
{
System.out.print("C");
for (int i=0; i<=10; i++)
{
total = total + i;
}
System.out.print("D");
this.notify();
}
}
}

ABCD55
ACB55D
ACDB55
ACBD55
Q7. The method wait() is a

static method
non-static method
Q8. Inter-thread communication is all about allowing _________ threads to communicate
with each other.

synchronized
non-synchronized
Q9. What is synchronization in reference to a thread?

It’s a process of handling situations when two or more threads need access to
a shared resource
It’s a process by which many threads are able to access the same shared
resource simultaneously
It’s a process by which a method is able to access many different threads
simultaneously
It’s a method that allows too many threads to access any information they
require
Q10. Mutual exclusive and inter-thread communication are which types of
Synchronization?

Thread Synchronization
Process Synchronization
Object Synchronization
None of the above
Answer Key & Solution
Q1 All Synchronized block/method
Q2 The thread will immediately release the lock of that particular object and enter into the
waiting state.
Q3 Invalid
Q4 InterruptedException
Q5 All of these
Q6 ACDB55
Q7 non-static method
Q8 synchronized
Q9 It’s a process of handling situations when two or more threads need access to a shared
resource
Q10 Thread Synchronization

You might also like