Module 3 Oops
Module 3 Oops
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.
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{
publicclassInterfaceVariablesExampleimplementsSampleInterface{
publicstaticvoidmain(String[]args){
The ‘class’ keyword is used to create a The ‘interface’ keyword is used to create an
class. interface.
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’.
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.
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.
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]);
$javac [Link]
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
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.
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
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.
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.
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
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
}
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.
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.
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.
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:
Output:
catch block
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:
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 {
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 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.
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.
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.
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
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]";
In java, we can use the following two ways to create a string object.
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
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
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
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
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]());
}
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.
Scanner: A simple text scanner can parse primitive types and strings using regular expressions.
MULTITHREADING
Multithreading in java is a process of executing multiple threads simultaneously.
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.
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
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)
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().
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
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.
When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it
when the thread completes its task.
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.
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");
}
}
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.
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(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.
3) notifyAll() method
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).
6. After completion of the task, thread releases the lock and exits the monitor state of the object.
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.
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.
We can use the setDaemon method of the Thread class to create a daemon thread.
Syntax: public final void setDaemon(boolean on)
The [Link] class provides two methods for java daemon thread.
1) public void setDaemon(boolean status) mark the current thread as daemon thread or user thread.
Example Program:
else
{
[Link](getName() + " is User thread");
}
}
[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.
[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.
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
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
enum WeekDays{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
class Demo {
public static void main(String args[])
{
WeekDays weekDays = [Link];
}
}
OUTPUT:
It is weekday: WEDNESDAY
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]();
[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,
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,
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
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 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.
In autoboxing, the Java compiler automatically converts primitive types into their corresponding wrapper class
objects. For example,
int a = 56;
// autoboxing
Integer aObj = a;
class Main {
public static void main(String[] args) {
//autoboxing
[Link](5);
[Link](6);
// autoboxing
Integer aObj = 56;
// unboxing
int a = aObj;
class Main {
public static void main(String[] args) {
//autoboxing
[Link](5);
[Link](6);
// 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:
@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 TestAnnotation1{
public static void main(String args[]){
Animal a=new Dog();
[Link]();
}}
Output:Comple Time Error
@SuppressWarnings
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.
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;
}
1. @MyAnnotation(value=10)
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";
}
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:
FIELD fields
METHOD methods
CONSTRUCTOR constructors
PARAMETER parameter
@Retention
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.
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{
MyAnnotation manno=[Link]([Link]);
[Link]("value is: "+[Link]());
}}
Output:value is: 10
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{}
@Documented
Java Generics
Java Generics allows us to create a single class, interface, and method that can be used with different types of
data (objects).
Note: Generics does not work with primitive types (int, float, char, etc).
class Main {
public static void main(String[] args) {
// variable of T type
private T data;
class Main {
public static void main(String[] args) {
class DemoClass {
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,
class Main {
public static void main(String[] args) {
Now, if we try to pass data other than Integer to this class, the program will generate an error at compile
time.