Java Unit-3
Java Unit-3
Java Unit-3
import java.io.*;
}
}
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
System.out.println(list[6]);
//ArrayIndexOutOfBoundsException
String msg=null;
System.out.println(msg.length()); //NullPointerException
String name="abc";
int i=Integer.parseInt(name); //NumberFormatException
}
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.
import java.util.Scanner;
}
}
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.
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;
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.");
}
}
}
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.");
}
}
}
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.
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;
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:
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.
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;
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.
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.
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
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.
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
The String class constructor accepts both string and character array as an argument.
Return
Method Description Value
string
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
join(String, String, ...) Joins all strings, first string as delimiter. String
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.
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 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.
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)
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
threadObject1.setPriority(4);
threadObject2.setPriority(Thread.MAX_PRIORITY);
threadObject1.start();
threadObject2.start();
}
}
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);
}
}
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
{
}
}
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
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.
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.start();//starting threads
t2.start();
t3.start();
}
}
Output:
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.
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;
}
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
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.
• 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
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 {
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;
}
}
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.
@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 Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Output
I am a dog.
1. Predefined annotations
@SuppressWarnings("deprecated")
public static void main(String args[]) {
Main depObj = new Main();
depObj. deprecatedMethod();
}
}
Output
Deprecated method
@FunctionalInterface
public interface MyFuncInterface{
public void firstMethod(); // this is an abstract method
}
3. Meta-annotations
RetentionPolicy Availability
RetentionPolicy.CLASS refers to the .class file, available to java compiler but not to
JVM . It is included in the class file.
@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 {
// ...
}
FIELD fields
METHOD methods
CONSTRUCTOR constructors
PARAMETER parameter
@Target(ElementType)
Example:
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}
@Inherited
For example,
@Inherited
public @interface MyCustomAnnotation { ... }
@MyCustomAnnotation
public class ParentClass{ ... }
Exploring java.util:
Java.util package classes
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
String nextToken() It returns the next token from the StringTokenizer object.
String nextToken(String delim) It returns the next token based on the delimiter.
Object nextElement() It is the same as nextToken() but its return type is Object.
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
Example:
import java.util.*;
class GFG {
public static void main(String args[])
{
Output:
-111
111
-222
222
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
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.
Example:
import java.util.*;
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,
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 provides several methods to generate random numbers of type
integer, double, long, float etc.
• 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;
}
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
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.
• As the Calendar class is an abstract class, we can not create an object using it.
Example:
import java.util.*;
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;
}
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
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 does not allows to store duplicate data values, but null values are
allowed.
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.
Example:
import java.util.*;
set.add(10);
set.add(20);
set.add(30);
set.add(40);
set.add(50);
anotherSet.addAll(set);
}
Output:
HashSet is
[50, 20, 40, 10, 30]
anotherSet is
[50, 20, 40, 10, 30]