0% found this document useful (0 votes)
3 views54 pages

Module 3 Oops

Uploaded by

sripadadhi135
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views54 pages

Module 3 Oops

Uploaded by

sripadadhi135
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE-III

Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and
multiple inheritance in Java.

Java Interface also represents IS-A relationship. It cannot be instantiated just like abstract class.
There are mainly three reasons to use interface. They are given below.

 It is used to achieve fully abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.

NOTE: The java compiler adds public and abstract keywords before the interface method and
public, static and final keywords before data members.
Understanding relationship between classes and interfaces

As shown in the figure given above, a class extends another class, an interface extends another
interface but a class implements an interface.

Defining an Interface
An interface is defined much like a class. This is the general form of an interface:
Here, access is either public or none. name is the name of the interface. The methods
which are declared in the interface have no bodies. Variables declared inside of interface are
implicitly final and static. They must be initialized with a constant value.
Here is an example of an interface definition.

Use of interfaces
Interfaces can not be instantiated. They can be inherited to other interfaces or to other
classes. Using interfaces the concept of multiple inheritances can be achieved. Once an interface
is defined, any number of classes can implement an interface. Also, one class can implement any
number of interfaces. Each class that includes an interface must implement all of the methods
declared in the interface. The data members declared in the interface cannot be changed by the
implementing class.
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements clause in a class definition, and then create the
methods defined by the interface. The general form of a class that includes the implements clause
looks like this:

Here, access is either public or none. If a class implements more than one interface, the
interfaces are separated with a comma. The methods that implement an interface must be
declared public. Also, the type signature of the implementing method must match exactly the
type signature specified in the interface definition.
Here is a small example class that implements the example interface shown earlier.

classes that implement interfaces can define additional members of their own.
For example:
Accessing Implementations through Interface References
We can declare variables as object references that use an interface rather than a class
type. Any instance of any class that implements the declared interface can be referred to by such
a variable. The following example calls the disp() method via an interface reference variable:

Notice that variable i1 is declared to be of the interface type inter, yet it was assigned an
instance of the class sample. Although i1 can be used to access the disp() method, it cannot
access
any other members of the sample class. An interface reference variable only has knowledge of
the methods declared by its interface declaration. Thus, i1 could not be used to access show( )
since it is defined by sample Partial Implementations
If a class includes an interface but does not fully implement the methods defined by that
interface, then that class must be declared as abstract.

For example:

Here, the class A does not implement disp() and must be declared as abstract. Any class
that inherits A must implement disp( ) or be declared abstract itself.
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){[Link]("Hello");} public void
show(){[Link]("Welcome");} public static void main(String args[]){
A7 obj = new A7(); [Link]();
[Link]();
}}
Output: Hello
Welcome

Variables in java:
In java, an interface is a completely abstract class. An interface is a container of abstract methods and
static final variables. The interface contains the static final variables. The variables defined in an interface
can not be modified by the class that implements the interface, but it may use as it defined in the interface.
 The variable in an interface is public, static, and final by default.
 If any variable in an interface is defined without public, static, and final keywords then,
the compiler automatically adds the same.
 No access modifier is allowed except the public for interface variables.
 Every variable of an interface must be initialized in the interface itself.
 The class that implements an interface can not modify the interface variable, but it may
use as it defined in the interface.
Example:
interfaceSampleInterface{

int UPPER_LIMIT =100;

//int LOWER_LIMIT; // Error - must be initialised

publicclassInterfaceVariablesExampleimplementsSampleInterface{

publicstaticvoidmain(String[]args){

[Link]("UPPER LIMIT = "+ UPPER_LIMIT);

// UPPER_LIMIT = 150; // Can not be modified


}
}
Interfaces Can Be Extended
Interface can inherit another interface by use of the keyword extends. The syntax is the
same as for inheriting classes. When a class implements an interface that inherits another
interface, it must provide implementations for all methods defined within
the interface inheritancee chain. Following is an example:

A is an interface which contains the declarations of meth1() and meth2(). B is an interface


which extends A and contains the declaration of meth3(). In the class Sample, which implements
interface B all the methods meth1(), meth2() and meth3() must be defined. Any class that
implements an interface must implement all methods defined by that interface, including any
that are inherited from other interfaces.
Difference between Class and Interface
CLASS INTERFACE

The ‘class’ keyword is used to create a The ‘interface’ keyword is used to create an
class. interface.

An object of a class can be created. An object of an interface cannot be created.

Class doesn’t support multiple Interface supports multiple inheritance.


inheritance.

A class can inherit another class. An Interface cannot inherit a class.

A class can be inherited by another An Interface can be inherited by a class using the
class using the keyword ‘extends’. keyword ‘implements’ and it can be inherited by
another interface using the keyword ‘extends’.

A class can contain constructors. An Interface cannot contain constructors.

It cannot contain abstract methods. It consists of abstract methods only.

Variables and methods can be Variables and methods are declared as public only.
declared using any specifiers like
public, protected, default, private.
Difference between Abstract Class and Interface in Java
[Link]. Abstract Class Interface

1. An abstract class can contain both abstract and non- Interface contains only abstract
abstract methods. methods.

2. An abstract class can have all four; static, non-static Only final and static variables are
and final, non-final variables. used.

3. To declare abstract class abstract keywords are The interface can be declared with the
used. interface keyword.

4. It supports multiple inheritance. It does not support multiple


inheritance.

5. The keyword ‘extend’ is used to extend an abstract The keyword implement is used to
class implement the interface.

6. It has class members like private and protected, etc. It has class members public by default.

Exploring [Link] (file handling)


The [Link] package contains nearly every class you might ever need to perform input and output
(I/O) in Java. All these streams represent an input source and an output destination. The stream in
the [Link] package supports many data such as primitives, object, localized characters, etc.

Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
• InPutStream − The InputStream is used to read data from a source.
• OutPutStream − The OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to files and networks very basic functionality
related to streams and I/O. We will see the most commonly used
examples one by one −

Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of these
two classes to copy an input file into an output file –

Example

import [Link].*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("[Link]");
out = new FileOutputStream("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}
Now let's have a file [Link] with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating [Link]
file with the same content as we have in [Link]. So let's put the above code in [Link] file
and do the following −
$javac [Link]
$java CopyFile

Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode. Though there are
many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes
at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input file
(having unicode characters) into an output file –
Example
import [Link].*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("[Link]");
out = new FileWriter("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}
Now let's have a file [Link] with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating [Link]
file with the same content as we have in [Link]. So let's put the above code in [Link] file
and do the following –

$javac [Link]
$java CopyFile

Standard Streams
All the programming languages provide support for standard I/O where the user's program can
take input from a keyboard and then produce an output on the computer screen. If you are aware
of C or C++ programming languages, then you must be aware of three standard devices STDIN,
STDOUT and STDERR. Similarly, Java provides the following three standard streams −
• Standard Input − This is used to feed the data to user's program and usually a keyboard is
used as standard input stream and represented as [Link].
• Standard Output − This is used to output the data produced by the user's program and
usually a computer screen is used for standard output stream and represented
as [Link].
• Standard Error − This is used to output the error data produced by the user's program and
usually a computer screen is used for standard error stream and represented as [Link].
Following is a simple program, which creates InputStreamReader to read standard input stream
until the user types a "q" –

Example
import [Link].*;
public class ReadConsole {
public static void main(String args[]) throws IOException {
InputStreamReadercin = null;
try {
cin = new InputStreamReader([Link]);

[Link]("Enter characters, 'q' to quit.");


char c;
do {
c = (char) [Link]();
[Link](c);
} while(c != 'q');
}finally {
if (cin != null) {
[Link]();
}
}
}
}
Let's keep the above code in [Link] file and try to compile and execute it as shown in
the following program. This program continues to read and output the same character until we
press 'q' –

$javac [Link]
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q

Reading and Writing Files


As described earlier, a stream can be defined as a sequence of data. The InputStream is used to
read data from a source and the OutputStreamis used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.

The two important streams are FileInputStreamand FileOutputStream, which would be


discussed in this tutorial.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file

InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.
[Link] Methods & Description
1. public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated with the file.
Throws an IOException.

2. protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close method of this file output
stream is called when there are no more references to this stream. Throws an IOException
3. public int read(int r)throws IOException{}
This method reads the specified byte of data from the InputStream. Returns an int. Returns the
next byte of data and -1 will be returned if it's the end of the file.

4. public int read(byte[] r) throws IOException{}


This method reads [Link] bytes from the input stream into an array. Returns the total number of
bytes read. If it is the end of the file, -1 will be returned.

5. public int available() throws IOException{}


Gives the number of bytes that can be read from this file input stream. Returns an int.

There are other important input streams available, for more detail you can refer to the following
links −
• ByteArrayInputStream
• DataInputStream

FileOutputStream

FileOutputStream is used to create a file and write data into it. The stream would create a file, if it
doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the file

OutputStream f = new FileOutputStream("C:/java/hello")

Following constructor takes a file object to create an output stream object to write the file. First,
we create a file object using File() method as follows −
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

Once you have OutputStream object in hand, then there is a list of helper methods, which can be
used to write to stream or to do other operations on the stream.
[Link] Method & Description
1 public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated with the file.
Throws an IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close method of this file output
stream iscalled when there are no more references to this stream. Throws an IOException
3 public void write(int w)throws IOException{}
This methods writes the specified byte to the output stream
4 public void write(byte[] w)
Writes [Link] bytes from the mentioned byte array to the OutputStream.

There are other important output streams available, for more detail you can refer to the following
links −
• ByteArrayOutputStream
• DataOutputStream
Example
Following is the example to demonstrate InputStream and OutputStream –

import [Link].*;
public class fileStreamTest {
public static void main(String args[]) {
try {
byte bWrite [] = {11,21,3,40,5};
OutputStreamos = new FileOutputStream("[Link]");
for(int x = 0; x <[Link] ; x++) {
[Link]( bWrite[x] ); // writes the bytes
}
[Link]();
InputStream is = new FileInputStream("[Link]");
int size = [Link]();
for(int i = 0; i< size; i++) {
[Link]((char)[Link]() + " ");
}
[Link]();
} catch (IOException e) {
[Link]("Exception");
}
}
}
The above code would create file [Link] and would write given numbers in binary format. Same
would be the output on the stdout screen.
File Navigation and I/O

There are several other classes that we would be going through to get to know the basics of File
Navigation and I/O.
• File Class
• FileReader Class
• FileWriter Class

Directories in Java
A directory is a File which can contain a list of other files and directories. You use File object to
create directories, to list down files available in a directory. For complete detail, check a list of all
the methods which you can call on File object and what are related to directories.
Creating Directories
There are two useful File utility methods, which can be used to create directories −
• The mkdir( ) method creates a directory, returning true on success and false on failure.
Failure indicates that the path specified in the File object already exists, or that the
directory cannot be created because the entire path does not exist yet.
• The mkdirs() method creates both a directory and all the parents of the directory.
Following example creates "/tmp/user/java/bin" directory −
Example
import [Link];
public class CreateDir {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
[Link]();
}
}
Compile and execute the above code to create "/tmp/user/java/bin".
Note − Java automatically takes care of path separators on UNIX and Windows as per
conventions. If you use a forward slash (/) on a Windows version of Java, the path will still
resolve correctly.

Listing Directories
You can use list( ) method provided by File object to list down all the files and directories
available in a directory as follows −
Example
import [Link];
public class ReadDir {
public static void main(String[] args) {
File file = null;
String[] paths;
try {
// create new file object
file = new File("/tmp");
// array of files and directory
paths = [Link]();
// for each name in the path array
for(String path:paths) {
// prints filename and directory name
[Link](path);
}
} catch (Exception e) {
// if any error occurs
[Link]();
}
}
}
This will produce the following result based on the directories and files available in
your /tmp directory −
Output
[Link]
[Link]
[Link]
[Link]
MODULE-III

Exception Handling and Multithreading: Exception handling and Multithreading-- Concepts of


exception handling, benefits of exception handling, Termination or resumptive models, exception hierarchy,
usage of try, catch, throw, throws and finally, built in exceptions, creating own exception subclasses. String
handling, Exploring [Link]. Differences between multithreading and multitasking, thread life cycle,
creating threads, thread priorities, synchronizing threads, inter thread communication, thread groups,
daemon threads. Enumerations, autoboxing, annotations, generics.

Exception Handling

Definition

An exception is an abnormal condition that arises in a code sequence at run time. In other
words, an exception is a run-time error. Java’s exception handling brings run-time error
management into the object-oriented world.

Reasons for Exception Occurrence


Several reasons lead to the occurrence of an exception. A few of them are as follows.
 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.

Types of Exception

In java, exceptions have categorized into two types, and they are as follows.

 Checked Exception - An exception that is checked by the compiler at the time of compilation is called a
checked exception.
 Unchecked Exception - An exception that can not be caught by the compiler but occurrs at the time of
program execution is called an unchecked exception.

How exceptions handled in Java?

In java, the exception handling mechanism uses five keywords namely try, catch, finally, throw, and throws.
In java, exceptions are mainly categorized into two types, and they are as follows.

 Checked Exceptions
 Unchecked Exceptions

Checked Exceptions
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

The checked exception is also known as a compile-time exception.


Let's look at the following example program for the checked exception method.

Example - Checked Exceptions

import [Link].*;
public class CheckedExceptions {
public static void main(String[] args) {
File f_ref = new File("C:\\Users\\User\\Desktop\\Today\\[Link]");
try {
FileReaderfr = new FileReader(f_ref);
}catch(Exception e) {
[Link](e);
}

Unchecked Exceptions
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
The unchecked exception is also known as a runtime exception.

Let's look at the following example program for the unchecked exceptions.
Example - Unchecked Exceptions
public class UncheckedException {
public static void main(String[] args) {
int list[] = {10, 20, 30, 40, 50};
[Link](list[6]); //ArrayIndexOutOfBoundsException
String msg=null;
[Link]([Link]()); //NullPointerException
String name="abc";
int i=[Link](name); //NumberFormatException
}

BENEFITS OF EXCEPTION HANDLING:


• Exception handling enables you to create applications that can resolve (or handle)
exceptions.
• This feature enables programmers to write robust and fault-tolerant programs (i.e.,
programs that are able to deal with problems that may arise and continue
executing).
Termination or Resumptive Model:
In java, there are two exception models. Java programming language has two models of exception handling. The
exception models that java suports are as follows.

 Termination Model
 Resumptive Model

Let's look into details of each exception 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.
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.

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 Class Hierarchy


In java, the built-in classes used to handle exceptions have the following class hierarchy.
USAGE OF TRY CATCH THROW THROWS AND FINALLY

we have seen the basics of exception handling in Java along with the various exceptions supported by Java
Exception class. We also discussed the NullPointerException in detail.

We can include exceptions in our program by using certain keywords that are provided in Java. These keywords
define various blocks of code that facilitate defining and handling exceptions.

To handle Exceptions, Java provides several methods, such as:


 try
 catch
 finally
 Throw
 Throws

try block
The try block is a domain that has a list of statements in which exceptions may occur. Try block
cannot be used alone; therefore, it is always accompanied by either catch block, finally block, or
both.
Syntax:

try{
//code that may throw an exception
} catch(Exception_class_Name ref){
//rest of the code
}
Nested try block
As the name implies, a nested try block is a try block inside a try block.
Example:

public class Main {


// main function
public static void main(String args[]) {
try {
try {
// we try to divide a number by 0.
// this will create an Arithmetic Exception
int x = 5 / 0;
}
// this catch block will handle
// Arithmetic Exception
catch (ArithmeticException e)
{
[Link]("Arithmetic Exception handled in this catch block");
}
try {
int arr[] = { 5, 0 };
[Link](arr[3]);
}
// this catch block will handle
// Array Index Out of Bounds Exeception
catch (ArrayIndexOutOfBoundsException e)
{
[Link]("Array Index Out of Bounds Exception is handled in this catch block");
}
} catch (Exception exception) {
[Link]("remaining code");
}
}
}

Output:
catch block

The catch block


ock is a method that is utilized to grasp exceptional cases. It always accompanies try block. Finally
block can accompany a catch block after it accompanies a try block. A number of catch blocks can be linked with
a try block. It can handle many exception cases in all linked blocks. The particular catch block assigned the code
with exception handles the exception.

try {
//statements that may give an exception
} catch (exception(type) e(object)) {
//error handling code
}
Multi-Catch block
If you need to perform
rform multiple tasks in response to multiple exceptions, you can use the multi
multi-catch
catch block.

Example:

import [Link].*;
public class Main {
// main function
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String> ();
[Link]("Coding");
[Link]("Ninjas");
try {
String wrongAccess = [Link](5);
} catch (ArithmeticException ae) {
[Link]("Wrong arithmetic expression. Please try again!");
} catch (IndexOutOfBoundsExceptionindxExcep) {
[Link]
[Link]("You
tln("You tried to access wrong index. Please check and try again!");
} catch (Exception e) {
[Link]("This will handle any exception!");
}
}
}

Output:

throw block

In Exception Handling, the throw keyword explicitly throws an exception from a method or constructor. We can
throw either checked or unchecked exceptions in Java by throw keyword. The "throw" keyword is mainly used to
throw a custom exception. The only object of the throwable class or its subclasses can be thrown. When a throw
thro
statement is encountered, program execution is halted, and the nearest catch statement is searched for a matching
kind of exception.

Example:

public class ThrowExample {


static void checkEligibilty(int stuage, int stuweight) {
// check if the student's age is less than 15
// and the student's weight is greater than 45
if (stuage<15 &&stuweight<45) {
throw new ArithmeticException("Student is not eligible for registration");
} else {
[Link]("Student Entry is Valid!!");
}
}
public static void main(String args[]) {
[Link]("Welcome to the Registration process!!");
checkEligibilty(10, 39);
[Link]("Have a nice day..");
}
}

Output:

throws block

Any method that might cause exceptions must identify all of the exceptions that can occur during its execution.
The programmer calling the method is aware of which exceptions must be handled. The throws keyword can be
used to do this.

Example:

import [Link].*;
class ThrowExample {
void myMethod(int num) throws IOException, ClassNotFoundException {
if (num == 1)
throw new IOException("IOException Occurred");
else
throw new ClassNotFoundException("ClassNotFoundException");
}
}
public class Main {
public static void main(String args[]) {
try {
ThrowExample obj = new ThrowExample();
[Link](1);
} catch (Exception ex) {
[Link](ex);
}
}
}
Finally Blocks

A finally keyword is used to create a block of code that follows a try block. A finally block of code is always
executed whether an exception has occurred or not. Using a finally block, it lets you run any cleanup type
statements that you want to execute, no matter what happens in the protected code. A finally block appears at the
end of catch block. finally blocks are used to nullify the object references and closing the I/O streams.

The finally block always executes when the try block exits. This ensures that the finally block is executed even if
an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the
programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup
code in a finally block is always a good practice, even when no exceptions are anticipated.

The runtime system always executes the statements within the finally block regardless of what happens within
the try block. So it's the perfect place to perform cleanup.

Syntax

finally {
// cleanup code
}

Example

The following finally block for the writeList method cleans up and then closes the PrintWriter and FileWriter.
finally {
if (out != null) {
[Link]("Closing PrintWriter");
[Link]();
} else {
[Link]("PrintWriter not open");
}
if (f != null) {
[Link]("Closing FileWriter");
[Link]();
}
}

Rethrow an Exception

Normally, catch block are used to handle the exceptions raised in the try block. The exception can re-throw using
throw keyword, if catch block is unable to handle it. This process is called as re-throwing an exception.

publicclass Main {

public int test(int n1, int n2){


try{
return n1/n2;
}catch(ArithmeticException e){
throw e;
}
}

publicstaticvoidmain(String[]args){
Main main=newMain();
try{
[Link]([Link](30, 0));
}catch(Exception e){
[Link]();
}
}

}
Output:

[Link]:/ by zero
at [Link]([Link])
at [Link]([Link])
Difference Between Errors and Exception

Java -Built-in Exceptions

Java defines several exception classes inside the standard package [Link].

The most general of these exceptions are subclasses of the standard type RuntimeException. Since [Link] is
implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically
available.

Java defines several other types of exceptions that relate to its various class libraries. Following is the list of Java
Unchecked RuntimeException.

[Link]. Exception & Description

ArithmeticException
1
Arithmetic error, such as divide-by-zero.

ArrayIndexOutOfBoundsException
2
Array index is out-of-bounds.

ArrayStoreException
3
Assignment to an array element of an incompatible type.

4 ClassCastException
Invalid cast.

IllegalArgumentException
5
Illegal argument used to invoke a method.

IllegalMonitorStateException
6
Illegal monitor operation, such as waiting on an unlocked thread.

IllegalStateException
7
Environment or application is in incorrect state.

IllegalThreadStateException
8
Requested operation not compatible with the current thread state.

IndexOutOfBoundsException
9
Some type of index is out-of-bounds.

NegativeArraySizeException
10
Array created with a negative size.

NullPointerException
11
Invalid use of a null reference.

NumberFormatException
12
Invalid conversion of a string to a numeric format.

SecurityException
13
Attempt to violate security.

StringIndexOutOfBounds
14
Attempt to index outside the bounds of a string.

UnsupportedOperationException
15
An unsupported operation was encountered.

Following is the list of Java Checked Exceptions Defined in [Link].

[Link]. Exception & Description

ClassNotFoundException
1
Class not found.

CloneNotSupportedException
2
Attempt to clone an object that does not implement the Cloneable interface.

IllegalAccessException
3
Access to a class is denied.

InstantiationException
4
Attempt to create an object of an abstract class or interface.

InterruptedException
5
One thread has been interrupted by another thread.
NoSuchFieldException
6
A requested field does not exist.

NoSuchMethodException
7
A requested method does not exist.

Creating own Exception Sub classes:


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.
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.
Let's look at the following Java code that illustrates the creation of user-defined exception.
Example
import [Link];
class NotEligibleException extends Exception{
NotEligibleException(String msg){
super(msg);
}
}

class VoterList{
int age;
VoterList(int age){
[Link] = age;
}
void checkEligibility() {
try {
if(age < 18) {
throw new NotEligibleException("Error: Not eligible for vote due to under age.");
}
[Link]("Congrates! You are eligible for vote.");
}
catch(NotEligibleException nee) {
[Link]([Link]());
}
}
public static void main(String args[]) {
Scanner input = new Scanner([Link]);
[Link]("Enter your age in years: ");
int age = [Link]();
VoterList person = new VoterList(age);
[Link]();
}
}
String Handling:
A string is a sequence of characters surrounded by double quotations. In a java programming language, a string is
the object of a built-in class String.
In the background, the string values are organized as an array of a character data type.
The string created using a character array cannot be extended. It does not allow to append more characters after its
definition, but it can be modified.
Let's look at the following example java code.
Example

char[] name ={'J','a','v','a',' ','T','u','t','o','r','i','a','l','s'};


//name[14] = '@'; //ArrayIndexOutOfBoundsException
name[5]='-';
[Link](name);

The String class defined in the package [Link] package. The String class
implements Serializable, Comparable, and CharSequence interfaces.
The string created using the String class can be extended. It allows us to add more characters after its definition,
and also it can be modified.
Let's look at the following example java code.

Example

StringsiteName="[Link]";
siteName="[Link]";

Creating String object in java

In java, we can use the following two ways to create a string object.

 Using string literal


 Using String constructor

Let's look at the following example java code.


Example

String title ="Java Tutorials"; // Using literals


StringsiteName=newString("[Link]"); // Using constructor

String handling methods

In java programming language, the String class contails various methods that can be used to handle string data
values. It containg methods like concat( ), compareTo( ), split( ), join( ), replace( ), trim( ), length( ), intern( ),
equals( ), comparison( ), substring( ), etc.
The following table depicts all built-in methods of String class in java.

Return
Method Description Value
Return
Method Description Value

charAt(int) Finds the character at given index char

length() Finds the length of given string int

compareTo(String) Compares two strings int

compareToIgnoreCase(String) Compares two strings, ignoring case int

concat(String) Concatenates the object string with argument string. String

contains(String) Checks whether a string contains sub-string boolean

contentEquals(String) Checks whether two strings are same boolean

equals(String) Checks whether two strings are same boolean

equalsIgnoreCase(String) Checks whether two strings are same, ignoring case boolean

startsWith(String) Checks whether a string starts with the specified string boolean

endsWith(String) Checks whether a string ends with the specified string boolean

getBytes() Converts string value to bytes byte[]

hashCode() Finds the hash code of a string int

indexOf(String) Finds the first index of argument string in object string int

lastIndexOf(String) Finds the last index of argument string in object string int
Return
Method Description Value

isEmpty() Checks whether a string is empty or not boolean

replace(String, String) Replaces the first string with second string String

replaceAll(String, String) Replaces the first string with second string at all String
occurrences.

substring(int, int) Extracts a sub-string from specified start and end String
index values

toLowerCase() Converts a string to lower case letters String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends String

toString(int) Converts the value to a String object String

split(String) splits the string matching argument string String[]

Let's look at the following example java code.


Java Program

publicclassJavaStringExample{

publicstaticvoidmain(String[]args){
String title ="Java Tutorials";
StringsiteName="[Link]";
[Link]("Length of title: "+[Link]());
[Link]("Char at index 3: "+[Link](3));
[Link]("Index of 'T': "+[Link]('T'));
[Link]("Last index of 'a': "+[Link]('a'));
[Link]("Empty: "+[Link]());
[Link]("Ends with '.com': "+[Link](".com"));
[Link]("Equals: "+[Link](title));
[Link]("Sub-string: "+[Link](9,14));
[Link]("Upper case: "+[Link]());
}

When we run this code, it produce the following output.

Exploring [Link] Package:


It is a Java package like other packages in Java. It is the one that contains Java collections framework classes. The
import is a Java keyword used for importing a Java class or entire package.
For eg.
import [Link]
Use of [Link] In java?
The Java util ([Link]) package contains a collection framework. It contains collection classes, date and time,
event models, and various utility classes. You can use all these classes and methods on importing this ([Link])
package.
The use of java. util package is as follows:
 It can be used for Java collections.
 It can be used for internalization-supported classes from this package.
 It can be used for random number generation.
 It can be used for string parsing.
 It can be used for base64 encoding and decoding.
Some important used classes.
 Arrays: This class consists of various methods for manipulating arrays.
import [Link];
int[] arr = new int[n];
 ArrayList: This class implements the resizable-array list interface.
import [Link];
ArrayList<Integer> list = new ArrayList<>();
 Collections: This class contains exclusively static methods that work or return collection.

 Date: This class addresses a particular moment on schedule with millisecond accuracy.

 HashMap: The HashMap class Hash table-based execution of the Map interface.
import [Link];
HashMap<string, Integer> map = new HashMap<>();
 HashSet: The HashSet is a collection of items in which every item is unique.
 HashTable:- The HashTable class implements a hash table, which maps keys to values.

 LinkedList: The LinkedList class Doubly Linked List implementation of the List and Deque interfaces.

 Objects: An Object can be defined as a character and behavior.

 Random: A random class can generate a list of random numbers.

 Scanner: A simple text scanner can parse primitive types and strings using regular expressions.

 StringTokenizer: String tokenizer allows you to break a String into tokens.

 TreeSet: The TreeSet class A NavigableSet implementation based on a TreeMap.

[Link] Package Enum


Enum Class Description

[Link] Used for BigDecimal formatting

[Link] Used for locale categories

[Link] Provides constants for filtering mode selection

[Link] Used to specify the type defined in ISO 3166

[Link] Package Exceptions


Exception Class Description

ConcurrentModificationException When an object is modified concurrently without permission

EmptyStackException Indicates that the Stack is empty

InputMismatchException When the user does not provide valid input

MissingResourceException Indicates absence of a resource

NoSuchElementException Indicates absence of requested element

PatternSyntaxException Indicates syntax error in a regular-expression pattern

IllegalFormatException Indicates that a format string contains illegal syntax

MULTITHREADING
Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process,


process, a smallest unit of processing. Multiprocessing and
multithreading,
ltithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context
context-switching between the
threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can performmultiple
operations at same time.
2) You can perform many operations
rations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.

Life cycle of a Thread (Thread States)


A thread can be in one of the five states. According to sun, there is only 4 st
states in thread life
cycle in java new, runnable, non-runnable
runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java th
thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

 New — A thread is in the “New” state, when an object of the thread class is instantiated but the “start” method
is not invoked.
 Runnable — When the “start”” method has been invoked on the thread object. In this state, the thread is either
waiting for the scheduler to pick it up for execution or it’s already running. Let us call the state when the thread
is already picked for execution, the “running” state.
 Running state: Running means Processor (CPU) has allocated time slot to thread for its execution. When
thread scheduler selects a thread from the runnable state for execution, it goes into running state.
 Non-Runnable(Blocked , Timed-Waiting)— When the thread is alive, i.e., the thread class object exists, but
it cannot be picked by the scheduler for execution. It is temporarily inactive.
 Terminated — When the thread completes execution of its “run” method, it goes into the “terminated” state.
At this stage, the task of the thread is completed.

Creation of thread

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:

 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the [Link] calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public [Link](): returns the state of the thread.
13. public booleanisAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public booleanisDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public booleanisInterrupted(): tests if the thread has been interrupted.

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().

1. 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.

Java Thread Example by extending Thread class


class Multi extends Thread{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
[Link]();
}}
Output:thread is running...

Java Thread Example by implementing Runnable interface


class Multi3 implements Runnable{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
[Link]();
}}
Output:thread is running...

Develop a java program how to create multiple threads.

package demotest;
public class GuruThread1 implements Runnable
{
public static void main(String[] args) {
Thread guruThread1 = new Thread("Guru1");
Thread guruThread2 = new Thread("Guru2");
Thread guruThread3 = new Thread("Guru3");
[Link]();
[Link]();
[Link]();
[Link]("Thread names are following:");
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
} output:
@Override Guru1
public void run() { Guru2
} Guru3
}
Priority of a Thread (Thread Priority):
Each thread have a priority. Priorities are represented by a number between 1 and 10. In mostcases, thread
schedular schedules the threads according to their priority (known as preemptivescheduling). But it is not
guaranteed because it depends on JVM specification that whichscheduling it chooses.

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is and
the value of MAX_PRIORITY is 10.

Example of priority of a Thread:


class TestMultiPriority1 extends Thread{
public void run(){
[Link]("running thread name is:"+[Link]().getName());
[Link]("running thread priority is:"+[Link]().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

Java synchronized method


If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it
when the thread completes its task.

Example of inter thread communication in java

Let's see the simple example of inter thread communication.


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

Thread Group:

 Java provides a convenient way to group multiple threads in a single object. In such a
way, we cansuspend, resume or interrupt a group of threads by a single method call.

 Java thread group is implemented


lemented by [Link] class.

 Every thread in a thread group has a parent thread except the initial thread and hence it
represents atree structure.
 It can access all the information about its own thread group.
 ThreadGroup class is very useful when we want to perform the same operation on multiple threads.
ThreadGroup Methods

ThreadGroup Example
public class ThreadGroupDemo implements Runnable{public void run() {
[Link]([Link]().getName());
}
public static void main(String[] args) {
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");

Thread t1 = new Thread(tg1, runnable,"one");


[Link]();
Thread t2 = new Thread(tg1, runnable,"two");
[Link]();
Thread t3 = new Thread(tg1, runnable,"three");
[Link]();
[Link]("Thread Group Name: "+[Link]());[Link]();

}
}
Inter-thread Communication
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.

It is implemented by following methods of Object class:

o wait()
o notify()
o 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 InterruptedException It waits until object is notified.

public final void wait(long timeout)throws It waits for the specified amount of time.
InterruptedException

2) notify() method

The 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()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor.

Syntax:public final void notifyAll()

BUnderstanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:


1. Threads enter to acquire lock.

2. Lock is acquired by on thread.

3. Now 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, 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.

Difference between wait and sleep?

Let's see the important differences between wait and sleep methods.

wait() sleep()

The wait() method releases the lock. The sleep() method doesn't release the lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

It should be notified by notify() or After the specified amount of time, sleep is


notifyAll() methods completed.

Daemon Thread:

A daemon thread is a low-priority thread whose purpose is to provide services to user threads.

Since daemon threads are only required when the user threads are operating, they do not prevent the JVM from
quitting after all the user threads have completed execution.

Infinite loops, which are common in daemon threads, do not cause issues because no code
(including finally blocks) is executed until all the user threads have completed execution. Therefore, daemon
threads should not be used for I/O activities.

How to create daemon threads in Java

We can use the setDaemon method of the Thread class to create a daemon thread.
Syntax: public final void setDaemon(boolean on)

Points to remember for Daemon Thread in Java


 It provides services to user threads for background supporting tasks. It has no role in life than to
serve user threads.
 Its life depends on user threads.
 It is a low priority thread.
Methods for Java Daemon thread by Thread class

The [Link] class provides two methods for java daemon thread.

No. Method Description

1) public void setDaemon(boolean status) mark the current thread as daemon thread or user thread.

2) public boolean isDaemon() is used to check that current is daemon.

Example Program:

// Java program to demonstrate the usage of


// setDaemon() and isDaemon() method.

public class DaemonThread extends Thread


{
public DaemonThread(String name){
super(name);
}

public void run()


{
// Checking whether the thread is Daemon or not
if([Link]().isDaemon())
{
[Link](getName() + " is Daemon thread");
}

else
{
[Link](getName() + " is User thread");
}
}

public static void main(String[] args)


{

DaemonThread t1 = new DaemonThread("t1");


DaemonThread t2 = new DaemonThread("t2");
DaemonThread t3 = new DaemonThread("t3");
// Setting user thread t1 to Daemon
[Link](true);

// starting first 2 threads


[Link]();
[Link]();

// Setting user thread t3 to Daemon


[Link](true);
[Link]();
}
}

Exceptions in a Daemon thread


If you call the setDaemon() method after starting the thread, it would throw IllegalThreadStateException.

// Java program to demonstrate the usage of


// exception in Daemon() Thread

public class DaemonThread extends Thread


{
public void run()
{
[Link]("Thread name: " + [Link]().getName());
[Link]("Check if its DaemonThread: "
+ [Link]().isDaemon());
}

public static void main(String[] args)


{
DaemonThread t1 = new DaemonThread();
DaemonThread t2 = new DaemonThread();
[Link]();

// Exception as the thread is already started


[Link](true);

[Link]();
}
}

Java Enumerations
Enumerations was added to Java language in JDK5. Enumeration means a list of named constant. In Java,
enumeration defines a class type. An Enumeration can have constructors, methods and instance variables. It is
created using enum keyword. Each enumeration constant is public, static and final by default. Even though
enumeration defines a class type and have constructors, you do not instantiate an enum using new. Enumeration
variables are used and declared in much a same way as you do a primitive variable.

How to Define and Use an Enumeration

[Link] enumeration can be defined simply by creating a list of enum variable. Let us take an example for list of
Subject variable, with different subjects in the list.
/Enumeration defined
enum Subject
{
Java, Cpp, C, Dbms
}
[Link] Java, Cpp, C and Dbms are called enumeration constants. These are public, static and final by
default.

[Link] of Enumeration can be defined directly without any new keyword.

Example of Enumeration

Lets create an example to define an enumeration and access its constant by using enum reference variable.
enum WeekDays{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

class Demo
{
public static void main(String args[])
{
WeekDays wk; //wk is an enumeration variable of type WeekDays
wk = [Link]; //wk can be assigned only the constants defined under enum
type Weekdays
[Link]("Today is "+wk);
}
}
Output:

Today is SUNDAY

Example of applying Enum on a switch statement

class EnumExample5{
enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDA
Y}
public static void main(String args[]){
Day day=[Link];

switch(day){
case SUNDAY:
[Link]("sunday");
break;
case MONDAY:
[Link]("monday");
break;
default:
[Link]("other day");
}
}}
Output:
monday

Example : Enumeration in If-Else


Enumeration can be used in if statement to compare a value with some predefined constants. Here we are using an
enumeration with if else statement.

enum WeekDays{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

class Demo {
public static void main(String args[])
{
WeekDays weekDays = [Link];

if(weekDays == [Link] || weekDays == [Link])


[Link]("It is Weekend");
else
[Link]("It is weekday: "+weekDays);

}
}

OUTPUT:
It is weekday: WEDNESDAY

Example: Traversing Enumeration Elements

We can iterate enumeration elements by calling its static method values(). This method returns an array of all the
enum constants that further can be iterate using for loop. See the below example.

enum WeekDays{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
class Demo {
public static void main(String args[])
{
WeekDays[] weekDays = [Link]();

for(WeekDays weekday : weekDays ){

[Link](weekday);
}
}
}
OUTPUT:
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
Values() and ValueOf() method
All the enumerations predefined methods values() and valueOf(). values() method returns an array of enum-type
containing all the enumeration constants in it. Its general form is,

public static enum-type[ ] values()

valueOf() method is used to return the enumeration constant whose value is equal to the string passed in as
argument while calling this method. It's general form is,

public static enum-type valueOf (String str)


Example of enumeration using values() and valueOf() methods:

Value and valueOf both are static methods of enum type and can be used to access enum elements. Here we are
using both the methods to access the enum elements.

enum Restaurants {
DOMINOS, KFC, PIZZAHUT, PANINOS, BURGERKING
}
class Demo {
public static void main(String args[])
{
Restaurants r;
[Link]("All constants of enum type Restaurants are:");
Restaurants rArray[] = [Link](); //returns an array of constants of type Restaurants
for(Restaurants a : rArray) //using foreach loop
[Link](a);

r = [Link]("DOMINOS");
[Link]("It is " + r);
}
}

OUTPUT:
All constants of enum type Restaurants are:
DOMINOS
KFC
PIZZAHUT
PANINOS
BURGERKING
It is DOMINOS

Points to remember about Enumerations

1. Enumerations are of class type, and have all the capabilities that a Java class has.
2. Enumerations can have Constructors, instance Variables, methods and can even implement Interfaces.
3. Enumerations are not instantiated using new keyword.
4. All Enumerations by default inherit [Link] class.

Enumeration with Constructor, instance variable and Method

Enumeration is similar to class except it cannot be instantiated. It can have methods, constructors, variables etc.
here in this example, we are creating constructor and method in the enum and accessing its constants value using
these.

enum Student
{
John(11), Bella(10), Sam(13), Viraaj(9);
private int age; //variable defined in enum Student
int getage() { return age; } //method defined in enum Student
private Student(int age) //constructor defined in enum Student
{
[Link]= age;
}
}
class Demo
{
public static void main( String args[] )
{
Student S;
[Link]("Age of Viraaj is " +[Link]()+ " years");
}
}
Output:
Age of Viraaj is 9 years
In this example as soon as we declare an enum variable(Student S), the constructor is called once, and it initializes
age for every enumeration constant with values specified with them in parenthesis.

Java Autoboxing - Primitive Type to Wrapper Object

In autoboxing, the Java compiler automatically converts primitive types into their corresponding wrapper class
objects. For example,

int a = 56;

// autoboxing

Integer aObj = a;

Autoboxing has a great advantage while working with Java collections.


Example 1: Java Autoboxing
import [Link];

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

ArrayList<Integer> list = new ArrayList<>();

//autoboxing
[Link](5);
[Link](6);

[Link]("ArrayList: " + list);


}
}
Run Code
Output
ArrayList: [5, 6]

Java Unboxing - Wrapper Objects to Primitive Types


In unboxing, the Java compiler automatically converts wrapper class objects into their corresponding primitive
types. For example,

// autoboxing
Integer aObj = 56;

// unboxing
int a = aObj;

Like autoboxing, unboxing can also be used with Java collections.


Example 2: Java Unboxing
import [Link];

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

ArrayList<Integer> list = new ArrayList<>();

//autoboxing
[Link](5);
[Link](6);

[Link]("ArrayList: " + list);

// unboxing
int a = [Link](0);
[Link]("Value at index 0: " + a);
}
}
Run Code

Output
ArrayList: [5, 6]
Value at index 0: 5

ANNOTATIONS

Annotations in Java provide additional information to the compiler and JVM. An annotation is a tag representing
metadata about classes, interfaces, variables, methods, or fields. Annotations do not impact the execution of the
code that they annotate. Some of the characteristics of annotations are:

 Begin with ‘@’


 Do not alter the execution of the program
 Provide supplemental information and help to link metadata with elements of a program such as classes,
variables, constructs, methods, etc.
 Are different from comments since they can affect how the program is treated by the compiler

Hierarchy of Annotations in Java


Understanding Built-In Annotations
Let's understand the built-in annotations first.

@Override

@Override annotation assures that the subclass method is overriding the parent class method. If it is not so,
compile time error occurs.

Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to mark @Override annotation
that provides assurity that method is overridden.

class Animal{
void eatSomething(){[Link]("eating something");}
}

class Dog extends Animal{


@Override
void eatsomething(){[Link]("eating foods");}//should be eatSomething
}

class TestAnnotation1{
public static void main(String args[]){
Animal a=new Dog();
[Link]();
}}
Output:Comple Time Error

@SuppressWarnings

@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.

import [Link].*;
class TestAnnotation2{
@SuppressWarnings("unchecked")
public static void main(String args[]){
ArrayList list=new ArrayList();
[Link]("sonoo");
[Link]("vimal");
[Link]("ratan");

for(Object obj:list)
[Link](obj);

}}
Now no warning at compile time.

If you remove the @SuppressWarnings("unchecked") annotation, it will show warning at compile time because
we are using non-generic collection.

@Deprecated

@Deprecated annoation marks that this method is deprecated so compiler prints warning. It informs user that it
may be removed in the future versions. So, it is better not to use such methods.
class A{
void m(){[Link]("hello m");}

@Deprecated
void n(){[Link]("hello n");}
}

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

A a=new A();
a.n();
}}

At Compile Time:
Note: [Link] uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.


At Runtime:
hello n

Java Custom Annotations


Java Custom annotations or Java User-defined annotations are easy to create and use. The @interface element is
used to declare an annotation. For example:

1. @interface MyAnnotation{}
Here, MyAnnotation is the custom annotation name.
Points to remember for java custom annotation signature
There are few points that should be remembered by the programmer.
1. Method should not have any throws clauses
2. Method should return one of the following: primitive data types, String, Class, enum or array of these
data types.
3. Method should not have any parameter.
4. We should attach @ just before interface keyword to define annotation.
5. It may assign a default value to the method.

Types of Annotation
There are three types of annotations.
1. Marker Annotation
2. Single-Value Annotation
3. Multi-Value Annotation
1) Marker Annotation
An annotation that has no method, is called marker annotation. For example:

1. @interface MyAnnotation{}
The @Override and @Deprecated are marker annotations.

2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:

@interface MyAnnotation{
int value();
}
We can provide the default value also. For example:

@interface MyAnnotation{
int value() default 0;
}

How to apply Single-Value Annotation

Let's see the code to apply the single value annotation.

1. @MyAnnotation(value=10)

The value can be anything.

3) Multi-Value Annotation

An annotation that has more than one method, is called Multi-Value annotation. For example:

@interface MyAnnotation{
int value1();
String value2();
String value3();
}
}
We can provide the default value also. For example:
@interface MyAnnotation{
int value1() default 1;
String value2() default "";
String value3() default "xyz";
}

How to apply Multi-Value Annotation


Let's see the code to apply the multi-value annotation.
1. @MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")

Built-in Annotations used in custom annotations in java


 @Target
 @Retention
 @Inherited
 @Documented
@Target

@Target tag is used to specify at which type, the annotation is used.

The [Link] enum declares many constants to specify the type of element where
annotation is to be applied such as TYPE, METHOD, FIELD etc. Let's see the constants of ElementType enum:

Element Types Where the annotation can be applied

TYPE class, interface or enumeration

FIELD fields

METHOD methods

CONSTRUCTOR constructors

LOCAL_VARIABLE local variables

ANNOTATION_TYPE annotation type

PARAMETER parameter

Example to specify annoation for a class


@Target([Link])
@interface MyAnnotation{
int value1();
String value2();
}

Example to specify annotation for a class, methods or fields


@Target({[Link], [Link], [Link]})
@interface MyAnnotation{
int value1();
String value2();
}

@Retention

@Retention annotation is used to specify to what level annotation will be available.

RetentionPolicy Availability

[Link] refers to the source code, discarded during compilation. It will not be available in the
compiled class.

[Link] refers to the .class file, available to java compiler but not to JVM . It is included in the class
file.

[Link] refers to the runtime, available to java compiler and JVM .

Example to specify the RetentionPolicy


@Retention([Link])
@Target([Link])
@interface MyAnnotation{
int value1();
String value2();
}

Example of custom annotation: creating, applying and accessing annotation

Let's see the simple example of creating, applying and accessing annotation.

File: [Link]

//Creating annotation
import [Link].*;
import [Link].*;

@Retention([Link])
@Target([Link])
@interface MyAnnotation{
int value();
}

//Applying annotation
class Hello{
@MyAnnotation(value=10)
public void sayHello(){[Link]("hello annotation");}
}

//Accessing annotation
class TestCustomAnnotation1{
public static void main(String args[])throws Exception{

Hello h=new Hello();


Method m=[Link]().getMethod("sayHello");

MyAnnotation manno=[Link]([Link]);
[Link]("value is: "+[Link]());
}}
Output:value is: 10

How built-in annotaions are used in real scenario?

In real scenario, java programmer only need to apply annotation. He/She doesn't need to create and access
annotation. Creating and Accessing annotation is performed by the implementation provider. On behalf of the
annotation, java compiler or JVM performs some additional operations.
@Inherited

By default, annotations are not inherited to subclasses. The @Inherited annotation marks the annotation to be
inherited to subclasses.

@Inherited
@interface ForEveryone { }//Now it will be available to subclass also

@interface ForEveryone { }
class Superclass{}

class Subclass extends Superclass{}

@Documented

The @Documented Marks the annotation for inclusion in the documentation.

Java Generics
Java Generics allows us to create a single class, interface, and method that can be used with different types of
data (objects).

This helps us to reuse our code.

Note: Generics does not work with primitive types (int, float, char, etc).

Java Generics Class


We can create a class that can be used with any type of data. Such a class is known as Generics Class.

Here's is how we can create a generics class in Java:

Example: Create a Generics Class

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

// initialize generic class


// with Integer data
GenericsClass<Integer> intObj = new GenericsClass<>(5);
[Link]("Generic Class returns: " + [Link]());

// initialize generic class


// with String data
GenericsClass<String> stringObj = new GenericsClass<>("Java Programming");
[Link]("Generic Class returns: " + [Link]());
}
}

// create a generics class


class GenericsClass<T> {

// variable of T type
private T data;

public GenericsClass(T data) {


[Link] = data;
}

// method that return T type variable


public T getData() {
return [Link];
}
}
Output

Generic Class returns: 5


Generic Class returns: J

Java Generics Method


Similar to the generics class, we can also create a method that can be used with any type of data. Such a class
is known as Generics Method.

Here's is how we can create a generics method in Java:

Example: Create a Generics Method

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

// initialize the class with Integer data


DemoClass demo = new DemoClass();

// generics method working with String


demo.<String>genericsMethod("Java Programming");

// generics method working with integer


demo.<Integer>genericsMethod(25);
}
}

class DemoClass {

// creae a generics method


public <T> void genericsMethod(T data) {
[Link]("Generics Method:");
[Link]("Data Passed: " + data);
}
}

Output

Generics Method:
Data Passed: Java Programming
Generics Method:
Data Passed: 25

Bounded Types
In general, the type parameter can accept any data types (except primitive types).

However, if we want to use generics for some specific types (such as accept data of number types) only, then
we can use bounded types.
In the case of bound types, we use the extends keyword. For example,

<T extends A>


This means T can only accept data that are subtypes of A.

Example: Bounded Types


class GenericsClass <T extends Number> {

public void display() {


[Link]("This is a bounded type generics class.");
}
}

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

// create an object of GenericsClass


GenericsClass<String> obj = new GenericsClass<>();
}
}
Advantages of Java Generics
1. Code Reusability
With the help of generics in Java, we can write code that will work with different types of data. For example,

public <T> void genericsMethod(T data) {...}


Here, we have created a generics method. This same method can be used to perform operations on integer
data, string data, and so on.

2. Compile-time Type Checking


The type parameter of generics provides information about the type of data used in the generics code. For
example,
// using Generics
GenericsClass<Integer> list = new GenericsClass<>();
Here, we know that GenericsClass is working with Integer data only.

Now, if we try to pass data other than Integer to this class, the program will generate an error at compile
time.

3. Used with Collections


The collections framework uses the concept of generics in Java. For example,

// creating a string type ArrayList


ArrayList<String> list1 = new ArrayList<>();

// creating a integer type ArrayList


ArrayList<Integer> list2 = new ArrayList<>();

You might also like