OOP Java - Unit 3
OOP Java - Unit 3
OBJECT ORIENTED
PROGRAMMING THROUGH JAVA
UNIT-3
Prepared by GSK
gets terminated. In such cases we get a system
generated error message.
The good thing about exceptions is that they can
be handled by programmers also.
By handling the exceptions we can provide a
meaningful message to the user about the
3
issue rather than a system generated message.
The problem with the exception is, it terminates
the program and skip rest of the execution
that means if a program have 100 lines of code
and at line 10 an exception occur then
Prepared by GSK
program will terminate immediately by
skipping execution of rest 90 lines of code.
Prepared by GSK
For example:
Prepared by GSK
Checked Exception:
The exception that can be predicted at the compile time.
The checked exceptions are generally caused by faults
outside of the code itself like missing resources,
networking errors.
Example : File that need to be opened is not found,
SQLException etc. These type of exceptions must be
7
checked at compile time.
TYPES OF EXCEPTIONS CONTD..
Unchecked Exception:
Prepared by GSK
and checked at runtime. The unchecked exceptions
are generally caused due to bugs such as logic
errors.
Examples:
❑ ArithmeticException,
❑ NullPointerException, 8
❑ ArrayIndexoutofBound exception.
Prepared by GSK
9
Prepared by GSK
Hierarchy of 10
Exception Classes
UNCAUGHT EXCEPTION
class UncaughtException
{
public static void main(String args[])
{
Prepared by GSK
As we don't have any mechanism for
int a = 0; handling exception in this program,
hence the default handler (JVM) will
int b = 7/a; //exception handle the exception and will print
} the details of the exception on the
terminal.
}
11
HOW TO HANDLE EXCEPTION
Prepared by GSK
try : It is used to enclose the suspected code.
catch: It acts as exception handler.
finally: It is used to execute necessary code.
throw: It throws the exception explicitly.
throws: It informs for the possible Exception.
12
TRY AND CATCH IN JAVA
Try and catch both are Java keywords and used
for exception handling.
Prepared by GSK
The try block is used to enclose the suspected code.
Suspected code is a code that may raise an
exception during program execution.
try
{
int a = 10;
int b = 0
int c = a/b; // exception 13
}
TRY AND CATCH IN JAVA CONTD..
Prepared by GSK
It handles the exception thrown by the code
enclosed into the try block.
The catch block must be used after the try
block only.
We can also use multiple catch block with a
single try block.
14
try
{
int a = 10;
int b = 0
Prepared by GSK
int c = a/b; // exception
}
catch(ArithmeticException e)
{
System.out.println(e);
15
}
//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try
Prepared by GSK
{
String a = null; //null value
System.out.println(a.charAt(0));
}
catch(NullPointerException e)
{
System.out.println("NullPointerException..");
}
}
} Output: 16
NullPointerException..
NULLPOINTEREXCEPTION
Prepared by GSK
The program tries to access the first character
of the string using a.charAt(0), which causes a
NullPointerException because a is null.
Prepared by GSK
attempts to use an object reference that has the
null value.
null is a special value used in Java.
It is mainly used to indicate that no value is
assigned to a reference variable.
One application of null is in implementing data
18
structures like linked list and tree
Example: Handling Arithmetic Exception
class Exception Output:
{
Divided by zero
public static void main(String args[])
{ After exception is handled
int a,b,c; Output:
try Divided by zero
Prepared by GSK
{ After exception is handled
a = 0;
b = 10;
c = b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled"); 19
}
}
EXECUTION PROCEDURE
An exception will thrown by this program as we
are trying to divide a number by zero
inside try block.
Prepared by GSK
The program control is transferred
outside try block. Thus the line "This line will not
be executed" is never parsed by the compiler.
The exception thrown is handled in catch block.
Prepared by GSK
exception occurrence.
The basic purpose of finally keyword is to
cleanup resources allocated by try block, such
as closing file, closing database connection,
etc.
Use of finally block is optional 21
MULTIPLE CATCH CLAUSES
A try block can be followed by multiple catch blocks.
Prepared by GSK
If an exception occurs in the try block, the exception
is passed to the first catch block in the list. If the
exception type matches with the first catch block it
gets caught, if not the exception is passed down to
the next catch block. This continue until the
exception is caught or failed to catch. 22
MULTIPLE CATCH SYNTAX
try
{
// suspected code Note:
Prepared by GSK
}
At a time, only one
catch(Exception1 e)
{ exception is
// handler code processed and only
}
one respective catch
catch(Exception2 e)
{ block is executed.
// handler code
23
}
public class MulCatch
{
public static void main(String[] args)
{ Output:
try ArrayIndexOutOfBounds
{ Exception -->
java.lang.ArrayIndexOut
Prepared by GSK
int a[ ]=new int[10]; OfBoundsException:
System.out.println(a[20]); Index
} 20 out of bounds for
length 10
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception --> "+e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds 24
Exception --> "+e);
} } }
UNREACHABLE CATCH BLOCK
Prepared by GSK
class Exception inside catch must come
before any of their super classes otherwise it
will lead to compile time error.
25
class UnreachCatch Program to implement Unreachable Catch block
{
public static void main(String[] args)
{
try Output:
{ Error
int arr[]={1,2};
Prepared by GSK
arr[2]=3/2;
}
catch(Throwable e) //This block handles all Exception
{
System.out.println("Generic exception");
}
catch(ArrayIndexOutOfBoundsException e) //This block is unreachable
{
System.out.println("array index out of bound exception");
}
} 26
}
NESTED TRY STATEMENT
try statement can be nested inside another block
of try. Nested try block is used when a part of a block
may cause one error while entire block may cause
Prepared by GSK
another error.
In nested try catch, the inner try block uses its own
catch block as well as catch block of the outer try, if
27
required.
class ExceptionsEx
{
public static void main(String[] args)
{ Output:
try
divide by zero array
{
int arr[ ]={5,0,1,2};
index out of bound exception
try
Prepared by GSK
{
int x = arr[3]/arr[1];
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
arr[4]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
} 28
}
} Program to implement Nested Try
THROW KEYWORD IN JAVA
Sometimes we can create Exception object explicitly
and we can hand over to the JVM manually by using
throw keyword.
Prepared by GSK
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
29
the try block.
THROW KEYWORD IN JAVA
Prepared by GSK
catch block.
Prepared by GSK
{
System.out.println(10/0);
}
Prepared by GSK
{
throw new ArithmeticException("/ by zero");
}
Prepared by GSK
num1 = input.nextInt();
num2 = input.nextInt();
try
{
if(num2 == 0)
throw new ArithmeticException("Division by zero is not possible");
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}
catch(ArithmeticException ae)
{
System.out.println("Problem info: " + ae.getMessage());
} 34
System.out.println("End of the program"); }}
THROWS KEYWORD IN JAVA
In our program if there is any chance of raising checked
exception then compulsory we should handle either by
try-catch or by throws keyword otherwise the code
Prepared by GSK
won't compile
Prepared by GSK
For any method that can throw exceptions, it is
mandatory to use the throws keyword to list the
exceptions that can be thrown.
Prepared by GSK
convince complier.
37
Output:Enter your name Amit Welcome Amit
import java.io.*; Output:
Enter your name: Ram
public class InputStr
Welcome Ram
{
public static void main(String[ ] args) throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader bfr = new BufferedReader(isr);
System.out.println("Enter Your Name:");
String str = bfr.readLine();
Prepared by GSK
IOException: This checked exception signals that
an I/O operation (like reading or writing) failed or
was interrupted.
When you use BufferedReader.readLine(), the
method can encounter I/O errors such as failing to
read from the input stream (e.g., if the stream is
closed or corrupted). 39
Basic The throw keyword The throws keyword is used to
handover our created delegate the responsibility of
exception object to exception handling to the caller
JVM manually. of the method.
Prepared by GSK
{
// body of method
}
Followed The throw keyword is The throws keyword is followed
by followed by exception by the list of the exception
object. classes that can occur in the
method.
Prepared by GSK
Prepared by GSK
These predefined exceptions are used to
handle errors occurring in the program.
But sometimes the programmer wants to
create his own customized exception as per the
requirements of the application which is
called user-defined exception or custom
45
exception.
Custom exceptions in Java are those exceptions that
are created by a programmer to meet the
specific requirements of the application. That’s
why it is also known as user-defined exception in
Java.
Prepared by GSK
For example:
1. A banking application, a customer whose age is
lower than 18 years, the program throws a custom
exception indicating “needs to open joint account”.
2. Voting age in India: If a person’s age entered is less
than 18 years, the program throws “invalid age” as a
46
custom exception.
HOW TO CREATE YOUR OWN USER-DEFINED
EXCEPTION IN JAVA?
Step 1: User defined exception basically derived
classes of Exception. This is done as:
class OwnException extends Exception
Prepared by GSK
Step 2: If you do not want to store any
exception details, define a default constructor in
your own exception class. This can be done as
follows:
OwnException( )
{
47
}
Step 3: If you want to store exception details, define a
parameterized constructor with string as a parameter,
call superclass (Exception) constructor from this, and
store variable “str”. This can be done as follows:
Prepared by GSK
OwnException(String str)
super(str);
} 48
Step 4: In the last step, we need to create an
object of user-defined exception class and throw it
using throw clause.
Prepared by GSK
OwnException obj = new
OwnException("Exception details");
throw obj;
or,
Prepared by GSK
super(s);
}
}
Prepared by GSK
register");
}
else if(age<18)
{
throw new TooYoungException(“You are too young… Not eligible to
register.....");
}
else
{
System.out.println("you will get match details soon by e-mail");
} 51
}
}
Output Case 1:
Javac CustomizedException.java
Java CustomizedException 25
Prepared by GSK
Output Case 2:
Java CustomizedException 15
Output Case 3:
Java CustomizedException 70
52
Exception in thread "main" TooOldException:
you are too old... Not eligible to register
Prepared by GSK
CHAPTER – 2
MULTITHREADING
53
Concurrently: two or
more events happen at
the same time, but not
necessarily at the exact
same moment.
Simultaneously: two or
more events happen at
Prepared by GSK
the exact same moment,
with no time lag
between them
Prepared by GSK
activity.
What is a Thread?
A thread is a path of execution within a process.
Prepared by GSK
smallest unit.
Process requires its own address space.
Process to Process communication is expensive. It is
comparatively heavy weight
Example – We can listen to music and browse
internet at the same time. The processes in this 56
Prepared by GSK
In thread based multitasking a thread is the smallest
unit.
Thread based multitasking requires less overhead.
Threads share same address space.
Thread to Thread communication is not expensive.
It is comparatively light weight.
58
Prepared by GSK
frequently making an impression on the user
that all threads are running simultaneously
and this is called multithreading.
60
MORE EXAMPLES FOR MULTITHREADING
Prepared by GSK
file.
In this example, navigation is one thread
and downloading is another thread.
Also in a word-processing application like
MS Word, we can type text in one thread
and spell checker checks for mistakes in 61
another thread.
APPLICATIONS
Prepared by GSK
2. To develop animations.
3. To develop video games etc.
4. To develop web and application servers
5. Whether it is process based or Thread based
the main objective of multitasking is to
improve performance of the system by
62
reducing response time.
Prepared by GSK
Note:
At a time one thread is executed only. 63
ADVANTAGE OF MULTITHREADING
Prepared by GSK
the system.
Prepared by GSK
are located in java.lang package.
Prepared by GSK
the code present in main method. This thread is called
as main thread.
Prepared by GSK
start() method to start the execution of
a thread.
67
Method-1: Creating a thread by using Thread Class
Prepared by GSK
68
Step-2:Create an instance of MyThread class and call the start
method and Override the run method
class ThreadDemo
{
Prepared by GSK
{
ThreadDemo
Thread: Main
MyThread t=new MyThread( ); Thread
//Instantiation of a Thread
t.start()
MyThread
t.start( ); //starting of a Thread
for(int i=0;i<5;i++)
{
System.out.println("main thread");
69
}
}}
Note: We can't expect exact output but there are several possible
outputs.
Prepared by GSK
70
Method-2: Creating a thread by using Runnable Interface
Prepared by GSK
71
Step-2: Create an instance of the MyRunnable class and pass it to a
Thread object, then call the start method.
Implement the run method.
class RunnableDemo
{
public static void main(String[] args)
Prepared by GSK
{
MyRunnable r=new MyRunnable();
Thread t=new Thread(r);
//here r is a Target Runnable
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main thread");
72
}
}}
Prepared by GSK
73
Output:
Prepared by GSK
74
Thread States/ Thread Life Cycle
Prepared by GSK
75
New:
Prepared by GSK
class "Thread class".
76
Runnable:
Prepared by GSK
In this State, the instance of the thread is
invoked with a start method.
Prepared by GSK
When the thread starts executing, then the
state is changed to "running" state.
Prepared by GSK
As there multiple threads are running in the
application, there is a need for synchronization
between threads.
Hence, one thread has to wait, till the other
thread gets executed.
Therefore, this state is referred as waiting state.
79
Dead:
Prepared by GSK
This is the state when the thread is
terminated.
Prepared by GSK
Once we call start() method then the Thread will
be entered into Runnable state.
Prepared by GSK
Higher-priority threads are more likely to be executed
before lower-priority ones, though this doesn’t
guarantee execution order due to the nature of thread
scheduling. In Java, when we create a thread, always a
priority is assigned to it.
The priority is given by the JVM or by the
programmer itself explicitly.
82
The range of the priority is between 1(Low) to 10(High)
GET AND SET METHODS IN THREAD
PRIORITY
1. int getPriority( )
Prepared by GSK
2. void setPriority (int newPriority)
Prepared by GSK
The default priority for a thread is 5
We can get thread’s priority by
using getPriority( ) method.
86
PROGRAM FOR GETTING DEFAULT PRIORITY OF THREADS
Prepared by GSK
MyThread p1 = new MyThread();
MyThread p2 = new MyThread();
MyThread p3 = new MyThread();
System.out.println("P1 thread priority : " +
p1.getPriority());
System.out.println("P2 thread priority : " +
p2.getPriority());
System.out.println("P3 thread priority : " +
p3.getPriority()); Output:
P1 thread priority : 5 87
P2 thread priority : 5
}} P3 thread priority : 5
EXAMPLE : SET PRIORITY
Prepared by GSK
It takes an integer argument that must be
between 1 and 10.
88
class ThreadSetPriority extends Thread
{
public void run()
{
System.out.println("Thread Running...");
}
Prepared by GSK
{
ThreadSetPriority p1 = new ThreadSetPriority();
// Starting thread
p1.start();
Output:
// Setting priority Thread Running...
p1.setPriority(2); thread priority : 2
// Getting priority
int p = p1.getPriority();
Prepared by GSK
suppose that both passengers start their reservation
process at 11 am and observe that only two seats are
available.
Prepared by GSK
Since the available number of seats is only two
but booked seats are three. This problem happened
due to asynchronous access to the railway reservation
system.
Prepared by GSK
• The solution to this problem can be solved by
a synchronization mechanism in which when
one thread is accessing the state of
object, another thread will wait to
access the same object at a time until
92
Prepared by GSK
The main purpose of synchronization is to avoid
thread interference.
When more than one thread try to access a
shared resource, we need to ensure that resource
will be used by only one thread at a time.
The process by which this is achieved is called
synchronization. 93
THREAD SYNCHRONIZATION? CONTD..
Prepared by GSK
In other words, when a thread is already
accessing an instance of a class, preventing any
other thread from acting on the same instance is
called ‘thread synchronization in Java‘ or
‘ Thread safe‘.
94
OBJECT LOCK IN JAVA
The code in Java program can be synchronized with the
help of a lock.
Prepared by GSK
Prepared by GSK
from inside. The second person who wants to
enter the room will wait until the first person
come out.
synchronized (object)
{
Prepared by GSK
//statement to be synchronized
}
Prepared by GSK
int wanted;
}
public void run()
{
//Display available berths
System.out.println("Available berths= "+available);
Prepared by GSK
//available berths are more than wanted berths
if(available>=wanted)
{
//get the name of the person
String name = Thread.currentThread().getName();
//Allot the berth to him
System.out.println(wanted +" Berth(s) reserved for
100
"+name);
try
{
Thread.sleep(2000); //wait for printing the
//ticket 2000 milliseconds (2 seconds)
available = available-wanted;
//update the no. of available berths
}
Prepared by GSK
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
else{
//if available berths are less, display message
System.out.println("Sorry! No berths available");
}
101
}
}
class Unsafe {
Prepared by GSK
//Attach second thread to the same object
Thread t2 = new Thread(obj);
Prepared by GSK
When thread t1 enters the run() method, it sees
available number of berths as 1 and hence, it allots it
to First person.
103
Then it enters into try{ } block inside the run()
method, where it will sleep for 2 seconds. In this time,
ticket will be printed on the printer. When thread t1 is
sleeping, thread t2 also enters the run() method, it
Prepared by GSK
also sees that there is 1 berth remaining.
104
To solve these problem in java, there is a concept called
synchronization.
Synchronization will not allow the multiple thread
accessing run() method at a time.
Prepared by GSK
What Is an InterruptedException?
An InterruptedException is thrown when a thread is
interrupted while it's waiting or sleeping.
printStackTrace()
The printStackTrace() method
of Java.lang.Throwable class used to print the details
like class name and line number where the exception
105
occurred.
HOW CAN WE SYNCHRONIZE THE OBJECT?
Prepared by GSK
synchronized (object)
{
statements;
}
In the above statement object represents the object to be locked
or synchronized. The statements inside the synchronized block
all are available to only one thread at a time
106
2. Using synchronized method:
Prepared by GSK
the synchronized keyword before the method name.
statements;
}
107
JAVA DAEMON THREAD
Daemon threads in Java are special types of
threads that run in the background to perform
tasks such as garbage collection, background clean-
Prepared by GSK
up, etc
Prepared by GSK
thread as a daemon thread or user thread(Non-
daemon)
If there is a user thread as obj1 then
obj1.setDaemon(true) will make it a Daemon
thread and if there is a Daemon thread obj2 then
calling obj2.setDaemon(false) will make it a user
thread 109
2. boolean isDaemon()
In Java, this method is used to check whether
the current thread is a daemon or not.
Prepared by GSK
It returns true if the thread is Daemon otherwise it
returns false.
Prepared by GSK
// Checking whether the thread is Daemon or not
if(Thread.currentThread().isDaemon())
{
System.out.println("Daemon thread executing");
}
else{
System.out.println("user(normal) thread
executing");
} 111
}
public static void main(String[] args)
{
/* Creating two threads: by default they are
user threads (non-daemon threads) */
DaemonThreadExample1 t1=new
DaemonThreadExample1();
Prepared by GSK
DaemonThreadExample1 t2=new
DaemonThreadExample1();
Prepared by GSK
group is that by using a single method, will be able
to control all the threads in a group.
To create a thread group, we should simply create an
object to ThreadGroup class as:
ThreadGroup tg= new ThreadGroup(" group name");
Here tg is ThreadGroup object, and group name is its
113
name.
GROUPING OF THREADS CONTD…
All the threads of a threadgroup can be stopped
together by calling tg.stop( ) or it can be
suspended by calling tg.suspend( ) or it can be
Prepared by GSK
resumed but calling tg.resume( ) where tg is a
threadgroup object.
Prepared by GSK
When a Java application first starts up, the Java
runtime system creates a ThreadGroup named
main.
1)ThreadGroup(String name)
Prepared by GSK
This constructor is used for creating a new thread
group, the parent of this thread group is the same
as the parent group of the currently executing
thread.
116
2)ThreadGroup(ThreadGroup parent, String name)
Prepared by GSK
specified thread group as a parent and
specified name.
Prepared by GSK
getParent( ) method returns the name of the parent
thread group of the current group. i.e. for a
Threadgroup we can create sub groups also. (like we
can create sub packages to packages).
118
METHODS CONTD…
Prepared by GSK
thread in a group.
Prepared by GSK
This is a very convenient method to know how
many threads in a group are alive at a
particular moment. In a containing many
threads some Threads must have been already
dead when they completed their Run method
and some may have not been started as by the
120
programmer.
Program to implement ThreadGroups
import java.lang.*;
class Tgroups
{
Prepared by GSK
{
121
Program to implement ThreadGroups
Prepared by GSK
Thread t4 = new Thread(tg1, can, "Fourth Thread");
Prepared by GSK
//Find how many threads are actively running
System.out.println("Number of active threads running in tg group:
"
+ tg.activeCount());
}
}
123
class Reservation extends Thread
{
public void run()
{
System.out.println("I am Reservation Thread");
}
}
Prepared by GSK
class Cancellation extends Thread
{
public void run()
{
System.out.println("I am Cancellation Thread");
}
}
Output:
Parent of tg1 is java.lang.ThreadGroup[name=First Group,maxpri=10]
Thread group of t1 isjava.lang.ThreadGroup[name=First Group,maxpri=10]
Thread group of t3 isjava.lang.ThreadGroup[name=Second Group,maxpri=7]
I am Reservation Thread
I am Reservation Thread
124
I am Cancellation Thread
I am Cancellation Thread
Number of active threads running in tg group: 0
INTER THREAD COMMUNICATION
Prepared by GSK
For example, a Consumer thread is waiting for a Producer
to produce the data (or some goods). When the Producer
completes production of data, then the consumer thread
should take that data and use it.
125
INTER THREAD COMMUNICATION CONTD…
Method Description
Obj.wait( ) This method makes a thread wait for
the object (obj) till it receives a
Prepared by GSK
notification
Obj.notify( ) This method releases an object (obj)
and sends a notification to a waiting
thread that the object is available.
Obj. This method is useful to send
notifyAll() notification to all waiting threads that
the object (obj) is available
126
Note:
Prepared by GSK
To make the Producer wait until Consumer
retrieves the item and Consumer wait until
Producer places an item, we can use
the wait() and notify() methods.
127
JAVA ENUMERATIONS
In Java, an enum (short for enumeration) is a type
that has a fixed set of constant values.
We use the enum keyword to declare enums.
Prepared by GSK
For example,
enum Size { SMALL, MEDIUM, LARGE,
EXTRALARGE }
Here, we have created an enum named Size. It
contains fixed values SMALL, MEDIUM, LARGE,
and EXTRALARGE.
These values inside the braces are called enum
constants (values).
Note: The enum constants are usually represented 132
in uppercase.
Example Program to Implement Enum
enum Size
{
SMALL, MEDIUM, LARGE, EXTRALARGE
Prepared by GSK
}
class Test
{
Size pizzaSize;
Prepared by GSK
break;
default:
System.out.println("I don't know which one to order.");
break;
}
}
}
class Enum_Ex {
public static void main(String[] args) {
Test t1 = new Test(Size.MEDIUM);
t1.orderPizza();
} 134
Output:
} I ordered a medium size pizza.
Example-2: Implementing enum
Prepared by GSK
THURSDAY, FRIDAY, SATURDAY
}
Prepared by GSK
break;
case FRIDAY:
System.out.println("Almost the weekend!");
break;
case SATURDAY:
case SUNDAY:
System.out.println("It's the weekend, enjoy!");
break;
default:
System.out.println("Just another day!");
break;
} Output:
136
Prepared by GSK
For example,
int a = 56;
import java.util.ArrayList;
Prepared by GSK
ArrayList<Integer> list = new ArrayList<>();
//autoboxing
list.add(5);
list.add(6);
we have created an array list of Integer type. Hence the array list can only
hold objects of Integer type. Notice the line,list.add(5); Here, we are passing
primitive type value. However, due to autoboxing, the primitive value138 is
automatically converted into an Integer object and stored in the array list.
UNBOXING
Prepared by GSK
// autoboxing
Integer aObj = 56;
// unboxing
int a = aObj;
//autoboxing
Prepared by GSK
list.add(5);
list.add(6);
// unboxing
int a = list.get(0);
System.out.println("Value at index 0: " + a);
}
}
notice the line,
int a = list.get(0); Here, the get() method returns the object at index 0.
140
However, due to unboxing, the object is automatically converted into
the primitive type int and assigned to the variable a.
JAVA ANNOTATIONS
Prepared by GSK
They provide additional information about
the program to the compiler but are not part
of the program itself.
Prepared by GSK
that has been marked with this annotation
overrides the method of the superclass with the
same method name, return type, and parameter list.
It is not mandatory to use @Override when
overriding a method. However, if we use it, the
compiler gives an error if something is wrong (such
as wrong parameter type) while overriding the 142
method.
class Animal
{ Example Program to implement
public void displayInfo() @Override annotation
{
System.out.println(“From animal class");
}
}
Output:
class Dog extends Animal
Prepared by GSK
From dog class
{
@Override
public void displayInfo()
{
System.out.println(“From dog class");
}
}
class Annotation_Ex
{
public static void main(String[] args)
{
Dog d1 = new Dog();
143
d1.displayInfo();
}
}
GENERICS
Prepared by GSK
different types of data (objects).
144
JAVA GENERICS METHOD
we can create a method that can be used with any
type of data, is known as Generics Method.
Prepared by GSK
class DemoClass
{
}
JAVA GENERICS METHOD CONTD…
class Generics_Ex
{
public static void main(String[] args)
{
Prepared by GSK
// initialize the class with Integer data
DemoClass demo = new DemoClass();
demo.<String>genericMethod("Java Programming");
demo.<Integer>genericMethod(25); 147