OOP thr Java-UNIT 3
OOP thr Java-UNIT 3
UNIT-III
When an exception occurs, it disrupts the program execution flow. When an exception
occurs, the program execution gets terminated, and the system generates an error. We use
the exception handling mechanism to avoid abnormal termination of program execution.
Java programming language has a very powerful and efficient exception handling mechanism
with a large number of built-in classes to handle most of the exceptions automatically.
There are many cases where abnormal conditions happen during program execution, suchas
When we try to open a file that does not exist may lead to an exception.
When the user enters invalid input data, it may lead to an exception.
When a network connection has lost during the program execution may lead to an
exception.
When we try to access the memory beyond the allocated range may lead to an
exception.
The physical device problems may also lead to an exception.
The exception object contains information about the exception including its type and the
state of the program when the error occurred.
In java, the exception handling mechanism uses five keywords such as try, catch, finally,
throw and throws.
Termination Model
In the termination model, when a method encounters an exception, further processing in
that method is terminated and control is transferred to the nearest catch block that can
handle the type of exception encountered.
In other words we can say that in termination model the error is so critical there is no way to
get back to where the exception occurred.
Presumptive Model
The alternative of termination model is presumptive model. In presumptive model, the
exception handler is expected to do something to stable the situation, and then the faulting
method is retried. In presumptive model we hope to continue the execution after the
exception is handled.
In presumptive model we may use a method call that want resumption like behaviour. We
may also place the try block in a while loop that keeps re-entering the try block until the
result is satisfactory.
Exception Hierarchy
The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited
by two subclasses: Exception and Error.
Try Block
No Exception
arise or
No Catch Block
Exceptional Handler
appropriate
Catch
block
Finally Block
Optional part
class Exception
{
public static void main(String args[])
{
int d = 0;
Checked Exception
The checked exception is an exception that is checked by the compiler during the
compilation process to confirm whether the exception is handled by the programmer or not.
If it is not handled, the compiler displays a compilation error using built-in classes.
The checked exceptions are generally caused by faults outside of the code itself like missing
resources, networking errors, and problems with threads come to mind.
The following are a few built-in classes used to handle checked exceptions in java.
IOException
FileNotFoundException
ClassNotFoundException
SQLException
DataAccessException
InstantiationException
UnknownHostException
In the exception class hierarchy, the checked exception classes are the direct children of the
exception class. The checked exception is also known as a compile-time exception.
Example
import java.io.*;
Unchecked Exception
The unchecked exception is an exception that occurs at the time of program execution. The
unchecked exceptions are not caught by the compiler at the time of compilation.
The unchecked exceptions are generally caused due to bugs such as logic errors, improper
use of resources, etc.
The following are a few built-in classes used to handle unchecked exceptions in java.
ArithmeticException
NullPointerException
NumberFormatException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
In the exception class hierarchy, the unchecked exception classes are the children of the
RuntimeException class which is a child class of Exception class. The unchecked exception is
also known as a run-time exception
Example
public class UncheckedException
{
public static void main(String[] args)
{
int list[] = {10, 20, 30, 40, 50};
System.out.println(list[6]); //ArrayIndexOutOfBoundsException
String msg=null;
System.out.println(msg.length()); //NullPointerException
String name="abc";
int i=Integer.parseInt(name); //NumberFormatException
}
}
OUTPUT
D:\TKREC\Java>java UncheckedException
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out
of bounds for length 5 at UncheckedException.main(UncheckedException.java:4)
Keyword Description
try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or
finally. It means, we can't use try block alone.
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 finally block later
finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw
an exception. It specifies that there may occur an exception in the
method. It is always used with method signature
The keyword catch is used to define a block of code that handles the exception occurred in
the respective try block. Both try and catch are used as a pair. Every try block must have one
or more catch blocks. We cannot use try without at least one catch, and catch alone can be
used (catch without try is not allowed).
Example
import java.util.Scanner;
OUTPUT:
D:\TKREC\Java>java TryCatchExample
Enter the a and b values:
5
0
Problem info: Value of divisor cannot be ZERO
class TryCatch
{
public static void main(String args[])
{
int[] no={1,2,3};
try
{
System.out.println(no[3]); //may throw exception
}
//handling the exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Out of bounds");
}
System.out.println("Quit");
}
}
OUTPUT:
D:\TKREC\Java>javac TryCatch.java
D:\TKREC\Java>java TryCatch
Out of bounds
Quit
The multiple catch clauses are defined when the try block contains the code that may lead to
different type of exceptions. The try block generates only one exception at a time, and at a
time only one catch block is executed.
When there are multiple catch blocks, the order of catch blocks must be from the most
specific exception handler to most general. The catch block with Exception class handler
must be defined at the last.
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
In case of nested try blocks, if an exception occured in the inner try block and it's catch
blocks are unable to handle it then it transfers the control to the outer try's catch block to
handle it.
// NestedTry Example
public class NestedTryExample
{
public static void main(String[] args)
{
try
{
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[0] = list[2] / list[4];
try
{
list[10] = 100;
}
catch(ArrayIndexOutOfBoundsException aie)
{
System.out.println("Problem info: ArrayIndexOutOfBoundsException has occured.");
}
}
catch(ArithmeticException ae)
{
System.out.println("Problem info: Value of divisor cannot be ZERO.");
}
catch(Exception e)
{
System.out.println("Problem info: Unknown exception has occured.");
}
}
}
OUTPUT:
D:\TKREC\Java>java NestedTryExample
Problem info: ArrayIndexOutOfBoundsException has occured.
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.
Using throw keyword only object of Throwable class or its sub classes can be thrown.
Using throw keyword only one exception can be thrown.
The throw keyword must followed by an throwable instance.
The following is the general syntax for using throw keyword in a try block.
throw instance;
Here the instance must be throwable instance and it can be created dynamically using new
operator.
// Throw Example
class ThrowExample
{
public static void divideByZero()
{
throw new ArithmeticException("Trying to divide by 0");
}
public static void main(String[] args)
{
divideByZero();
}
}
OUTPUT:
D:\TKREC\Java>java ThrowExample
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
at ThrowExampke.divideByZero(ThrowExample.java:8)
at ThrowExample.main(ThrowExample.java:13)
class ThrowExample2
{
void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("Welcome to vote");
}
public static void main(String[] args)
{
ThrowExample2 obj=new ThrowExample2();
D:\TKREC\Java>java ThrowExample2
Welcome to vote
Rest of code
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}
OUTPUT:
D:\TKREC\Java>java ThrowsDemo
Inside throwOne.
class ThrowsExample
{
void validate(int age) throws ArithmeticException
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("Welcome to vote");
}
public static void main(String[] args)
{
try
{
ThrowsExample obj=new ThrowsExample();
obj.validate(13);
//obj.validate(19);
}
catch(ArithmeticException e)
{
System.out.println("e");
}
System.out.println("Rest of code");
}
}
OUTPUT:
D:\TKREC\Java>java ThrowsExample
e
Rest of code
D:\TKREC\Java>java ThrowsExample
Welcome to vote
Rest of code
import java.io.*;
class ThrowsDemoFiles
{
public static void findFile() throws IOException
{
// code that may produce IOException
File newFile=new File("test.txt");
FileInputStream stream=new FileInputStream(newFile);
}
public static void main(String[] args)
{
try
When we run this program, if the file test.txt does not exist, FileInputStream throws a
FileNotFoundException which extends the IOException class.
If a method does not handle exceptions, the type of exceptions that may occur within it must
be specified in the throws clause so that methods further up in the call stack can handle them
or specify them using throws keyword themselves.
The findFile() method specifies that an IOException can be thrown. The main() method calls
this method and handles the exception if it is thrown.
OUTPUT:
D:\TKREC\Java>javac ThrowsDemoFiles.java
D:\TKREC\Java>java ThrowsDemoFiles
java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
class FinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/5;
// int data=25/0
System.out.println(data);
}
catch(NullPointerException e)
{
P.Ramesh, Assistant Professor, AIML Dept, 15
TKREC
OOP through Java UNIT-3
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
OUTPUT:
D:\TKREC\Java>java FinallyBlock
5
finally block is always executed
rest of the code...
D:\TKREC\Java>java FinallyBlock
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at FinallyBlock.main(FinallyBlock.java:9)
The throws keyword is used to declare which exceptions can be thrown from a method,
while the throw keyword is used to explicitly throw an exception within a method or block of
code. The throws keyword is used in a method signature and declares which exceptions can
be thrown from a method
Since java.lang is implicitly imported into all Java programs, most exceptions derived from
RuntimeException are automatically available
Table 10-2 lists those exceptions defined by java.lang that must be included in a method’s
throws list if that method can generate one of these exceptions and does not handle it itself.
These are called checked exceptions.
Java defines several other types of exceptions that relate to its various class libraries
The Java programming language allow us to create our own exception classes which are
basically subclasses built-in class Exception. To create our own exception class simply create
a class as a subclass of built-in Exception class.
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user
need. By the help of custom exception, you can have your own exception and message.
We may create constructor in the user-defined exception class and pass a string to Exception
class constructor using super(). We can use getMessage() method to access the string.
void checkEligibility()
{
try
{
if(age < 18)
{
throw new NotEligibleException("Error: Not eligible for vote due to under age.");
}
System.out.println("Congrats! 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 obj = new VoterList(age);
obj.checkEligibility();
}
}
OUTPUT:
D:\TKREC\Java>java VoterList
Enter your age in years:
25
Congrats! You are eligible for vote.
D:\TKREC\Java>java VoterList
Enter your age in years:
12
Error: Not eligible for vote due to under age.
It is probably the most commonly used class in java library. In java, every string that we
create is actually an object of type String. One important thing to notice about string object is
that string objects are immutable that means once a string object is created it cannot be
changed.
Example
String siteName = "JavaProgram.com";
siteName = "JavaProgram.com";
Exploring java.util.
Multithreading
Multithreading in java is a process of executing multiple threads simultaneously
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking
As shown in the above figure, a thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS, and one
process can have multiple threads.
Java Thread class: - Java provides Thread class to achieve thread programming. Thread
class provides constructors and methods to create and perform operations on a thread.
(OR)
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.
Ex: - t1.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.
Ex: -
Thread.sleep(100);
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.
Creating threads
In java, 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)
Using 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 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.
P.Ramesh, Assistant Professor, AIML Dept, 25
TKREC
OOP through Java UNIT-3
Step-4: Call the start( ) method on the object created in the above step.
Example: -
OUTPUT: -
D:\TKREC\Java>java ThreadDemo1
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 above created object as parameter
to the Thread class constructor.
Example: -
class MultiThread
{
public static void main(String args[])
{
new MyThread("One");
new MyThread("Two");
new MyThread("Three");
try {
Thread.sleep(10000);
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
OUTPUT: -
D:\TKREC\Java>java MultiThread
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Three: 5
Two: 5
One: 4
Two: 4
Three: 4
One: 3
Two: 3
Three: 3
One: 2
Two: 2
Three: 2
class CurrentThread
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
Interrupting threads
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the
interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException. If the thread is not in the sleeping or waiting state, calling the
interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the
interrupt flag to true. Let's first see the methods provided by the Thread class for thread
interruption.
Example of interrupting a thread that stops working: - After interrupting the thread, we
are propagating it, so it will stop working. If we don't want to stop the thread, we can handle
it where sleep() or wait() method is invoked. Let's first see the example where we are
propagating the exception
Example of interrupting a thread that doesn’t stops working: - After interrupting the
thread, we handle the exception, so it will break out the sleeping but will not stop working.
Thread Priority
In a java programming language, every thread has a property called priority. Most of the
scheduling algorithms use the thread priority to schedule the execution sequence. In java,
the thread priority range from 1 to 10. Priority 1 is considered as the lowest priority, and
priority 10 is considered as the highest priority. The thread with more priority allocates the
processor first.
The java programming language 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.
setPriority( ) method: - The setPriority( ) method of Thread class used to set the priority of
a thread. It takes an integer range from 1 to 10 as an argument and returns nothing (void).
The regular use of the setPriority( ) method is as follows.
getPriority( ) method:- The getPriority( ) method of Thread class used to access the
priority of a thread. It does not takes any argument and returns name of the thread as String.
The regular use of the getPriority( ) method is as follows.
Example:-
String threadName = threadObject.getPriority();
Note: In java, it is not guaranteed that threads execute according to their prority because it
depends on JVM specification that which scheduling it chooses
P.Ramesh, Assistant Professor, AIML Dept, 32
TKREC
OOP through Java UNIT-3
// Thread Priority
class SampleThread extends Thread
{
public void run()
{
System.out.println("Inside SampleThread");
System.out.println("Current Thread: " + Thread.currentThread().getName());
}
}
public class ThreadProrityDemo
{
public static void main(String[] args)
{
SampleThread threadObject1 = new SampleThread();
SampleThread threadObject2 = new SampleThread();
threadObject1.setName("first");
threadObject2.setName("second");
threadObject1.start();
threadObject2.start();
}
}
OUTPUT: -
D:\TKREC\Java>java ThreadProrityDemo
Inside SampleThread
Inside SampleThread
Current Thread: first
Current Thread: second
// MultiThread Priority
class MultiThreadPriority extends Thread
{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
}
class ThreadPriorityDemo1
{
public static void main(String args[])
{
MultiThreadPriority m1=new MultiThreadPriority ();
MultiThreadPriority m2=new MultiThreadPriority ();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
Synchronized keyword in java creates a block of code as critical section, to enter a critical
section a thread needs to obtain the corresponding objects Lock.
class Table
{
//synchronized method
synchronized void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
}
}
}
import java.io.*;
import java.util.*;
// Driver class
class SynchronizationDemo1
{
public static void main(String args[])
{
Sender snd = new Sender();
MyThread S1 = new MyThread( " Hi " , snd );
MyThread S2 = new MyThread( " Bye " , snd );
OUTPUT: -
D:\TKREC\Java>java SynchronizationDemo1
Sending Hi
Hi Sent
Sending Bye
Bye Sent
wait() method:- Causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed. The current thread must own this object's monitor, so it must be
called from the synchronized method only otherwise it will throw exception.
Method Description
public final void wait()throws waits until object is notified.
InterruptedException
public final void wait(long Waits for the specified amount of time
timeout)throws InterruptedException
notify() method:- Wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened. The choice is
arbitrary and occurs at the discretion of the implementation.
Syntax:
public final void notify()
notifyAll() method:- Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class? It
is because they are related to lock and object has a lock.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock
wait() method is the method of Object sleep() method is the method of Thread
class class
wait() method is the non-static method sleep() method is the static method
wait() method should be notified by sleep() method after the specified
notify() or notifyAll() methods amount of time, sleep is completed
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...");
}
this.amount-=amount;
System.out.println("going to deposit...");
}
synchronized void deposit(int amount)
{
System.out.println("deposit completed... ");
this.amount+=amount;
System.out.println("withdraw completed...");
notify();
}
}
class InterThreadCommunicationDemo
P.Ramesh, Assistant Professor, AIML Dept, 38
TKREC
OOP through Java UNIT-3
{
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: -
D:\TKREC\Java>java InterThreadCommunicationDemo
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed...
Thread groups
Java provides a convenient way to group multiple threads in a single object. In such a way,
we can suspend, resume or interrupt a group of threads by a single method call.
A thread is allowed to access information about its own thread group, but it cannot access
the information about its thread group's parent thread group or any other thread groups.
Constructor Description
ThreadGroup(String name) Creates a thread group with given name.
ThreadGroup(ThreadGroup Creates a thread group with a given parent
parent, String name) group and name.
Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is
the class that implements Runnable interface and "one", "two" and "three" are the thread
names.
// Threadgroup Example
Daemon threads.
Daemon thread in Java is a service provider thread that provides services to the user thread.
Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM
terminates this thread automatically. There are many java daemon threads running
automatically e.g. gc, finalizer etc.
The jconsole tool provides information about the loaded classes, memory usage, running
threads etc.
The java.lang.Thread class provides two methods for java daemon thread.
//starting threads
t1.start();
t2.start();
t3.start();
}
Note: If you want to make a user thread as Daemon, it must not be started otherwise it will
throw IllegalThreadStateException.
Enumerations
An enumeration is a list of named constants. Java enumerations appear similar to
enumerations in other languages.
In java, an Enum(short for enumeration) is a special data type in Java that contains a fixed
set of constants. Enum is a special kind of class that extends the java.lang.Enum class.
Enums allow us to know all the possible values for a field at the compile-time and make our
code more readable. We can use them to avoid undesirable behavior due to invalid inputs.
For example, an enum of directions can only have four possible values - north, south, east,
and west.
In java, the enumeration concept was defined based on the class concept. When
All the constants of an enum are public, static, and final. As they are static, we
can access directly using enum name.
The main objective of enum is to define our own data types in Java, and they
are said to be enumeration data types.
In java, an enum can be defined outside a class, inside a class, but not inside a
method.
enum Apple
{
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
Let's look at the following example program for creating a basic enum.
enum WeekDay
{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
Every enum is converted to a class that extends the built-in class Enum.
Every constant of an enum is defined as an object.
enum WeekDay
{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY("Holiday");
String msg;
WeekDay()
{
System.out.println("Default constructor!");
}
WeekDay(String str)
{
System.out.println("\n Parameterized constructor!");
msg = str;
}
}
Parameterized constructor!
In the above example, the constant SUNDAY is created by calling the parameterized
constructor, other constants created by calling default constructor.
class EnumDemo
{
public static void main(String args[])
{
Apple ap;
System.out.println("Here are all Apple constants:");
ap contains Winesap
Autoboxing
In java, all the primitive data types have defined using the class concept, these
classes known as wrapper classes. In java, every primitive type has its
corresponding wrapper class.
All the wrapper classes in Java were defined in the java.lang package.
The following table shows the primitive type and its corresponding wrapper
class.
2 short Short
3 int Integer
4 long Long
5 float Float
6 double Double
7 char Character
8 boolean Boolean
The Java 1.5 version introduced a concept that converts primitive type to
corresponding wrapper type and reverses of it.
Autoboxing in Java
In java, the process of converting a primitive type value into its corresponding
wrapperclass object is called autoboxing or simply boxing.
The compiler automatically performs the autoboxing when a primitive type value
has assigned to an object of the corresponding wrapper class.
We can also perform autoboxing manually using the method valueOf( ), which
is provided by every wrapper class.
import java.lang.*;
We can also perform auto un-boxing manually using the method intValue( ),
which is provided by Integer wrapper class. Similarly every wrapper class has a
method for auto un-boxing.
import java.lang.*;
Annotations
An annotation is created through a mechanism based on the interface.
An annotation cannot include extends clause. However, all annotation types automatically
extend the Annotation interface. Thus, Annotation is a super-interface of all annotations. It
is declared within the java.lang.annotation package. It overrides hashCode( ), equals( ),
and toString( ), which are defined by Object. It also specifies annotationType( ), which
returns a Class object that represents the invoking annotation
Here is a program that assembles all of the pieces shown earlier and uses reflection to
display the annotation associated with a method.
// Example
import java.lang.annotation.*;
import java.lang.reflect.*;
Generics
The java generic is a language feature that allows creating methods and class which
can handle any type of data values. The generic programming is a way to write
generalized programs, java supports it by java generics.
The java generic is similar to the templates in the C++ programming language.
Most of the collection framework classes are generic classes.
The java generics allows only non-primitive type, it does not support primitive
typeslike int, float, char, etc.
The java generics feature was introduced in Java 1.5 version. In java, generics
usedangular brackets “< >”.
Just like classes, methods in Java can also take a type parameter. This will enable us to use
the same method for different object types.
Consider the code below, which uses a Generic print() method to print an object. <T> in the
method definition, tells Java that this is a Generic method with parameter type T. We can use
this type T anywhere in the method implementation. The diamond operator must be used
even if the method returns void.
print(s);
print(i);
print(d);
}
}
OUTPUT:
D:\TKREC\Java>java GenericsDemo
100
100
100.0
import java.util.ArrayList;
import java.util.LinkedList;
A generic class declaration looks like a non-generic class declaration, except that
theclass name is followed by a type parameter section.
class GenericDemoClass
{
public static void main (String[] args)
{
Gen < Integer> iob = new Gen<>(100); //instance of Integer type Gen Class
int x = iob.getOb();
System.out.println(x);
Gen < String> sob = new Gen<>("Hello"); //instance of String type Gen Class
String str = sob.getOb();
System.out.println(str);
}
}
OUTPUT:
D:\TKREC\Java>java GenericDemoClass
100
Hello