[go: up one dir, main page]

0% found this document useful (0 votes)
66 views61 pages

Java Unit-3

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 61

UNIT - III

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 java.util.
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.
Unit-3
Exception Handling and Multithreading
Concepts of exception handling:
An exception in java programming is an abnormal situation that is araised during the program
execution. In simple words, an exception is a problem that arises at the time of program
execution.
When an exception occurs, it disrupts the program execution flow. When an exception
occurs, the program execution gets terminated, and the system generates an error. We use the
exception handling mechanism to avoid abnormal termination of program execution.
Java programming language has a very powerful and efficient exception handling mechanism
with a large number of built-in classes to handle most of the exceptions automatically.
Java programming language has the following class hierarchy to support the exception
handling mechanism.

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.
We will learn all these concepts in this series of tutorials.

Exception Types in Java


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
In the exception class hierarchy, the checked exception classes are the direct children of
the Exception class.
The checked exception is also known as a compile-time exception.
Let's look at the following example program for the checked exception method.
Example - Checked Exceptions

import java.io.*;

public class CheckedExceptions {

public static void main(String[] args) {

File f_ref = new File("C:\\Users\\User\\Desktop\\Today\\Sample.txt");


try {
FileReader fr = new FileReader(f_ref);
}catch(Exception e) {
System.out.println(e);
}

}
}

When we run the above program, it produces the following output.

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
In the exception class hierarchy, the unchecked exception classes are the children of
RuntimeException class, which is a child class of Exception class.
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};

System.out.println(list[6]);
//ArrayIndexOutOfBoundsException

String msg=null;
System.out.println(msg.length()); //NullPointerException

String name="abc";
int i=Integer.parseInt(name); //NumberFormatException
}

When we run the above program, it produces the following output.

Exception Models in Java


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.

Uncaught Exceptions in Java


In java, assume that, if we do not handle the exceptions in a program. In this case, when an
exception occurs in a particular function, then Java prints a exception message with the help
of uncaught exception handler.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Java programming language has a very strong exception handling mechanism. It allow us to
handle the exception use the keywords like try, catch, finally, throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the exception occurs
and terminates the thread.
The Division by zero exception is one of the example for uncaught exceptions. Look at the
following code.
Example

import java.util.Scanner;

public class UncaughtExceptionExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);

}
}

When we execute the above code, it produce the following output for the value a = 10 and b
= 0.

In the above example code, we are not used try and catch blocks, but when the value of b is
zero the division by zero exception occurs and it caught by the default exception handler.

try and catch in Java

In java, the trytry and catch, both are the keywords used for exception handling.
The keyword try is used to define a block of code that will be tests the occurence of an
exception. The keyword catch is used to define a block of code that handles the exception
occured in the respective try block.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Both try and catch are used as a pair. Every try block must have one or more catch blocks.
We cannot use try without atleast one catch, and catch alone can be used (catch without try is
not allowed).
The following is the syntax of try and catch blocks.
Syntax

try{
...
code to be tested
...
}
catch(ExceptionType object){
...
code for handling the exception
...
}

Consider the following example code to illustrate try and catch blocks in Java.
Example

import java.util.Scanner;

public class TryCatchExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.println("Enter the a and b values: ");
try {
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO");
}
}
}

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


In the above example code, when an exception occurs in the try block the execution control
transfered to the catch block and the catch block handles it.
Multiple catch clauses
In java programming language, a try block may has one or more number of catch blocks.
That means a single try statement can have multiple catch clauses.
When a try block has more than one catch block, each catch block must contain a different
exception type to be handled.
The multipe catch clauses are defined when the try block contains the code that may lead to
different type of exceptions.
The try block generates only one exception at a time, and at a time only one catch block is
executed.
When there are multiple catch blocks, the order of catch blocks must be from the most
specific exception handler to most general.
The catch block with Exception class handler must be defined at the last.
Let's look at the following example Java code to illustrate multiple catch clauses.
Example

public class TryCatchExample {

public static void main(String[] args) {

try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[10] = list[2] / list[4];
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO.");
}
catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has occured.");
}
catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}

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

Nested try statements


The java allows to write a try statement inside another try statement. A try block within
another try block is known as nested try block.
When there are nested try blocks, each try block must have one or more seperate catch
blocks.
Let's look at the following example Java code to illustrate nested try statements.
Example

public class TryCatchExample {

public static void main(String[] args) {

try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[0] = list[2] / list[4];
try {
list[10] = 100;
}
catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has
occured.");
}
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO.");
}
catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}

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

In case of nested try blocks, if an exception occured in the inner try block and it's catch
blocks are unable to handle it then it transfers the control to the outer try's catch block to
handle it.

throw, throws, and finally keywords in Java

In java, the keywords throw, throws, and finally are used in the exception handling concept.
Let's look at each of these keywords.
throw keyword in Java
The throw keyword is used to throw an exception instance explicitly from a try block to
corresponding catch block. That means it is used to transfer the control from try block to
corresponding catch block.
The throw keyword must be used inside the try block. When JVM encounters the throw
keyword, it stops the execution of try block and jump to the corresponding catch block.
Using throw keyword only object of Throwable class or its sub classes can be thrown.
Using throw keyword only one exception can be thrown.
The throw keyword must followed by an throwable instance.
The following is the general syntax for using throw keyword in a try block.
Syntax

throw instance;

Here the instace must be throwable instance and it can be created dynamically using new
operator.
Let's look at the following example Java code to illustrate throw keyword.
Example

import java.util.Scanner;

public class Sample {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);


int num1, num2, result;
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new ArithmeticException("Division by zero is not possible");
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
System.out.println("End of the program");
}
}

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


throws keyword in Java
The throws keyword is used to handle checked exceptions. As we learned in the previous
article that exceptions are of two types: checked and unchecked. Checked exception (compile
time) needs to be handled else the program won’t compile. On the other hand unchecked
exception (Runtime) doesn’t get checked during compilation. Throws keyword is used for
handling checked exceptions. You can declare multiple exceptions using throws keyword.

The throws keyword vs try-catch in Java


You may be wondering why we need throws keyword when we can handle exceptions using
try-catch block in Java. Well, thats a valid question. We already know we can handle
exceptions using try-catch block.

The throws keyword does the same thing that try-catch does but there are some cases where
you would prefer throws over try-catch. For example: Lets say we have a method
myMethod() the statements inside this method can throw either ArithmeticException or
NullPointerException, in this case you can use try-catch as shown below:

public void myMethod()


{
try {
// Statements that might throw an exception
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
}
But suppose you have several such methods that can cause exceptions, in that case it would
be tedious to write these try-catch for each method. The code will become unnecessary long
and will be less-readable.

One way to overcome this problem is by using throws like this: declare the exceptions in the
method signature using throws and handle the exceptions where you are calling this method
by using try-catch.

Another advantage of using this approach is that you will be forced to handle the exception
when you call this method, all the exceptions that are declared using throws, must be handled
where you are calling this method else you will get compilation error.

public void myMethod() throws ArithmeticException, NullPointerException


{
// Statements that might throw an exception
}

public static void main(String args[]) {


try {
myMethod();
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
}

The throws keyword specifies the exceptions that a method can throw to the default handler
and does not handle itself. That means when we need a method to throw an exception
automatically, we use throws keyword followed by method declaration
When a method throws an exception, we must put the calling statement of method in try-
catch block.

Let's look at the following example Java code to illustrate throws keyword.
Example
public class ThrowsExample2
{
void division() throws ArithmeticException,ArrayIndexOutOfBoundsException
{
int list[]=new int[5];
list[2]=10;
list[4]=2;
list[0]=list[2]/list[4];
list[10]=100;
}
public static void main(String[] args)
{
try
{
new ThrowsExample2().division();
}
catch(ArithmeticException ae)
{
System.out.println("Problem info: divide by zero");
}
catch(ArrayIndexOutOfBoundsException aie)
{
System.out.println("Problem info: ArrayIndexOutOfBounds Exception");
}
}
}

Output:
Problem info: ArrayIndexOutOfBounds Exception
finally keyword in Java
The finally keyword used to define a block that must be executed irrespective of exception
occurence.
The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.
Only one finally block is allowed for each try block.
Use of finally block is optional.
Let's look at the following example Java code to illustrate throws keyword.
Example

import java.util.Scanner;

public class FinallyExample {

public static void main(String[] args) {


int num1, num2, result;
Scanner input = new Scanner(System.in);
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new ArithmeticException("Division by zero");
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
finally {
System.out.println("The finally block executes always");
}
System.out.println("End of the program");
}

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


Built-in Exceptions in Java

The Java programming language has several built-in exception class that support exception
handling. Every exception class is suitable to explain certain error situations at run time.All
the built-in exception classes in Java were defined a package java.lang.

List of checked exceptions in Java


The following table shows the list of several checked exceptions.
S.
No. Exception Class with Description

1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and
the specified class cannot be found in the classpath.

2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an
object, but that the object's class does not implement the Cloneable interface.

3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers
do not allow.

4 InstantiationException
It is thrown when an application tries to create an instance of a class using the
newInstance method in class Class , but the specified class object cannot be instantiated
because it is an interface or is an abstract class.

5 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.

6 NoSuchFieldException
It indicates that the class doesn't have a field of a specified name.
S.
No. Exception Class with Description

7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at
compile time, a NoSuchMethodException occurs during reflection when we try to
access a method that does not exist.

List of unchecked exceptions in Java


The following table shows the list of several unchecked exceptions.

S.
No. Exception Class with Description

1 ArithmeticException
It handles the arithmetic exceptions like dividion by zero

2 ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index. The
index is either negative or greater than or equal to the size of the array.

3 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type of
object into an array of objects

4 AssertionError
It is used to indicate that an assertion has failed

5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to another.

6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal or
inappropriate argument.

7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or
has attempted to notify other threads that wait on an object's monitor, without owning
the specified monitor.

8 IllegalStateException
It signals that a method has been invoked at an illegal or inappropriate time.

9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to modify
the state of the thread when it is illegal.

10 IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as an
S.
No. Exception Class with Description

array , vector , string , and so forth.

11 NegativeArraySizeException
It is thrown if an applet tries to create an array with negative size.

12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.

13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or
integer, but the format of the input string is not appropriate or illegal.

14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.

15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is
either negative, or greater than the size of the string itself.

16 UnsupportedOperationException
It is thrown to indicate that the requested operation is not supported.

Creating Own Exceptions in Java


In Java, we can create our own exceptions that are derived classes of the Exception class.
Creating our own Exception is known as custom exception or user-defined exception.
Basically, Java custom exceptions are used to customize the exception according to user
need.
Consider the example 1 in which InvalidAgeException class extends the Exception class.
Using the custom exception, we can have your own exception and message. Here, we have
passed a string to the constructor of superclass i.e. Exception class that can be obtained using
getMessage() method on the object we have created.
In this section, we will learn how custom exceptions are implemented and used in Java
programs.

Why use custom exceptions?


Java exceptions cover almost all the general type of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.
Following are few of the reasons to use custom exceptions:
o To catch and provide specific treatment to a subset of existing Java exceptions.
o Business logic exceptions: These are the exceptions related to business logic and
workflow. It is useful for the application users or the developers to understand the
exact problem.
In order to create custom exception, we need to extend Exception class that belongs to
java.lang package.
Consider the following example, where we create a custom exception named
WrongFileNameException:
1. public class WrongFileNameException extends Exception {
2. public WrongFileNameException(String errorMessage) {
3. super(errorMessage);
4. }
5. }
Note: We need to write the constructor that takes the String as the error message and it is
called parent class constructor.
Example 1:
Let's see a simple example of Java custom exception. In the following code, constructor of
InvalidAgeException takes a string as an argument. This string is passed to constructor of
parent class Exception using the super() method. Also the constructor of Exception class can
be called without using a parameter and calling super() method is not mandatory.
TestCustomException1.java
1. // class representing custom exception
2. class InvalidAgeException extends Exception
3. {
4. public InvalidAgeException (String str)
5. {
6. // calling the constructor of parent Exception
7. super(str);
8. }
9. }
10. // class that uses custom exception InvalidAgeException
11. public class TestCustomException1
12. {
13. // method to check the age
14. static void validate (int age) throws InvalidAgeException{
15. if(age < 18){
16. // throw an object of user defined exception
17. throw new InvalidAgeException("age is not valid to vote");
18. }
19. else {
20. System.out.println("welcome to vote");
21. }
22. }
23. // main method
24. public static void main(String args[])
25. {
26. try
27. {
28. // calling the method
29. validate(13);
30. }
31. catch (InvalidAgeException ex)
32. {
33. System.out.println("Caught the exception");
34. // printing the message from InvalidAgeException object
35. System.out.println("Exception occured: " + ex);
36. }
37. System.out.println("rest of the code...");
38. }
39. }
Output:

Java 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 can not 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] = '-';
System.out.println(name);

The String class defined in the package java.lang 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

String siteName = "btechsmartclass.com";


siteName = "www.btechsmartclass.com";

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


String siteName = new String("www.btechsmartclass.com"); // Using constructor

The String class constructor accepts both string and character array as an argument.

String handling methods


In java programming language, the String class contains various methods that can be used to
handle string data values. It contains 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

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 boolean


case

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


string

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


string

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 int


string

lastIndexOf(String) Finds the last index of argument string in object int


Return
Method Description Value

string

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[]

intern() returns string from the pool String

join(String, String, ...) Joins all strings, first string as delimiter. String

Let's look at the following example java code.


Java Program

public class JavaStringExample {

public static void main(String[] args) {


String title = "Java Tutorials";
String siteName = "www.btechsmartclass.com";

System.out.println("Length of title: " + title.length());


System.out.println("Char at index 3: " + title.charAt(3));
System.out.println("Index of 'T': " + title.indexOf('T'));
System.out.println("Last index of 'a': " + title.lastIndexOf('a'));
System.out.println("Empty: " + title.isEmpty());
System.out.println("Ends with '.com': " + siteName.endsWith(".com"));
System.out.println("Equals: " + siteName.equals(title));
System.out.println("Sub-string: " + siteName.substring(9, 14));
System.out.println("Upper case: " + siteName.toUpperCase());
}
}

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

Exploring java.util.
The java.util package in Java is a built-in package that contains various utility classes and
interfaces. It provides basic functionality for commonly occurring use cases. It contains
Java's collections framework, date and time utilities, string-tokenizer, event-model utilities,
etc.
Introduction to java.util Package in Java
To support the needs of a software developer, Java provides various built-in and pre-written
functionalities in the form of packages. These built-in packages contain various kinds of
classes and interfaces that can be used to develop better and maintainable code. Some of the
built-in Java packages are shown in the figure given below:
import java.util.*;
The above statement is used to load all the functionalities provided by the java.util package.

What is the Use of java.util Package in Java?


The java.util package in Java consists of several components that provide basic necessities to
the programmer. These components include:
Let's explore these components and their usage in Java:
• Data Structure Classes: The java.util package contains several pre-written data
structures like Dictionary, Stack, LinkedList, etc. that can be used directly in the
program using the import statements.
• Date and Time Facility: The java.util package provides several date and time-
related classes that can be used to create and manipulate date and time values in a
program.
• Enumeration: It provides a special interface known as enumeration(enum for short)
that can be used to iterate through a set of values.
• Exceptions: It provides classes to handle commonly occurring exceptions in a Java
program.
• Miscellaneous Utility Classes: The java.util package contains essential utilities such
as the string tokenizer and random-number generator.

java.util Package Interfaces


Interface Description
Collections Root interface for the Collections API
Comparator Provides sorting logic
Deque Implements Deque data structure
Enumeration Produces enumeration objects
Iterator Provides iteration logic
List Implements an ordered collection (Sequence)
Map Implements Map data structure (key-value pairs)
Queue Implements Queue data structure
Set Produces a collection that contains no duplicate elements
SortedSet Produces a set that remembers the total ordering

java.util Package Classes


Class Description
Collections Provides methods to represent and manage collections
Class Description
Formatter An interpreter for format strings
Scanner Text scanner used to take user inputs
Arrays Provides methods for array manipulation
LinkedList Implements Doubly-linked list data structure
HashMap Implements Map data structure using Hash tables
TreeMap Implements Red-Black tree data structure
Stack Implements last-in-first-out (LIFO) data structure
PriorityQueue Implements unbounded priority queue data structure
Date Represents a specific instance of time
Calendar Provides methods to manipulate calendar fields
Random Used to generate a stream of pseudorandom numbers.
StringTokenizer Used to break a string into tokens
Timer, TimerTask Used by threads to schedule tasks
UUID Represents an immutable universally unique identifier

Differences between multithreading and multitasking

Multithreading in JAVA:

The java programming language allows us to create a program that contains one or more
parts that can run simultaneously at the same time. This type of program is known as a
multithreading program. Each part of this program is called a thread. Every thread defines a
separate path of execution in java. A thread is explained in different ways, and a few of them
are as specified below.
A thread is a light wieght process.
A thread may also be defined as follows.
A thread is a subpart of a process that can run individually.
In java, multiple threads can run at a time, which enables the java to write multitasking
programs. The multithreading is a specialized form of multitasking. All modern operating
systems support multitasking. There are two types of multitasking, and they are as follows.
• Process-based multitasking
• Thread-based multitasking
It is important to know the difference between process-based and thread-based multitasking.
Let's distinguish both.
Process-based multitasking Thread-based multitasking

It allows the computer to run two or more It allows the computer to run two or more
programs concurrently threads concurrently

In this process is the smallest unit. In this thread is the smallest unit.

Process is a larger unit. Thread is a part of process.

Process is heavy weight. Thread is light weight.

Process requires seperate address space for Threads share same address space.
each.

Process never gain access over idle time of Thread gain access over idle time of CPU.
CPU.

Inter process communication is expensive. Inter thread communication is not


expensive.

JAVA THREAD MODEL:


The java programming language allows us to create a program that contains one or more
parts that can run simultaneously at the same time. This type of program is known as a
multithreading program. Each part of this program is called a thread. Every thread defines a
separate path of execution in java. A thread is explained in different ways, and a few of them
are as specified below.
A thread is a light wieght process.
A thread may also be defined as follows.
A thread is a subpart of a process that can run individually.
In java, a thread goes through different states throughout its execution. These stages are
called thread life cycle states or phases. A thread may in any of the states like new, ready or
runnable, running, blocked or wait, and dead or terminated state. The life cycle of a thread in
java is shown in the following figure.
Let's look at each phase indetailed.
New
When a thread object is created using new, then the thread is said to be in the New state. This
state is also known as Born state.
Example

Thread t1 = new Thread();

Runnable / Ready
When a thread calls start( ) method, then the thread is said to be in the Runnable state. This
state is also known as a Ready state.
Example

t1.start( );

Running
When a thread calls run( ) method, then the thread is said to be Running. The run( ) method
of a thread called automatically by the start( ) method.
Blocked / Waiting
A thread in the Running state may move into the blocked state due to various reasons like
sleep( ) method called, wait( ) method called, suspend( ) method called, and join( ) method
called, etc.
When a thread is in the blocked or waiting state, it may move to Runnable state due to
reasons like sleep time completed, waiting time completed, notify( ) or notifyAll( ) method
called, resume( ) method called, etc.
Example

Thread.sleep(1000);
wait(1000);
wait();
suspened();
notify();
notifyAll();
resume();

Dead / Terminated
A thread in the Running state may move into the dead state due to either its execution
completed or the stop( ) method called. The dead state is also known as the terminated state.

Creation of threads:
The java programming language provides two methods to create threads, and they are listed
below.
• Using Thread class (by extending Thread class)
• Using Runnable interface (by implementing Runnable interface)

Extending Thread class


The java contains a built-in class Thread inside the java.lang package. The Thread class
contains all the methods that are related to the threads.
To create a thread using Thread class, follow the step given below.
• Step-1: Create a class as a child of Thread class. That means, create a class that
extends Thread class.
• Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
• Step-3: Create the object of the newly created class in the main( ) method.
• Step-4: Call the start( ) method on the object created in the above step.
Look at the following example program.
Example

class SampleThread extends Thread{

public void run() {


System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++) {
System.out.println("i = " + i);
}
}
}

public class My_Thread_Test {

public static void main(String[] args) {


SampleThread t1 = new SampleThread();
System.out.println("Thread about to start...");
t1.start();
}
}

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

Implementng Runnable interface


The java contains a built-in interface Runnable inside the java.lang package. The Runnable
interface implemented by the Thread class that contains all the methods that are related to the
threads.
To create a thread using Runnable interface, follow the step given below.
• Step-1: Create a class that implements Runnable interface.
• Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
• Step-3: Create the object of the newly created class in the main( ) method.
• Step-4: Create the Thread class object by passing above created object as parameter
to the Thread class constructor.
• Step-5: Call the start( ) method on the Thread class object created in the above step.
Look at the following example program.
Example

class SampleThread implements Runnable{

public void run() {


System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++) {
System.out.println("i = " + i);
}
}
}

public class My_Thread_Test {

public static void main(String[] args) {


SampleThread threadObject = new SampleThread();
Thread thread = new Thread(threadObject);
System.out.println("Thread about to start...");
thread.start();
}
}

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

JAVA THREAD PRIORITY


In a java programming language, every thread has a property called priority. Most of the
scheduling algorithms use the thread priority to schedule the execution sequence. In java, the
thread priority range from 1 to 10. Priority 1 is considered as the lowest priority, and priority
10 is considered as the highest priority. The thread with more priority allocates the processor
first.
The java programming language Thread class provides two methods setPriority(int),
and getPriority( ) to handle thread priorities.

The Thread class also contains three constants that are used to set the thread priority, and they
are listed below.
• MAX_PRIORITY - It has the value 10 and indicates highest priority.
• NORM_PRIORITY - It has the value 5 and indicates normal priority.
• MIN_PRIORITY - It has the value 1 and indicates lowest priority.
The default priority of any thread is 5 (i.e. NORM_PRIORITY).
setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread. It takes an
integer range from 1 to 10 as an argument and returns nothing (void).
The regular use of the setPriority( ) method is as follows.
Example

threadObject.setPriority(4);
or
threadObject.setPriority(MAX_PRIORITY);

getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread. It does not
takes anyargument and returns name of the thread as String.
The regular use of the getPriority( ) method is as follows.
Example

String threadName = threadObject.getPriority();

Look at the following example program.


Example

class SampleThread extends Thread{


public void run() {
System.out.println("Inside SampleThread");
System.out.println("Current Thread: " +
Thread.currentThread().getName());
}
}

public class My_Thread_Test {

public static void main(String[] args) {


SampleThread threadObject1 = new SampleThread();
SampleThread threadObject2 = new SampleThread();
threadObject1.setName("first");
threadObject2.setName("second");

threadObject1.setPriority(4);
threadObject2.setPriority(Thread.MAX_PRIORITY);

threadObject1.start();
threadObject2.start();
}
}

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

JAVA THREAD SYNCRONIZATION:


The java programming language supports multithreading. The problem of shared resources
occurs when two or more threads get execute at the same time. In such a situation, we need
some way to ensure that the shared resource will be accessed by only one thread at a time,
and this is performed by using the concept called synchronization.
The synchronization is the process of allowing only one thread to access a shared
resource at a time.
In java, the synchronization is achieved using the following concepts.
• Mutual Exclusion
• Inter thread communication
In this tutorial, we discuss mutual exclusion only, and the interthread communication will be
discussed in the next tutorial.
Mutual Exclusion
Using the mutual exclusion process, we keep threads from interfering with one another while
they accessing the shared resource. In java, mutual exclusion is achieved using the following
concepts.
• Synchronized method
• Synchronized block
Synchronized method
When a method created using a synchronized keyword, it allows only one object to access it
at a time. When an object calls a synchronized method, it put a lock on that method so that
other objects or thread that are trying to call the same method must wait, until the lock is
released. Once the lock is released on the shared resource, one of the threads among the
waiting threads will be allocated to the shared resource.

In the above image, initially the thread-1 is accessing the synchronized method and other
threads (thread-2, thread-3, and thread-4) are waiting for the resource (synchronized method).
When thread-1 completes it task, then one of the threads that are waiting is allocated with the
synchronized method, in the above it is thread-3.
Example

class Table{
synchronized void printTable(int n) {
for(int i = 1; i <= 10; i++)
System.out.println(n + " * " + i + " = " + i*n);
}
}

class MyThread_1 extends Thread{


Table table = new Table();
int number;
MyThread_1(Table table, int number){
this.table = table;
this.number = number;
}
public void run() {
table.printTable(number);
}
}

class MyThread_2 extends Thread{

Table table = new Table();


int number;
MyThread_2(Table table, int number){
this.table = table;
this.number = number;
}
public void run() {
table.printTable(number);
}
}
public class ThreadSynchronizationExample {

public static void main(String[] args) {


Table table = new Table();
MyThread_1 thread_1 = new MyThread_1(table, 5);
MyThread_2 thread_2 = new MyThread_2(table, 10);
thread_1.start();
thread_2.start();
}
}

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

Synchronized block
The synchronized block is used when we want to synchronize only a specific sequence of
lines in a method.
The folllowing syntax is used to define a synchronized block.
Syntax

synchronized(object){
...
block code
...
}
Look at the following example code to illustrate synchronized block.
Example
class Table{
void printTable(int n)
{
synchronized(this) //synchronized block
{
for(int i = 1; i <= 5; i++)
System.out.println(n + " * " + i + " = " + i*n);

}
}
}
class MyThread_2 extends Thread
{
Table table = new Table();
int number;
MyThread_2(Table table, int number)
{
this.table = table;
this.number = number;
}
public void run() {
table.printTable(number);
}
}
public class ThreadSynchronizationExample1
{

public static void main(String[] args)


{
Table table = new Table();

MyThread_2 thread_2 = new MyThread_2(table, 10);


thread_2.start();

}
}

Output:
C:\Users\Tariq\OneDrive\Desktop\java>java ThreadSynchronizationExample1
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
INTER THREAD COMMUNICATION:
Inter thread communication is the concept where two or more threads communicate to solve
the problem of polling. In java, polling is the situation to check some condition repeatedly, to
take appropriate action, once the condition is true. That means, in inter-thread
communication, a thread waits until a condition becomes true such that other threads can
execute its task. The inter-thread communication allows the synchronized threads to
communicate with each other.
Java provides the following methods to achieve inter thread communication.
• wait( )
• notify( )
• notifyAll( )
The following table gives detailed description about the above methods.
Method Description

void wait( It makes the current thread to pause its execution until other thread in the same
) monitor calls notify( )

void It wakes up the thread that called wait( ) on the same object.
notify( )

void It wakes up all the threads that called wait( ) on the same object.
notifyAll()
Calling notify( ) or notifyAll( ) does not actually give up a lock on a resource.
Let's look at an example problem of producer and consumer. The producer produces the item
and the consumer consumes the same. But here, the consumer can not consume until the
producer produces the item, and producer can not produce until the consumer consumes the
item that already been produced. So here, the consumer has to wait until the producer
produces the item, and the producer also needs to wait until the consumer consumes the
same. Here we use the inter-thread communication to implement the producer and consumer
problem.
The sample implementation of producer and consumer problem is as follows.
Example

Program:
class Producer implements Runnable{
InterThread obj;
Producer(InterThread obj){
this.obj=obj;
new Thread(this,"Producer").start();
}
public void run(){
for(int i=0;i<10;i++){
obj.put(i);
}
}
}
class Consumer implements Runnable{
InterThread obj;
Consumer(InterThread obj){
this.obj=obj;
new Thread(this, "Consumer").start();
}
public void run(){
for(int i=0;i<10;i++){
obj.get();
}
}
}
class InterThread{
int n;
boolean flag=false;
synchronized int get(){
if(!flag)
try{
wait();
}
catch(InterruptedException ie){
System.out.println("Interrupted Exception");
}
System.out.println("Consumer Consuming:"+n);
flag=false;
notify();
return n;
}
synchronized void put(int n){
if(flag)
try{
wait();
}
catch(InterruptedException ie){
System.out.println("InterruptedException");
}
this.n=n;
flag=true;
System.out.println("Producer producing"+n);
notify();
}
public static void main(String ar[]){
InterThread t=new InterThread();
new Producer(t);
new Consumer(t);
}
}
ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such a way,
we can suspend, resume or interrupt a group of threads by a single method call.
Java thread group is implemented by java.lang.ThreadGroup class.
A ThreadGroup represents a set of threads. A thread group can also include the other thread
group. The thread group creates a tree in which every thread group except the initial thread
group has a parent.
A thread is allowed to access information about its own thread group, but it cannot access the
information about its thread group's parent thread group or any other thread groups.
Constructors of ThreadGroup class
There are only two constructors of ThreadGroup class.
No. Constructor Description

1) ThreadGroup(String name) creates a thread group with given name.

2) ThreadGroup(ThreadGroup parent, creates a thread group with a given parent


String name) group and name

let's see a code to group multiple threads.


1. ThreadGroup tg1 = new ThreadGroup("Group A");
2. Thread t1 = new Thread(tg1,new MyRunnable(),"one");
3. Thread t2 = new Thread(tg1,new MyRunnable(),"two");
4. Thread t3 = new Thread(tg1,new MyRunnable(),"three");
Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is
the class that implements Runnable interface and "one", "two" and "three" are the thread
names.
Now we can interrupt all threads by a single line of code only.
1. Thread.currentThread().getThreadGroup().interrupt();
ThreadGroup Example
File: ThreadGroupDemo.java
1. public class ThreadGroupDemo implements Runnable{
2. public void run() {
3. System.out.println(Thread.currentThread().getName());
4. }
5. public static void main(String[] args) {
6. ThreadGroupDemo runnable = new ThreadGroupDemo();
7. ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
8.
9. Thread t1 = new Thread(tg1, runnable,"one");
10. t1.start();
11. Thread t2 = new Thread(tg1, runnable,"two");
12. t2.start();
13. Thread t3 = new Thread(tg1, runnable,"three");
14. t3.start();
15.
16. System.out.println("Thread Group Name: "+tg1.getName());
17. tg1.list();
18.
19. }
20. }
Output:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup]

Deamon thread:

Daemon thread in Java is a low-priority thread that performs background operations such as
garbage collection, finalizer, Action Listeners, Signal dispatches, etc.

Daemon thread in Java is also a service provider thread that helps the user thread. Its life is at
the mercy of user threads; when all user threads expire, JVM immediately terminates this
thread.

In simple words, we can say that it provides services to user threads for background-
supporting tasks. Daemon thread in Java has no role in life other than to serve user threads.

Properties of Daemon Thread in Java


• It's a thread with the lowest priority possible.
• They won't be able to stop the JVM from quitting once all of the user threads have
completed their tasks.
• When all user threads have completed their execution, the JVM terminates.
• If JVM finds a running daemon thread, it terminates the thread and, after that,
shutdown it.
• The JVM is unconcerned about whether the Daemon thread is active or not.
• The nature of a demon is passed down from parent to child. That is, if the parent is a
Daemon, the child will be a Daemon as well, and if the parent is a non-daemon, the
child will be a non-daemon as well.
Methods for Daemon Thread in Java by Thread Class
S.No. Method Description
public
This method marks whether the current thread as a daemon
1. void setDaemon(boolean
thread or a user thread.
status)
This method is used to determine whether or not the current
public final
2. thread is a daemon. If the thread is Daemon, it returns true.
boolean isDaemon()
Otherwise, false is returned.

Example Program:
public class TestDaemonThread1 extends Thread{
public void run(){
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();

t1.setDaemon(true);//now t1 is daemon thread

t1.start();//starting threads
t2.start();
t3.start();
}
}

Output:

daemon thread work


user thread work
user thread work
Enumeration:

The Enum in Java is a data type which contains a fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and
WEST), season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED,
YELLOW, BLUE, GREEN, WHITE, and BLACK) etc. According to the Java naming
conventions, we should have all constants in capital letters. So, we have enum constants in
capital letters.

Java Enums can be thought of as classes which have a fixed set of constants (a variable that
does not change). The Java enum constants are static and final implicitly. It is available since
JDK 1.5.

Enums are used to create our own data type like classes. The enum data type (also known as
Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java is
more powerful. Here, we can define an enum either inside the class or outside the class.

Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it can
implement many interfaces. We can have fields, constructors, methods, and main methods in
Java enum.

Points to remember for Java Enum

• Enum improves type safety


• Enum can be easily used in switch
• Enum can be traversed
• Enum can have fields, constructors and methods
• Enum may implement many interfaces but cannot extend any class because it
internally extends Enum class

Program:
class EnumExample1{
//defining the enum inside the class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//main method
public static void main(String[] args) {
//traversing the enum
for (Season s : Season.values())
System.out.println(s);
}}

Output:
WINTER
SPRING
SUMMER
FALL

Program:
enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY;
}

public class EnumerationExample {


public static void main(String[] args) {

WeekDay day = WeekDay.SUNDAY;

System.out.println("Today is " + day);

System.out.println("\nAll WeekDays: ");


for(WeekDay d:WeekDay.values())
System.out.println(d);

Output:
Today is SUNDAY

All WeekDays:
MONDAY
TUESDAY
WEDNESSDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

AUTOBOXING

In java, all the primitive data types have defined using the class concept, these classes known
as wrapper classes. In java, every primitive type has its corresponding wrapper class.
All the wrapper classes in Java were defined in the java.lang package.
The following table shows the primitive type and its corresponding wrapper class.
S.No. Primitive Type Wrapper class

1 byte Byte

2 short Short

3 int Interger

4 long Long

5 float Float

6 double Double

7 char Character

8 boolean Boolean
The Java 1.5 version introduced a concept that converts primitive type to corresponding
wrapper type and reverses of it.

Autoboxing in Java
In java, the process of converting a primitive type value into its corresponding wrapper class
object is called autoboxing or simply boxing. For example, converting an int value to an
Integer class object.
The compiler automatically performs the autoboxing when a primitive type value has
assigned to an object of the corresponding wrapper class.

We can also perform autoboxing manually using the method valueOf( ), which is provided by
every wrapper class.
For example :
int num = 100;
Integer i = num;
Integer j = Integer.valueOf(num);

Example Program:

class BoxingExample1{
public static void main(String args[]){
int a=50;
Integer a2=new Integer(a);//Boxing

Integer a3=5;//Boxing

System.out.println(a2+" "+a3);
}
}

Output:50 5

Auto un-boxing in Java


In java, the process of converting an object of a wrapper class type to a primitive type value
is called auto un-boxing or simply unboxing. For example, converting an Integer object to an
int value.

The compiler automatically performs the auto un-boxing when a wrapper class object has
assigned to a primitive type.

We can also perform auto un-boxing manually using the method intValue( ), which is
provided by Integer wrapper class. Similarly every wrapper class has a method for auto un-
boxing.
For example:
Integer num = 200;
int i = num;
int j = num.intValue();

Example program:
class UnboxingExample1{
public static void main(String args[]){
Integer i=new Integer(50);
int a=i;

System.out.println(a);
}
}

Output:
50

Generics in java
The java generics is a language feature that allows creating methods and class which can
handle any type of data values. The generic programming is a way to write generalized
programs, java supports it by java generics.

The java generics is similar to the templates in the C++ programming language.

• Most of the collection framework classes are generic classes.

• The java generics allows only non-primitive type, it does not support primitive types
like int, float, char, etc.

The java generics feature was introduced in Java 1.5 version. In java, generics used angular
brackets “< >”.
In java, the generics feature implemented using the following.

• Generic Method
• Generic Class

Generic methods in Java


The java generics allows creating generic methods which can work with a different type of
data values.

Using a generic method, we can create a single method that can be called with arguments of
different types. Based on the types of the arguments passed to the generic method, the
compiler handles each method call appropriately.

Example program:
public class GenericFunctions {

public <T, U> void displayData(T value1, U value2) {

System.out.println("(" + value1.getClass().getName() + ", " +


value2.getClass().getName() + ")");
}

public static void main(String[] args) {


GenericFunctions obj = new GenericFunctions();

obj.displayData(45.6f, 10);
obj.displayData(10, 10);
obj.displayData("Hi", 'c');
}

Output:
(java.lang.Float, java.lang.Integer)
(java.lang.Integer, java.lang.Integer)
(java.lang.String, java.lang.Character)

Generic Class:
A Generic class simply means that the items or functions in that class can be generalized
with the parameter(example T) to specify that we can add any type as a parameter in place
of T like Integer, Character, String, Double or any other user-defined type.
Example: Single type parameter
class Solution<T>
{
T data;
public static T getData(){
return data;
}
}

public class Area<T> {

// T is the Datatype like String,


// Integer of which Parameter type,
// the class Area is of
private T t;

public void add(T t)


{
// this.t specify the t variable inside
// the Area Class whereas the right hand
// side t simply specify the value as the
// parameter of the function add()
this.t = t;
}

public T get() { return t; }

public void getArea() {}


public static void main(String[] args)
{
// Object of generic class Area with parameter Type
// as Integer
Area<Integer> rectangle = new Area<Integer>();
// Object of generic class Area with parameter Type
// as Double
Area<Double> circle = new Area<Double>();
rectangle.add(10);
circle.add(2.5);
System.out.println(rectangle.get());
System.out.println(circle.get());
}
}

Output
10
2.5

ANNOTATIONS IN JAVA

Java Annotation is a kind of a tag that represents the metadata or information attached with
class, interface, methods, or fields to show some additional information that Java compiler
and JVM can use.

Though Annotations are not a part of the Java code they allow us to add metadata information
into our source code. Java introduced Annotations from JDK 5.

There is no direct effect of Annotations on the operation of the code they annotate; they do
not affect the execution of the program. Annotations provide supplemental information about
a program.

Some points about Annotations are:

They start with ‘@’.


They do not change the action or execution of a compiled program.
Annotations help to associate metadata or information to the elements of the program like
classes, instance variables, interfaces, constructors, methods, etc.
We cannot consider Annotations as pure comments as they can change the way a compiler
treats a program.

Annotations start with @. Its syntax is:

@AnnotationName
Let's take an example of @Override annotation.
The @Override annotation specifies that the method that has been marked with this
annotation overrides the method of the superclass with the same method name, return type,
and parameter list.

It is not mandatory to use @Override when overriding a method. However, if we use it, the
compiler gives an error if something is wrong (such as wrong parameter type) while
overriding the method.

class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}

class Dog extends Animal {


@Override
public void displayInfo() {
System.out.println("I am a dog.");
}
}

class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}

Output

I am a dog.

These annotations can be categorized as:

1. Predefined annotations

• @Override- This annotation is used to indicate that a method is overriding a method


in a superclass.
• @Deprecated: This annotation is used to indicate that a method or class is deprecated
and should no longer be used.

• @SuppressWarnings: This annotation is used to suppress compiler warnings.


class Main {
@Deprecated
public static void deprecatedMethod() {
System.out.println("Deprecated method");
}

@SuppressWarnings("deprecated")
public static void main(String args[]) {
Main depObj = new Main();
depObj. deprecatedMethod();
}
}

Output

Deprecated method

• @SafeVarargs: The @SafeVarargs annotation asserts that the annotated method or


constructor does not perform unsafe operations on its varargs (variable number of
arguments). Varargs, or variable-length arguments, allow a method to accept a
variable number of arguments. This can be useful for methods that need to process a
list of items, but the number of items is not known in advance.
public static void printInts(int... numbers) {
for (int number : numbers) {
System.out.println(number);
}
}
printInts(1, 2, 3);
printInts(4, 5, 6, 7);
printInts(8, 9, 10);

• @FunctionalInterface: This annotation is used to specify that a type declaration is a


functional interface. A functional interface can have only one abstract method. If we
add another abstract method, we will get the compile error.

@FunctionalInterface
public interface MyFuncInterface{
public void firstMethod(); // this is an abstract method
}

2. Custom annotations: It is also possible to create our own custom annotations.


Syntax: Declaration
[Access Specifier] @interface<AnnotationName>
{
DataType <Method Name>() [default value];
}

Here is what you need to know about custom annotation:

• Annotations can be created by using @interface followed by the annotation name.


• The annotation can have elements that look like methods but they do not have an
implementation.
• The default value is optional. The parameters cannot have a null value.
• The return type of the method can be primitive, enum, string, class name or array of
these types.

3. Meta-annotations

• @Retention: This annotation is used to specify how long an annotation is retained.

RetentionPolicy Availability

RetentionPolicy.SOURCE refers to the source code, discarded during compilation. It will


not be available in the compiled class.

RetentionPolicy.CLASS refers to the .class file, available to java compiler but not to
JVM . It is included in the class file.

RetentionPolicy.RUNTIME refers to the runtime, available to java compiler and JVM .

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
int value1();
String value2();
}
• @Documented: This annotation is used to specify whether an annotation should be
documented.
@Documented
public @interface MyDocumentedAnnotation {
}
@MyDocumentedAnnotation("This is my documented annotation")
public class MyClass {
// ...
}
/**
* This is my documented annotation
*
*
*/
public class MyClass {
// ...
}

• @Target: This annotation is used to specify where an annotation can be used.


• The java.lang.annotation.ElementType 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

@Target(ElementType)
Example:
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}

• @Inherited: This annotation is used to specify whether an annotation should be


inherited by subclasses.

Its syntax is:

@Inherited
For example,

@Inherited
public @interface MyCustomAnnotation { ... }

@MyCustomAnnotation
public class ParentClass{ ... }

public class ChildClass extends ParentClass { ... }

• @Repeatable: An annotation that has been marked by @Repeatable can be applied


multiple times to the same declaration.
Example:
@interface Color
{
String name();
}
@Color(name=”red”);
@Color(name=”blue”);
@Color(name=”pink”);
Class Shirt
{
--------
}

Exploring java.util:
Java.util package classes

StringTokenizer class in java.util package

The java.util.StringTokenizer class allows you to break a String into tokens. It is simple
way to break a String. It is a legacy class of Java.It doesn't provide the facility to differentiate
numbers, quoted strings, identifiers etc. like StreamTokenizer class. We will discuss about the
StreamTokenizer class in I/O chapter.In the StringTokenizer class, the delimiters can be
provided at the time of creation or one by one to the tokens.
Methods of the StringTokenizer Class:

Methods Description

boolean hasMoreTokens() It checks if there is more tokens available.

String nextToken() It returns the next token from the StringTokenizer object.

String nextToken(String delim) It returns the next token based on the delimiter.

boolean hasMoreElements() It is the same as hasMoreTokens() method.

Object nextElement() It is the same as nextToken() but its return type is Object.

int countTokens() It returns the total number of tokens.

Example of StringTokenizer Class

Let's see an example of the StringTokenizer class that tokenizes a string "my name is khan"
on the basis of whitespace.

Simple.java

1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }

Output:

my
name
is
khan

Formatter class in java.util pacakage


Format specifiers begin with a percent character (%) and terminate with a “type character, ”
which indicates the type of data (int, float, etc.) that will be converted the basic manner in
which the data will be represented (decimal, hexadecimal, etc.) The general syntax of a
format specifier is
% [flags] [width] [.precision] [argsize] typechar
The format() method of Formatter class accepts a wide variety of format specifiers. When
an uppercase specifier is used, then letters are shown in uppercase. Otherwise, the upper-
and lowercase specifiers perform the same conversion.

Format Specifier Conversion Applied


%% Inserts a % sign
%x %X Integer hexadecimal
%t %T Time and Date
%s %S String
%n Inserts a newline character
%o Octal integer
%f Decimal floating-point
%e %E Scientific notation
%g Causes Formatter to use either %f or %e, whichever is shorter
%h %H Hash code of the argument
%d Decimal integer
%c Character
%b %B Boolean
%a %A Floating-point hexadecimal
• Space format specifier : When creating columns of numbers, it is sometimes
very useful to print a space before a positive number so that positive and
negative number get aligned. To do this, space format specifier can be used.
Syntax:
Formatter().format("% d", -111);
Formatter().format("% d", 111);
Output:
-111
111

Example:

// Java program to demonstrate


// the space format specifier

import java.util.*;

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

// create Formatter class object


Formatter formatter = new Formatter();

// Use Space format specifier


formatter.format("%d", -111);
System.out.println(formatter);

formatter = new Formatter();


formatter.format("% d", 111);
System.out.println(formatter);

formatter = new Formatter();


formatter.format("% d", -222);
System.out.println(formatter);

formatter = new Formatter();


formatter.format("% d", 222);
System.out.println(formatter);
}
}

Output:
-111
111
-222
222

Scanner class in java


Scanner class in Java is found in the java.util package. Java provides various ways to read
input from the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by
default. It provides many methods to read and parse various primitive values.
The Java Scanner class is widely used to parse text for strings and primitive types using a
regular expression. It is the simplest way to get input in Java. By the help of Scanner in Java,
we can get input from the user in primitive types such as int, long, double, byte, float, short,
etc.
How to get Java Scanner
To get the instance of Java Scanner which reads input from the user, we need to pass the
input stream (System.in) in the constructor of Scanner class.
For Example:
Scanner in = new Scanner(System.in);
To get the instance of Java Scanner which parses the strings, we need to pass the strings in
the constructor of Scanner class. For Example:
Scanner in = new Scanner("Hello Java");

Example
Let's see a simple example of Java Scanner where we are getting a single input from the user.
Here, we are asking for a string through in.nextLine() method.

import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Output:
Enter your name: sonoo jaiswal
Name is: sonoo jaiswal

Array class in java.util package

The Arrays class in java.util package is a part of the Java Collection Framework. This class
provides static methods to dynamically create and access Java arrays. It consists of only
static methods and the methods of Object class. The methods of this class can be used by
the class name itself.

The class hierarchy is as follows:


java.lang.Object
java.util.Arrays

Syntax: Class declaration


public class Arrays extends Object

Syntax: In order to use Arrays


Arrays.<function name>;

Example:

import java.util.*;

public class ArraysClassExample {

public static void main(String[] args) {

int[] arr1 = {10, 3, 50, 7, 30, 66, 28, 54, 42};

int[] arr2 = {67, 2, 54, 67, 13, 56, 98};

System.out.print("Array1 => ");


for(int i:arr1)
System.out.print(i + ", ");
System.out.print("\nArray2 => ");
for(int i:arr2)
System.out.print(i + ", ");
System.out.println("\n-------------------------------------------");

System.out.println("Array1 as List => " + Arrays.asList(arr1));

System.out.println("Position of 30 in Array1 => " + Arrays.binarySearch(arr1,


30));

System.out.println("equity of array1 and array2 => " + Arrays.equals(arr1,


arr2));

System.out.println("Hash code of Array1 => " + Arrays.hashCode(arr1));

Arrays.fill(arr1, 15);
System.out.print("fill Array1 with 15 => ");
for(int i:arr1)
System.out.print(i + ", ");

Arrays.sort(arr2);
System.out.print("\nArray2 in sorted order => ");
for(int i:arr2)
System.out.print(i + ", ");
}
}
Output:
Array1 => 10, 3, 50, 7, 30, 66, 28, 54, 42,
Array2 => 67, 2, 54, 67, 13, 56, 98,
-------------------------------------------
Array1 as List => [[I@15db9742]
Position of 30 in Array1 => 4
equity of array1 and array2 => false
Hash code of Array1 => 1497890365
fill Array1 with 15 => 15, 15, 15, 15, 15, 15, 15, 15, 15,
Array2 in sorted order => 2, 13, 54, 56, 67, 67, 98,

Random class in java.util package:

The Random is a built-in class in java used to generate a stream of pseudo-random numbers
in java programming. The Random class is available inside the java.util package.

• The Random class implements Serializable, Cloneable and Comparable interface.

• The Random class is a part of java.util package.

• The Random class provides several methods to generate random numbers of type
integer, double, long, float etc.

• The Random class is thread-safe.

• Random number generation algorithm works on the seed value. If not provided, seed
value is created from system nano time.

Example:
import java.util.Random;

public class RandomClassExample {

public static void main(String[] args) {

Random rand = new Random();

System.out.println("Integer random number - " + rand.nextInt());


System.out.println("Integer random number from 0 to 100 - " +
rand.nextInt(100));
System.out.println("Boolean random value - " + rand.nextBoolean());
System.out.println("Double random number - " + rand.nextDouble());
System.out.println("Float random number - " + rand.nextFloat());
System.out.println("Long random number - " + rand.nextLong());
System.out.println("Gaussian random number - " + rand.nextGaussian());
}

}
Output:
Integer random number - 1680955064
Integer random number from 0 to 100 - 24
Boolean random value - false
Double random number - 0.9865316375590315
Float random number - 0.8961278
Long random number - -800426607900600794
Gaussian random number - 2.048080307982639

Calender class in java.util package:

The Calendar is a built-in abstract class in java used to convert date between a specific instant
in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. The Calendar class
is available inside the java.util package.

• The Calendar class implements Serializable, Cloneable and Comparable interface.

• As the Calendar class is an abstract class, we can not create an object using it.

• We will use the static method Calendar.getInstance() to instantiate and implement a


sub-class.

Example:
import java.util.*;

public class CalendarClassExample {

public static void main(String[] args) {

Calendar cal = Calendar.getInstance();

System.out.println("Current date and time : \n=>" + cal);


System.out.println("Current Calendar type : " + cal.getCalendarType());
System.out.println("Current date and time : \n=>" + cal.getTime());
System.out.println("Current date time zone : \n=>" + cal.getTimeZone());
System.out.println("Calendar filed 1 (year): " + cal.get(1));
System.out.println("Calendar day in integer form: " + cal.getFirstDayOfWeek());
System.out.println("Calendar weeks in a year: " + cal.getWeeksInWeekYear());
System.out.println("Time in milliseconds: " + cal.getTimeInMillis());
System.out.println("Available Calendar types: " + cal.getAvailableCalendarTypes());
System.out.println("Calendar hash code: " + cal.hashCode());
System.out.println("Is calendar supports week date? " + cal.isWeekDateSupported());
System.out.println("Calendar string representation: " + cal.toString());
}
}
Output:

Current date and time :


=>java.util.GregorianCalendar[time=1702622119707,areFieldsSet=true,areAllFieldsSet=true,
lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSaving
s=0,useDaylight=false,transitions=7,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstW
eek=1,ERA=1,YEAR=2023,MONTH=11,WEEK_OF_YEAR=50,WEEK_OF_MONTH=3,D
AY_OF_MONTH=15,DAY_OF_YEAR=349,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_M
ONTH=3,AM_PM=1,HOUR=0,HOUR_OF_DAY=12,MINUTE=5,SECOND=19,MILLISE
COND=707,ZONE_OFFSET=19800000,DST_OFFSET=0]
Current Calendar type : gregory
Current date and time :
=>Fri Dec 15 12:05:19 IST 2023
Current date time zone :
=>sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight
=false,transitions=7,lastRule=null]
Calendar filed 1 (year): 2023
Calendar day in integer form: 1
Calendar weeks in a year: 52
Time in milliseconds: 1702622119707
Available Calendar types: [gregory, buddhist, japanese]
Calendar hash code: -1705357620
Is calendar supports week date? true
Calendar string representation:
java.util.GregorianCalendar[time=1702622119707,areFieldsSet=true,areAllFieldsSet=true,le
nient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=
0,useDaylight=false,transitions=7,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWee
k=1,ERA=1,YEAR=2023,MONTH=11,WEEK_OF_YEAR=50,WEEK_OF_MONTH=3,DA
Y_OF_MONTH=15,DAY_OF_YEAR=349,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MO
NTH=3,AM_PM=1,HOUR=0,HOUR_OF_DAY=12,MINUTE=5,SECOND=19,MILLISEC
OND=707,ZONE_OFFSET=19800000,DST_OFFSET=0]

Date class in java.util package:


The Date is a built-in class in java used to work with date and time in java. The Date class is
available inside the java.util package. The Date class represents the date and time with
millisecond precision.

The Date class implements Serializable, Cloneable and Comparable interface. Most of the
constructors and methods of Date class has been deprecated after Calendar class introduced.

Example:
import java.time.Instant;
import java.util.Date;

public class DateClassExample {

public static void main(String[] args) {

Date time = new Date();


System.out.println("Current date => " + time);

System.out.println("Date => " + time.getTime() + " milliseconds");

System.out.println("after() => " + time.after(time) + " milliseconds");

System.out.println("before() => " + time.before(time) + " milliseconds");

System.out.println("hashCode() => " + time.hashCode());

}
Output:
Current date => Fri Dec 15 12:11:49 IST 2023
Date => 1702622509847 milliseconds
after() => false milliseconds
before() => false milliseconds
hashCode() => 1815460507

PriorityQueue in java.util

If we want to represent a group of individual objects prior to processing according to some


Priorty ,Then we should go for PriorityQueue class
• The Priority can be either Default nature sorting order(integers like Accending order
and Strings lke Alphabetical Order) or customized sorting order defined by
Comparator Interface.
• Insertion Order is not allowed and it is based on some Priority.
• Duplicates objects are not allowed.
• If we are depending on Default natural sorting order compulsory the objects should be
Homogeneous and comparable otherwise we will get Runtime Exception i.e
ClassCastException.
• If we are defining customized sorting order by comparator the objects need not be
Homogeneous and comparable.
• Null is not allowed even as the first element also.
Constuctors:
// default 11 elements capacity and Default natural Sorting order (integers like Accending
order and Strings lke Alphabetical Order)
PriorityQueue pq=new PriorityQueue();
PriorityQueue pq=new PriorityQueue(int initialcapacity);
PriorityQueue pq=new PriorityQueue(int initialapacity,Comparator c);
PriorityQueue pq=new PriorityQueue(SortedSet s);
PriorityQueue pq=new PriorityQueue(Collection c);

Example:
import java.util.*;
class ProiorityQueueEx
{
public static void main(String args[])
{
PriorityQueue pq=new PriorityQueue();
//System.out.println(pq.peek()); //null
//System.out.println(pq.element()); //Runtime Exception
for(int i=0;i<=10;i++)
{
pq.offer(i);
}
System.out.println(pq);
System.out.println(pq.peek());
System.out.println(pq.element());
}
}

Output:
[0,1,2,3,4,5,6,7,8,9,10]
0
[1,2,3,4,5,6,7,8,9,10]

Hashset in java.util

The HashSet class is a part of java collection framework. It is available inside the java.util
package. The HashSet class extends AbstractSet class and implements Set interface.

The elements of HashSet are organized using a mechanism called hashing. The HashSet is
used to create hash table for storing set of elements.

• The HashSet class is used to create a collection that uses a hash table for storing set of
elements.

• The HashSet is a child class of AbstractSet

• The HashSet implements interfaces like Set, Cloneable, and Serializable.

• The HashSet does not allows to store duplicate data values, but null values are
allowed.

• The HashSet does not maintains the order of insertion.

• The HashSet initial capacity is 16 elements.

• The HashSet is best suitable for search operations.

HashSet class declaration


The HashSet class has the following declaration.

Example
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable,
Serializable
HashSet class constructors
The HashSet class has the following constructors.

• HashSet( ) - Creates an empty HashSet with the default initial capacity (16).
• HashSet(Collection c) - Creates a HashSet with given collection of elements.
• HashSet(int initialCapacity) - Creates an empty HashSet with the specified initial
capacity.
• HashSet(int initialCapacity, float loadFactor) - Creates an empty HashSet with the
specified initial capacity and loadFactor.

Operations on HashSet
The HashSet class allow us to perform several operations like adding, accesing, deleting,
updating, looping, etc. Let's look at each operation with examples.

Adding Items
The HashSet class has the following methods to add items.

• boolean add(E element) - Inserts given element to the HashSet.


• boolean addAll(Collection c) - Inserts given collection of elements to the HashSet.

Example:
import java.util.*;

public class HashSetExample {

public static void main(String[] args) {

HashSet set = new HashSet();


HashSet anotherSet = new HashSet();

set.add(10);
set.add(20);
set.add(30);
set.add(40);
set.add(50);

System.out.println("\nHashSet is\n" + set);

anotherSet.addAll(set);

System.out.println("\nanotherSet is\n" + anotherSet);

}
Output:
HashSet is
[50, 20, 40, 10, 30]
anotherSet is
[50, 20, 40, 10, 30]

You might also like