Unit3 Java
Unit3 Java
Exception
An Exception is a run time error, which occurs during the execution of a program, that disrupts
the normal flow of the program's instructions.
Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be
executed.
If we perform exception handling, the rest of the statement will be executed. That is why
we use exception handling in Java.
Types of Exception
There are two types of exceptions
1.Checked Exception
2.Un-Checked Exception
1.Checked Exception
Checked Exceptions are the exception which checked at compile-time. These exceptions are
directly sub-class of java.lang.Exception class.
The following are a few built-in classes used to handle checked exceptions in java.
IOException
FileNotFoundException
ClassNotFoundException
2.Un-Checked Exception
Un-Checked Exceptions are the exception both identifies or raised at run time. These exceptions
are directly sub-class of java.lang.RuntimeException class.
Note: In real time application mostly we can handle un-checked exception.
The following are a few built-in classes used to handle unchecked exceptions in java:
ArithmeticException: It is thrown when an exceptional condition has occurred in an
arithmetic operation.
ArrayIndexOutOfBounds Exception: It is thrown to indicate that an array has been
accessed with an illegal index. The index is either negative or greater than or equal to the size
of the array.
NullPointerException: This exception is raised when referring to the members of a null
object. Null represents nothing
NumberFormatException: This exception is raised when a method could not convert a
string into a numeric format.
StringIndexOutOfBoundsException: It is thrown by String class methods to indicate that
an index is either negative than the size of the string.
Termination Model
Resumptive Model
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.
Resumptive Model
The alternative of termination model is resumptive model. In resumptive model, the exception
handler is expected to do something to stable the situation, and then the faulting method is retried.
In resumptive model we hope to continue the execution after the exception is handled.
In resumptive model we may use a method call that want resumption like behavior. We may also
place the try block in a while loop that keeps re-entering the try block util the result is satisfactory.
Exception Hierarchy
The exception hierarchy in many programming languages typically follows a structure where more
specific exceptions inherit from more general ones. For example, in Java:
• Throwable
• Error
• Exception
• RuntimeException
• ArithmeticException
• NullPointerException
• IOException
• FileNotFoundException
This hierarchy allows for more specific handling of different types of exceptions
1. Throwable:
• Throwable is the superclass for all exceptions and errors in Java. Both exceptions
and errors inherit from this class.
2. Error:
• Errors represent serious, often unrecoverable issues that typically result from
problems external to the program. Examples include OutOfMemoryError or
StackOverflowError. These are not meant to be caught or handled by regular
application code because they usually indicate a severe problem that should be
addressed at the system level.
3. Exception:
• Exceptions are conditions that a program should catch and handle. They are meant
to indicate exceptional conditions that a well-behaved application should anticipate
and recover from. Exception itself is further divided into two main subclasses:
RuntimeException and IOException, among others.
4. RuntimeException:
• RuntimeException is a subclass of Exception and represents exceptions that can
occur during the normal operation of the Java Virtual Machine. These exceptions
are considered to be unchecked exceptions because they are not explicitly checked
at compile time. Programmers are not required to catch or declare them explicitly,
but they can still be caught and handled if desired.
• Examples of RuntimeException include:
• ArithmeticException: Thrown when an arithmetic operation exceeds the
limits of the data type, such as division by zero.
• NullPointerException: Thrown when attempting to access an object
reference that is null.
• ArrayIndexOutOfBoundsException: Thrown when attempting to access
an array with an index that is outside its bounds.
5. IOException:
• IOException is a subclass of Exception and represents input/output exceptions that
may occur during the execution of a program. These exceptions are checked at
compile time, meaning that the programmer is required to either catch them or
declare that the method throws these exceptions.
• Examples of IOException include:
• FileNotFoundException: Thrown when attempting to access a file that
cannot be found.
• IOException itself is a more general class for handling various input/output-
related issues.
The hierarchy allows for organized and structured handling of exceptions. By catching more
specific exceptions, developers can tailor their error-handling strategies to the specific issues that
might occur during program execution. This improves the robustness and reliability of the code by
allowing it to gracefully handle unexpected situations.
1.try block
The try block contains set of statements where an exception can occur.
In other words try block always contains problematic statements.
A try block is always followed by a catch block, which handles the exception that occurs in
associated try block. A try block must be followed by catch blocks or finally block or both.
Syntax
try
{
//statements that may cause an exception
}
2.catch block
A catch block is where we handle the exceptions, this block must follow the try block.
A single try block can have multiple catch blocks associated with it. We can catch different
exceptions in different catch blocks.
When an exception occurs in try block, the corresponding catch block that handles that
particular exception executes.
For example if an arithmetic exception occurs in try block then the statements enclosed in
catch block for arithmetic exception executes.
Example(try&catch)
class ExceptionDemo
{
public static void main(String[] args)
{
int a=30, b=0;
try
{
int c=a/b;
}
catch (ArithmeticException e)
{
System.out.println("Denominator should not be zero");
}
}
}
Output:
Denominator should not be zero
Example
class ExceptionDemo
{
public static void main(String[] args)
{
int a=30, b=0;
try
{
int c=a/b;
System.out.println("Result: "+c);
}
catch(NullPointerException e)
{
System.out.println("Enter valid number");
}
catch(ArithmeticException e)
{
System.out.println("Denominator not be zero");
}
}
}
Syntax
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
…………
}
}
catch(Exception e)
{
………..
}
Example
class NestedTry
{
public static void main(String args[])
{
try
{
try
{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
catch(Exception e)
{
System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
3.throw
The throw keyword in Java is used to explicitly throw an exception from a method or any
block of code.
We can throw either checked or unchecked exception.
The throw keyword is mainly used to throw custom exceptions.
Syntax
throw Instance
Example
throw new ArithmeticException("/ by zero");
Example
class ThrowExcep
{
static void fun()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
}
}
public static void main(String args[])
{
try
{
fun();
}
catch(NullPointerException e)
{
System.out.println("Caught in main.");
}
}
}
Output: Caught inside fun().
Caught in main.
4. throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to provide the
exception handling code so that the normal flow of the program can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers' fault that he is not checking
the code before it being used.
Only checked exceptions are required to be thrown using the throws keyword. Unchecked
exceptions don’t need to be thrown or handled explicitly in code.
import java.io.IOException;
class Testthrows1{
void m() throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
Case 1: We have caught the exception i.e. we have handled the exception using try/catch block.
Case 2: We have declared the exception i.e. specified throws keyword with the method.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
•In case we declare the exception, if exception does not occur, the code will be executed
fine.
•In case we declare the exception and the exception occurs, it will be thrown at runtime
because throws does not handle the exception.
Let's see examples for both the scenario.
A) If exception does not occur
Testthrows3.java
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output:
B) If exception occurs
importjava.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output:
Exception in thread "main" java.io.IOException: device error
at M.method(Testthrows4.java:4)
at Testthrows4.main(Testthrows4.java:10)
5.finally Block
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.
Example
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Example
class RethrowExcep
{
static void fun()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
}
}
public static void main(String args[])
{
try
{
fun();
}
catch(NullPointerException e)
{
System.out.println("Caught in main.");
}
}
}
Output:
Caught inside fun().
Caught in main.
Example
package nage;
public class InvalidAgeException extends Exception
{
public InvalidAgeException (String s)
{
super(s);
}
}
Multithreading in Java
Multithreading in java is a process of executing multiple threads simultaneously. The aim of
multithreading is to achieve the concurrent execution.
What is Thread?
A thread is a light weight subprocess, a smallest unit of processing.
A thread is a subpart of a process that can run individually.
As shown in the above figure, 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.
Note:At a time only one thread is executed.
Comparing Multitasking and Multithreading
Factors Multi-tasking Multi-threading
In multithreading, the CPU creates and
In multitasking, the CPU executes
Fundamentals processes multiple threads from a
multiple tasks simultaneously.
single task concurrently.
In multithreading, a CPU divides a
With multitasking, a user can
program into multiple threads to work
Operation perform multiple tasks
more efficiently, thereby enhancing
simultaneously on their CPU.
computer power.
In multitasking, the system In multithreading, the system allocates
Resources and allocates separate resources and a single memory to a process, and the
Memory memory to different programs threads derived from it share the same
running simultaneously. resources and memory.
The CPU constantly switches In multithreading, the CPU constantly
Switching between different programs in switches between threads, not
multitasking. programs.
Multitasking involves Multithreading does not involve
Multiprocessing multiprocessing among various multiprocessing among its
components. components.
Execution Execution in multitasking is Execution in multithreading is
Speed relatively slower. significantly faster.
Process The termination of a process in The termination of a process in
Termination multitasking takes more time. multithreading takes less time.
2.Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
public void run(): is used to perform action for a thread
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
Output:
thread is running...
If you are not extending the Thread class,your class object would not be treated as a thread
object.So you need to explicitely create Thread class object.We are passing the object of your class
that implements Runnable so that your class run() method may execute.
Thread Priorities
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling).
But it is not guaranteed because it depends on JVM specification that which scheduling it
chooses.
Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Synchronizing Threads
Synchronization
Synchronization is the capability of control the access of multiple threads to any shared resource.
Synchronization is better in case we want only one thread can access the shared resource at a time.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only thread synchronization.
Thread Synchronization
There are two types of thread synchronizations.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This
can be done by two ways in java:
1. by synchronized method
2. by synchronized block
Example:
class Table
{
void printTable(int n)
{
//method not synchronized
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
class TestSynchronization
{
public static void main(String args[])
{
Table obj = new Table(); //only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
100
10
200
15
300
20
400
25
500
Example:
class Table
{
synchronized void printTable(int n)
{
//method not synchronized
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
class TestSynchronization
{
public static void main(String args[])
{
Table obj = new Table(); //only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
Inter-thread Communication
Inter-thread communication or Co-operation is all about allowing synchronized
threads to communicate with each other.
•wait()
•notify()
•notifyAll()
1) wait() method
The 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
It waits until object is notified.
InterruptedException
c
l
a
s
s
public final void wait(long It waits for the specified amount
M timeout)throws InterruptedException of time.
y
T
h 2) notify() method
r
e The notify() method wakes up a single thread that is waiting on this object's
a
d 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
i implementation.
m
p Syntax:
l
e public final void notify()
m
e
n 3) notifyAll() method
t
s Wakes up all threads that are waiting on this object's monitor.
R Syntax:
u
n public final void notifyAll()
n
a Difference between wait and sleep
b
l Let's see the important differences between wait and sleep methods.
e
{ wait() sleep()
i The wait() method releases the lock. The sleep() method doesn't release the lock.
n
t It is a method of Object class It is a method of Thread class
(
}
public class InnerThreadDemo {
public static void main (String []args)throws InterruptedException {
MyThread mt = new MyThread ();
Thread t = new Thread (mt);
t.start();
synchronized (mt) {
mt.wait();
System.out.println ("Total Earnings:" + mt.total);
}
} }
Output:
Main Thread total:1000
ThreadGroup in Java
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 ThreadGroup represents a set of threads. A thread group can also include the
other thread group. The thread group creates a tree in which every thread group
except the initial thread group has a parent.
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.
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.
Thread.currentThread().getThreadGroup().interrupt();
ThreadGroup Example
public class ThreadGroupDemo implements Runnable{
System.out.println(Thread.currentThread().getName());
t1.start();
t2.start();
t3.start();
tg1.list();
} }
Output:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
Let's look at an example problem of producer and consumer.
The producer produces the item and the consumer consumes the same.
But here, the consumer cannot consume until the producer produces the item, and producer
cannot produce until the consumer consumes the item that already been produced.
So here, the consumer has to wait until the producer produces the item, and the producer also
needs to wait until the consumer consumes the same.
Here we use the inter-thread communication to implement the producer and consumer
problem.
Example
class ItemQueue
{
int item;
boolean valueSet = false;
synchronized int getItem()
{
while (!valueSet)
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Consummed:" + item);
valueSet = false;
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
notify();
return item;
}
synchronized void putItem(int item)
{
while (valueSet)
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.item = item;
valueSet = true;
System.out.println("Produced: " + item);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
notify();
}
}
class Producer implements Runnable
{
ItemQueue itemQueue;
Producer(ItemQueue itemQueue)
{
this.itemQueue = itemQueue;
new Thread(this, "Producer").start();
}
public void run()
{
int i = 0;
while(true)
{
itemQueue.putItem(i++);
}
}
}
class Consumer implements Runnable
{
ItemQueue itemQueue;
Consumer(ItemQueue itemQueue)
{
this.itemQueue = itemQueue;
new Thread(this, "Consumer").start();
}
public void run()
{
while(true)
{
itemQueue.getItem();
}
}
}
class ProducerConsumer
{
public static void main(String args[])
{
ItemQueue itemQueue = new ItemQueue();
new Producer(itemQueue);
new Consumer(itemQueue);
}
}
Output:
Produced: 0
Consummed:0
Produced: 1
Consummed:1
Produced: 2
Consummed:2
Produced: 3
Consummed:3
Produced: 4
Consummed:4
Produced: 5
Consummed:5
Produced: 6
Consummed:6
Produced: 7
Consummed:7
Produced: 8
Consummed:8
Daemon Thread
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 java.lang.Thread class provides two methods for java daemon thread.
t1.start();//starting threads
t2.start();
t3.start();
}
}
Output:
Annotations in Java
Annotations are used to provide supplemental information about a program.
Note: This program throws compiler error because we have mentioned override, but
not overridden, we have overloaded display
class Base {
System.out.println("Base display()");
} }
obj.display();
}}
Output:
10: error: method does not override or implement a method from a supertype
If we remove parameter (int x) or we remove @override, the program compiles fine.
Categories of Annotations
There are broadly 5 categories of annotations as listed:
1.Marker Annotations
2.Single value Annotations
3.Full Annotations
4.Type Annotations
5.Repeating Annotations
Category 1: Marker Annotations
The only purpose is to mark a declaration. These annotations contain no members
and do not consist of any data. Thus, its presence as an annotation is sufficient.
Since the marker interface contains no members, simply determining whether it is
present or absent is sufficient. @Override is an example of Marker Annotation.
Example
@TestAnnotation()
Category 2: Single value Annotations
These annotations contain only one member and allow a shorthand form of
specifying the value of the member. We only need to specify the value for that
member when the annotation is applied and don’t need to specify the name of the
member. However, in order to use this shorthand, the name of the member must be
a value.
@TestAnnotation(“testing”);
Category 3: Full Annotations
These annotations consist of multiple data members, names, values, pairs.
Example
@TestAnnotation(owner=”Rahul”, value=”Class Geeks”)
Category 4: Type Annotations
These annotations can be applied to any place where a type is being used. For
example, we can annotate the return type of a method. These are declared
annotated with @Target annotation.
Category 5: Repeating Annotations
These are the annotations that can be applied to a single item more than once. For
an annotation to be repeatable it must be annotated with the @Repeatable
annotation, which is defined in the java.lang.annotation package. Its value field
specifies the container type for the repeatable annotation. The container is specified
as an annotation whose value field is an array of the repeatable annotation type.
Hence, to create a repeatable annotation, firstly the container annotation is created,
and then the annotation type is specified as an argument to the @Repeatable
annotation.
ENUMERATION
In java, an Enumeration is a list of named constants. The enum concept was
introduced in Java SE 5 version.
The enum in Java programming the concept of enumeration is greatly expanded
with lot more new features
compared to the other languages like C, and C++.
In java, the enumeration concept was defined based on the class concept. When we
create an enum in java, it
converts into a class type. This concept enables the java enum to have constructors,
methods, and instance
variables.
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.
Creating enum in Java
To create enum in Java, we use the keyword enum. The syntax for creating enum is
similar to that of class.
In java, an enum can be defined outside a class, inside a class, but not inside a
method.
Example
enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class EnumerationExample {
public static void main(String[] args) {
WeekDay day = WeekDay.FRIDAY;
System.out.println("Today is " + day);
System.out.println("\nAll WeekDays: ");
for(WeekDay d:WeekDay.values())
System.out.println(d);}
}
• Every enum is converted to a class that extends the built-in class Enum.
• Every constant of an enum is defined as an object.
• As an enum represents a class, it can have methods, constructors. It also gets
a few extra methods from the
Enum class, and one of them is the values() method.
Constructors enum
In a java programming language, an enum can have both the type of constructors
default and parameterized.
The execution of constructor depends on the constants we defined in the enum. For
every constant in an
enum, the constructor is executed.
If an enum has a parameterized constructor, the parameter value should be passed
when we define constant.
Example
enum WeekDay{
MONDAY,
TUESDAY,
SUNDAY("Holiday");
WEDNESSDAY,
THURSDAY,
String msg;
WeekDay(){
System.out.println("Default constructor!");
}
WeekDay(String str){
System.out.println("Parameterized constructor!");
FRIDAY,
SATURDAY,msg = str;
}
}
public class EnumerationExample {
public static void main(String[] args) {
WeekDay day = WeekDay.SUNDAY;
System.out.println("\nToday is " + day + " and its " + day.msg);
}
}
In the above example, the constant SUNDAY is created by calling the parameterized
constructor, other
constants created by calling default constructor.
Methods enum
In a java programming language, an enum can have methods. These methods are
similar to the methods of a
class. All the methods defined in an enum can be used with all the constants
defined by the same enum.
Example
enum WeekDay{
MONDAY,
TUESDAY,
SUNDAY("Holiday");
WEDNESSDAY,
String msg;
WeekDay(){
System.out.println("Default constructor!");
THURSDAY,
FRIDAY,
SATURDAY,}
WeekDay(String str){
System.out.println("Parameterized constructor!");
msg = str;
}
void printMessage() {
System.out.println("Today is also " + msg);
}
}
public class EnumerationExample {
public static void main(String[] args) {
WeekDay day = WeekDay.SUNDAY;
System.out.println("\nToday is " + day);
day.printMessage();
}
}
•
• enum can not extend another enum and a class.
• enum can implement interfaces.
• enum does not allow to create an object of it.
• Every enum extends a built-in class Enum by default.
GENERICS
The java generics 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 generics 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
types like int, float, char, etc.
The java generics feature was introduced in Java 1.5 version. In java, generics used
angular brackets “< >”.
In java, the generics feature implemented using the following.
• Generic Method
• Generic Classes
Generic methods
Generics allows creating generic methods which can work with a different type of
data values.
Using a generic method, we can create a single method that can be called with
arguments of different types.
Based on the types of the arguments passed to the generic method, the compiler
handles each method call
appropriately.
Example - Generic method
Generic Class
A class can be defined as a generic class that allows creating a class that can work
with different types.
A generic class declaration looks like a non-generic class declaration, except that the
class name is followed by a type parameter section.
Example - Generic class
public class GenericsExample<T> {
T obj;
public GenericsExample(T anotherObj) {
this.obj = anotherObj;
}
public T getData() {
return this.obj;
}
public static void main(String[] args) {
GenericsExample<Integer> actualObj1 = new GenericsExample<Integer>(100);
System.out.println(actualObj1.getData());
GenericsExample<String> actualObj2 = new GenericsExample<String>("Java");
System.out.println(actualObj2.getData());
GenericsExample<Float> actualObj3 = new GenericsExample<Float>(25.9f);
System.out.println(actualObj3.getData());
}
}