Core Java
Core Java
History of Java
The history of Java is very interesting. Java was originally designed for interactive television,
but it was too advanced technology for the digital cable television industry at the time. The
history of Java starts with the Green Team. Java team members (also known as Green Team),
initiated this project to develop a language for digital devices such as set-top boxes,
televisions, etc. However, it was best suited for internet programming. Later, Java technology
was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic". Java was developed by James Gosling, who is known
as the father of Java, in 1995. James Gosling and his team members started the project in the
early '90s.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions,
etc. Following are given significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in electronic appliances like set-top
boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries
like the U.S.A., France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind
of espresso bean. Java name was chosen by James Gosling while having a cup of coffee nearby his
office.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been
many additional features added to the language. Now Java is being used in Windows
applications, Web applications, enterprise applications, mobile applications, cards, etc. Each
new version adds new features in Java.
Many java versions have been released till now. The current stable release of Java is Java SE
10.
Since Java SE 8 release, the Oracle corporation follows a pattern in which every even version
is release in March month and an odd version released in September month.
Features of Java
1. Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun Microsystem, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
2. Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
3. Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).
4. Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
5. Robust
6. Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32
and 64-bit architectures in Java.
7. Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
8. High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g.,
C, C++, etc.
9. Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.
10. Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
11. Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Difference between JDK, JRE, and JVM
We must understand the differences between JDK, JRE, and JVM before proceeding further
to Java. See the brief overview of JVM here.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in which
Java bytecode can be executed. It can also run those programs which are written in other
languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other.
However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM.
It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro
Systems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It
physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.
JVMs are available for many hardware and software platforms (i.e. JVM is platform
dependent).
What is JVM
It is:
What it does
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.
1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the
java program, it is loaded first by the classloader. There are three built-in classloaders in Java.
1. Bootstrap ClassLoader: This is the first classloader which is the super class of
Extension classloader. It loads the [Link] file which contains all class files of Java
Standard Edition like [Link] package classes, [Link] package classes, [Link]
package classes, [Link] package classes, [Link] package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent
classloader of System classloader. It loades the jar files located
inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension
classloader. It loads the classfiles from classpath. By default, classpath is set to
current directory. You can change the classpath using "-cp" or "-classpath" switch. It
is also known as Application classloader.
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.
3) Heap
4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in
method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.
PC (program counter) register contains the address of the Java virtual machine instruction
currently being executed.
It contains:
1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles
parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation. Here, the term "compiler" refers
to a translator from the instruction set of a Java virtual machine (JVM) to the
instruction set of a specific CPU.
Java Native Interface (JNI) is a framework which provides an interface to communicate with
another application written in another language like C, C++, Assembly etc. Java uses JNI
framework to send output to the Console or interact with OS libraries.
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes the author's
name, date of creation, version, program name, company name, and description of the
program. It improves the readability of the program. Whatever we write in the documentation
section, the Java compiler ignores the statements during the execution of the program. To
write the statements in the documentation section, we use comments. The comments may
be single-line, multi-line, and documentation comments.
o Single-line Comment: It starts with a pair of forwarding slash (//). For example:
/*It is an example of
multiline comment*/
o Documentation Comment: It starts with the delimiter (/**) and ends with */. For
example:
Package Declaration
The package declaration is optional. It is placed just after the documentation section. In this
section, we declare the package name in which the class is placed. Note that there can
be only one package statement in a Java program. It must be defined before any class and
interface declaration. It is necessary because a Java class can be placed in different packages
and directories based on the module they are used. For all these classes package belongs to a
single parent directory. We use the keyword package to declare the package name. For
example:
package javatpoint; //where javatpoint is the package name
package [Link]; //where com is the root directory and javatpoint is the subdirectory
Import Statements
The package contains the many predefined classes and interfaces. If we want to use any class
of a particular package, we need to import that class. The import statement represents the
class stored in the other package. We use the import keyword to import the class. It is written
before the class declaration and after the package statement. We use the import statement in
two ways, either import a specific class or import all classes of a particular package. In a Java
program, we can use multiple import statements. For example:
interface car
{
void start();
void stop();
}
Class Definition
In this section, we define the class. It is vital part of a Java program. Without the class, we
cannot create any Java program. A Java program may conation more than one class
definition. We use the class keyword to define the class. The class is a blueprint of a Java
program. It contains information about user-defined methods, variables, and constants. Every
Java program has at least one class that contains the main() method. For example:
In this section, we define the main() method. It is essential for all Java programs. Because
the execution of all Java programs starts from the main() method. In other words, it is an
entry point of the class. It must be inside the class. Inside the main method, we create objects
and call the methods. We use the following statement to define the main() method:
class Simple{
public static void main(String args[]){
[Link]("Hello Java");
}
}
Save the above file as [Link].
Output:
Hello Java
Let's see what is the meaning of class, public, static, void, main, String[],
[Link]().
To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read Strings:
Example
class Main {
[Link]("Enter username");
}
Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read
other types, look at the table below:
Method Description
Java keywords are also known as reserved words. Keywords are particular words that act as a
key to a code. These are predefined words by Java so they cannot be used as a variable or
object name or class name.
1. abstract: Java abstract keyword is used to declare an abstract class. An abstract class can
provide the implementation of the interface. It can have abstract and non-abstract methods.
2. boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold
True and False values only.
3. break: Java break keyword is used to break the loop or switch statement. It breaks the current
flow of the program at specified conditions.
4. byte: Java byte keyword is used to declare a variable that can hold 8-bit data values.
5. case: Java case keyword is used with the switch statements to mark blocks of text.
6. catch: Java catch keyword is used to catch the exceptions generated by try statements. It must
be used after the try block only.
7. char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode
characters
8. class: Java class keyword is used to declare a class.
9. continue: Java continue keyword is used to continue the loop. It continues the current flow of
the program and skips the remaining code at the specified condition.
10. default: Java default keyword is used to specify the default block of code in a switch
statement.
11. do: Java do keyword is used in the control statement to declare a loop. It can iterate a part of
the program several times.
12. double: Java double keyword is used to declare a variable that can hold 64-bit floating-point
number.
13. else: Java else keyword is used to indicate the alternative branches in an if statement.
14. enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are
always private or default.
15. extends: Java extends keyword is used to indicate that a class is derived from another class or
interface.
16. final: Java final keyword is used to indicate that a variable holds a constant value. It is used
with a variable. It is used to restrict the user from updating the value of the variable.
17. finally: Java finally keyword indicates a block of code in a try-catch structure. This block is
always executed whether an exception is handled or not.
18. float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point
number.
19. for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the number of
iteration is fixed, it is recommended to use for loop.
20. if: Java if keyword tests the condition. It executes the if block if the condition is true.
21. implements: Java implements keyword is used to implement an interface.
22. import: Java import keyword makes classes and interfaces available and accessible to the
current source code.
23. instanceof: Java instanceof keyword is used to test whether the object is an instance of the
specified class or implements an interface.
24. int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
25. interface: Java interface keyword is used to declare an interface. It can have only abstract
methods.
26. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
27. native: Java native keyword is used to specify that a method is implemented in native code
using JNI (Java Native Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to anything. It
removes the garbage value.
30. package: Java package keyword is used to declare a Java package that includes the classes.
31. private: Java private keyword is an access modifier. It is used to indicate that a method or
variable may be accessed only in the class in which it is declared.
32. protected: Java protected keyword is an access modifier. It can be accessible within the
package and outside the package but through inheritance only. It can't be applied with the
class.
33. public: Java public keyword is an access modifier. It is used to indicate that an item is
accessible anywhere. It has the widest scope among all other modifiers.
34. return: Java return keyword is used to return from a method when its execution is complete.
35. short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
36. static: Java static keyword is used to indicate that a variable or method is a class method. The
static keyword in Java is mainly used for memory management.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
38. super: Java super keyword is a reference variable that is used to refer to parent class objects.
It can be used to invoke the immediate parent class method.
39. switch: The Java switch keyword contains a switch statement that executes code based on test
value. The switch statement tests the equality of a variable against multiple values.
40. synchronized: Java synchronized keyword is used to specify the critical sections or methods
in multithreaded code.
41. this: Java this keyword can be used to refer the current object in a method or constructor.
42. throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword
is mainly used to throw custom exceptions. It is followed by an instance.
43. throws: The Java throws keyword is used to declare an exception. Checked exceptions can be
propagated with throws.
44. transient: Java transient keyword is used in serialization. If you define any data member as
transient, it will not be serialized.
45. try: Java try keyword is used to start a block of code that will be tested for exceptions. The
try block must be followed by either catch or finally block.
46. void: Java void keyword is used to specify that a method does not have a return value.
47. volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
48. while: Java while keyword is used to start a while loop. This loop iterates a part of the
program several times. If the number of iteration is not fixed, it is recommended to use the
while loop.
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
The Boolean data type is used to store only two possible values: true and false. This data type
is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
The byte data type is an example of primitive data type. It is an 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value
is -128 and maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used
in place of "int" data type.
Example:
The short data type is a 16-bit signed two's complement integer. Its value-range lies between
-32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767.
Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data
type is 2 times smaller than an integer.
Example:
The int data type is a 32-bit signed two's complement integer. Its value-range lies between
- 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is
- 2,147,483,648 and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is
no problem about memory.
Example:
The long data type is a 64-bit two's complement integer. Its value-range lies between
-9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is -9,223,372,036,854,775,808 and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.
Example:
The float data type is a single-precision 32-bit IEEE 754 floating [Link] value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.
Example:
float f1 = 234.5f
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The
double data type also should never be used for precise values, such as currency. Its default
value is 0.0d.
Example:
double d1 = 12.3
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example:
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of
the memory location. It is a combination of "vary + able" which means its value can be
changed.
int data=50;//Here data is variable
Types of Variables
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.
Scope of a Variable
In programming, a variable can be declared and defined inside a class, method, or block. It
defines the scope of the variable i.e. the visibility or accessibility of a variable. Variable
declared inside a block or method are not visible to outside. If we try to do so, we will get a
compilation error. Note that the scope of a variable can be nested.
o We can declare variables anywhere in the program but it has limited scope.
o A variable can be a parameter of a method or constructor.
o A variable can be defined and declared inside the body of a method and constructor.
o It can also be defined inside blocks and loops.
o Variable declared inside main() function cannot be accessed outside the main()
function
[Link]
private No No No
default Yes No No
These are the variables that are declared inside a method, constructor, or block have
a method-level or block-level scope and cannot be accessed outside in which it is defined.
Variables declared inside a pair of curly braces {} have block-level scope.
Declaring a Variable Inside a Method
Output:
The value of x is: 10
Type casting
Convert a value from one data type to another data type is known as type casting.
Types of Type Casting
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's
see an example.
[Link]
In the above example, we have taken a variable x and converted it into a long type.
After that, the long type is converted into the float type.
double -> float -> long -> int -> char -> short -> byte
In the following example, we have performed the narrowing type casting two times. First, we
have converted the double type into long data type after that long data type is converted into
int type.
[Link]
Output
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Output:
10
12
12
10
Java Unary Operator Example 2: ++ and –
Output:
-11
9
false
true
Output:
21
Output:
40
80
80
240
The Java right shift operator >> is used to move the value of the left operand to right by the
number of bits specified by the right operand.
Java Right Shift Operator Example
public OperatorExample{
public static void main(String args[]){
[Link](10>>2);//10/2^2=10/4=2
[Link](20>>2);//20/2^2=20/4=5
[Link](20>>3);//20/2^3=20/8=2
}}
Output:
2
5
2
The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
Output:
false
false
The logical || operator doesn't check the second condition if the first condition is true. It
checks the second condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
Output:
true
true
true
10
true
11
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot
in Java programming. It is the only conditional operator which takes three operands.
Output:
13
9
18
9
Output:
Output:
20
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and
when. Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided. There are two types of decision-
making statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a
Boolean value, either true or false. In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
if(condition) {
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java code.
[Link]
[Link]
Output:
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
[Link]
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In
other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter in the block of code where the condition is true. We can also
define an else statement at the end of the chain.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
[Link]
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if
or else-if statement.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
[Link]
if([Link]("India"))
{
if([Link]("Meerut")) {
[Link]("Your city is Meerut");
}
else if([Link]("Noida")) {
[Link]("Your city is Noida");
}else
{
[Link]([Link](",")[0]);
}
}
else {
[Link]("You are not living in India");
} } }
Output:
Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which
is being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
[Link]
Output:
While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value. The switch permits only int,
string, and Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check
the condition, and increment/decrement in a single line of code. We use the for loop only
when we exactly know the number of times, we want to execute the block of code.
[Link]
Output:
Java provides an enhanced for loop to traverse the data structures like array or collection. In
the for-each loop, we don't need to update the loop variable. The syntax to use the for-each
loop in java is given below.
Consider the following example to understand the functioning of the for-each loop in Java.
[Link]
Output:
Java
C
C++
Python
JavaScript
The while loop is also used to iterate over the number of statements multiple times. However,
if we don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.
while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.
Consider the following example.
Calculation .java
Output:
0
2
4
6
8
10
Java do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.
do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in Java.
[Link]
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.
As the name suggests, the break statement is used to break the current flow of the program
and transfer the control to the next statement outside a loop or switch statement. However, it
breaks only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
Consider the following example in which we have used the break statement with the for loop.
[Link]
Output:
0
1
2
3
4
5
6
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in
Java.
Output:
0
1
2
3
5
1
2
3
5
2
3
5
2. Introducing classes and objects
Introduction:
An entity that has state and behaviour is known as an object e.g., chair, bike, marker, pen, table,
car, etc. It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.
For Example, Pen is an object. Its name is Reynolds; colour is white, known as its state. It is
used to write, so writing is its behaviour.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance (result) of a class.
Object Definitions:
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
class <class_name>{
field;
method;
}
A variable which is created inside the class but outside the method is known as an instance
variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when
an object or instance is created. That is why it is known as an instance variable.
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of Method
o Code Reusability
o Code Optimization
The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.
Object and Class Example: main within the class
In this example, we have created a Student class which has two data members id and name.
We are creating the object of the Student class by new keyword and printing the object's value.
In real time development, we create classes and use it from another class. It is a better approach
than previous one. Let's see a simple example, where we are having main() method in another
class.
We can have multiple classes in different Java files or single Java file. If you define multiple
classes in a single Java source file, it is a good idea to save the file name with the class name
which has main() method.
1. By reference variable
2. By method
3. By constructor
Initializing an object means storing data into the object. Let's see a simple example where we
are going to initialize the object through a reference variable.
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
[Link]=101;
[Link]="Sonoo";
[Link]([Link]+" "+[Link]);//printing members with a white space
}
}
In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method. Here, we are displaying the state (data) of
the objects by invoking the displayInformation() method.
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){[Link](rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
[Link](111,"Karan");
[Link](222,"Aryan");
[Link]();
[Link]();
}
}
As you can see in the above figure, object gets the memory in heap memory area. The
reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 both
are reference variables that refer to the objects allocated in memory.
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.
class A{
private int data=40;
private void msg(){[Link]("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}
}
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
//save by [Link]
package pack;
class A{
void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
//save by [Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
o The static variable can be used to refer to the common property of all objects (which is
not unique for each object), for example, the company name of employees, college
name of students, etc.
o The static variable gets memory only once in the class area at the time of class loading.
Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and name,
so instance data member is good in such case. Here, "college" refers to the common property
of all objects
. If we make it static, this field will get the memory only once.
In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object
will have the copy of the instance variable. If it is incremented, it won't reflect other objects.
So each object will have the value 1 in the count variable.
Output:
1
1
1
As we have mentioned above, static variable will get the memory only once, if any object
changes the value of the static variable, it will retain its value.
Counter2(){
count++;//incrementing the value of static variable
[Link](count);
}
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
//Java Program to get the cube of a given number using the static method
class Calculate{
static int cube(int x){
return x*x*x;
}
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
Ans) It is because the object is not required to call a static method. If it were a non-static
method, JVM creates an object first then call main() method that will lead the
problem of extra memory allocation.
Method Overloading:
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behaviour of the method because its name differs.
So, we perform method overloading to figure out the program quickly.
Note: In Java, Method Overloading is not possible by changing the return type of the method
only.
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}}
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](12.3,12.6));
}}
Q) Why Method Overloading is not possible by changing the return type of method only?
In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
[Link]([Link](11,11));//ambiguity
}}
Constructors:
In Java , a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object is allocated in
the memory.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It
is not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.
The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and their
types.
There are many differences between constructors and methods. They are given below.
A constructor is used to initialize the state of A method is used to expose the behavior of
an object. an object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default The method is not provided by the compiler
constructor if you don't have any constructor in any case.
in a class.
The constructor name must be same as the The method name may or may not be same
class name. as the class name.
this keyword in Java
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.
The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display(){[Link](rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
[Link]();
[Link]();
}}
Note: It is better approach to use meaningful names for variables. So we use same name for
instance variables and parameters in real time, and always use this keyword.
You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see
the example
class A{
void m(){[Link]("hello m");}
void n(){
[Link]("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.
class A{
A(){[Link]("hello a");}
A(int x){
this();
[Link](x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
class A{
A(){
this(5);
[Link]("hello a");
}
A(int x){
[Link](x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}
4) this: to pass as an argument in the method
The this keyword can also be passed as an argument in the method. It is mainly used in the
event handling. Let's see the example:
class S2{
void m(S2 obj){
[Link]("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
In event handling (or) in a situation where we have to provide reference of a class to another
one. It is used to reuse one object in many methods.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
It is automatically done by the garbage collector (a part of JVM) so we don't need to
make extra efforts.
finalize() Method in Java:
The Java finalize() method of Object class is a method that the Garbage Collector always
calls just before the deletion/destroying the object which is eligible for Garbage Collection to
perform clean-up activity. Clean-up activity means closing the resources associated with that
object like Database Connection, Network Connection, or we can say resource de-allocation.
Remember, it is not a reserved keyword. Once the finalize() method completes immediately,
Garbage Collector destroys that object.
Finalization: Just before destroying any object, the garbage collector always calls finalize()
method to perform clean-up activities on that object. This process is known as Finalization in
Java.
Note: The Garbage collector calls the finalize() method only once on any object.
Syntax:
protected void finalize throws Throwable{}
Since the Object class contains the finalize method hence finalize method is available for
every java class since Object is the superclass of all java classes. Since it is available for
every java class, Garbage Collector can call the finalize() method on any java object.
finalize() method releases system resources before the garbage collector runs for a specific
object. JVM allows finalize() to be invoked only once per object.
The finalize method, which is present in the Object class, has an empty implementation. In
our class, clean-up activities are there. Then we have to override this method to define our
clean-up activities.
In order to Override this method, we have to define and call finalize within our code
explicitly.
Program:
import [Link].*;
// Defining a class demo since every java class is a subclass of predefined Object class
// Therefore demo is a subclass of Object class
public class demo
{
protected void finalize() throws Throwable
{
[Link]("inside demo's finalize()");
}
public static void main(String[] args) throws Throwable
{
demo d = new demo();
[Link]();
}}
Wrapper Classes
A Wrapper class is a class whose object wraps or contains primitive data types. When we
create an object to a wrapper class, it contains a field and in this field, we can store primitive
data types. In other words, we can wrap a primitive value into a wrapper class object.
Wrapper class in java provides the mechanism to convert primitive data type into object is
called boxing and object into primitive data type is called unboxing.
Since J2SE 5.0, auto boxing and unboxing feature converts primitive data type into object
and object into primitive data type automatically. The automatic conversion of primitive data
type into object is known as auto-boxing and vice-versa auto-unboxing.
One of the eight classes of [Link] package are known as wrapper class in java. The list of
eight wrapper classes is given below:
/*Java Program to convert all primitives into its corresponding wrapper objects
and vice- versa */
class WrapperTest
{
public static void main(String args[])
{
int i=30;
Integer intobj=i; //Autoboxing: Converting primitives into objects
[Link]("Integer object: "+intobj);
int intvalue=intobj; //Unboxing: Converting Objects to Primitives
[Link]("int value: "+intvalue);
}
}
Example 2:
/* Java Program to convert all primitives into its corresponding wrapper objects and
vice-versa */
class Wrapper
{
public static void main(String args[])
{
byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;
//Printing objects
[Link]("---Printing object values---");
[Link]("Byte object: "+byteobj);
[Link]("Short object: "+shortobj);
[Link]("Integer object: "+intobj);
[Link]("Long object: "+longobj);
[Link]("Float object: "+floatobj);
[Link]("Double object: "+doubleobj);
[Link]("Character object: "+charobj);
[Link]("Boolean object: "+boolobj);
//Printing primitives
[Link]("---Printing primitive values---");
[Link]("byte value: "+bytevalue);
[Link]("short value: "+shortvalue);
[Link]("int value: "+intvalue);
[Link]("long value: "+longvalue);
[Link]("float value: "+floatvalue);
[Link]("double value: "+doublevalue);
[Link]("char value: "+charvalue);
[Link]("boolean value: "+boolvalue);
}
}
//Converting primitive numbers to object number using construtor methods
import [Link].*;
public class Wrapper1
{
public static void main(String args[])
{
int a=10;
Integer IntVal=new Integer(a);
[Link](IntVal);
}
}
import [Link].*;
public class Wrapper2
{
public static void main(String args[])
{
Integer IntVal=new Integer(10);
int i=[Link]();
[Link](i);
}
}
import [Link].*;
public class Wrapper3
{
public static void main(String args[])
{
int i=10;
String str;
str=[Link](i);
[Link](str);
}
}
Table 9.8 Converting string objects to numeric objects using the Static method valueOf()
Note: These numeric objects may be converted to primitive numbers using the typeValue()
method as shown in Table 9.6.
Example:
//Converting string objects to numeric objects using the Static method valueOf()
import [Link].*;
public class Wrapper4
{
public static void main(String args[])
{
String str="10";
Integer IntVal=[Link](str);
[Link](IntVal);
}
}
import [Link].*;
public class Wrapper5
{
public static void main(String args[])
{
String str="10";
int i=[Link](str);
[Link](i);
}
}
Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory
location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need
to use the sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class,
and implements the Serializable as well as Cloneable interfaces. We can store primitive values
or objects in an array in Java. Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow
its size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.
Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the loop.
for(data_type variable:array){
//body of the loop
}
Let us see the example of print the elements of Java array using the for-each loop.
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](arr[i][j]+" ");
}
[Link]();
}
}}
Example 2:
Java is an object-oriented programming language. Most of the work done with the help
of objects. We know that an array is a collection of the same data type that dynamically creates
objects and can have elements of primitive types. Java allows us to store objects in an array.
In Java , the class is also a user-defined data type. An array that conations class type
elements are known as an array of objects. It stores the reference variable of the object.
Before creating an array of objects, we must create an instance of the class by using the new
keyword. We can use any of the following statements to create an array of objects.
Syntax:
Example:
import [Link].*;
class Student
{
int rollno;
String name;
float fee;
void getdata(int x,String y,float z)
{
rollno=x;
name=y;
fee=z;
}
void display()
{
[Link](rollno+" "+name+" "+fee);
}
}
class ArrayofObject
{
public static void main(String args[])
{
int a;
String b;
float c;
Student s[]=new Student[3];
for(int i=0;i<3;i++)
{
s[i]=new Student();
}
Scanner sc=new Scanner([Link]);
for(int i=0;i<3;i++)
{
[Link]("Enter the values of student "+(i+1));
a=[Link]();
b=[Link]();
c=[Link]();
s[i].getdata(a,b,c);
}
for(int i=0;i<3;i++)
{
[Link]("Information about student "+(i+1));
s[i].display();
}
}
}
Collection Framework
The Collection in Java is a framework that provides an architecture to store and manipulate the group
of objects.
Java Collections can achieve all the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces
(Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList , PriorityQueue, HashSet,
LinkedHashSet, TreeSet).
The Collection framework represents a unified architecture for storing and manipulating a group of
objects. It has:
Let us see the hierarchy of Collection framework. The [Link] package contains all
the classesand interfaces for the Collection framework.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
Method Description
public void clear() It removes the total number of elements from the
collection.
public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime
type of the returned array is that of the specified
array.
public int hashCode() It returns the hash code number of the collection.
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
There are only three methods in the Iterator interface. They are:
Method Description
public boolean It returns true if the iterator has more elements otherwise it
hasNext() returns false.
public Object next() It returns the element and moves the cursor pointer to the
next element.
public void remove() It removes the last elements returned by the iterator. It is less
used.
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the collection
framework. It declares the methods that every collection will have. In other words, we can say that the
Collection interface builds the foundation on which the collection framework depends
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll ( Collection
c), void clear(), etc. which are implemented by all the subclasses of Collection interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure in which
we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
There are various methods in List interface that can be used to insert, delete, and access the elements
from the list.
The classes that implement the List interface are given below.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate element
of different data types. The ArrayList class maintains the insertion order and is non-synchronized. The
elements stored in the ArrayList class can be randomly accessed. Consider the following example.
import [Link].*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
[Link]("Ravi"); //Adding object in arraylist
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing list through Iterator
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the
elements. It can store the duplicate elements. It maintains the insertion order and is not synchronized. In
LinkedList, the manipulation is fast because no shifting is required.
import [Link].*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is
synchronized and contains many methods that are not the part of Collection framework.
import [Link].*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
[Link]("Ayush");
[Link]("Amit");
[Link]("Ashish");
[Link]("Garima");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The
stack contains all of the methods of Vector class and also provides its methods like boolean push(),
boolean peek(), boolean push(object o), which defines its properties.
import [Link].*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
[Link]("Ayush");
[Link]("Garvit");
[Link]("Amit");
[Link]("Ashish");
[Link]("Garima");
[Link]();
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Though Java Iterator was introduced in Java 1.2, however, it is still not the oldest tool available to
traverse through the elements of the Collection object. The oldest Iterator in the Java programming
language is the Enumerator predated Iterator. Java Iterator interface succeeds the enumerator iterator
that was practiced in the beginning to traverse over some accessible collections like the ArrayLists.
The Java Iterator is also known as the universal cursor of Java as it is appropriate for all the classes of
the Collection framework. The Java Iterator also helps in the operations like READ and REMOVE.
When we compare the Java Iterator interface with the enumeration iterator interface, we can say that the
names of the methods available in Java Iterator are more precise and straightforward to use.
When a user needs to use the Java Iterator, then it's compulsory for them to make an instance of the
Iterator interface from the collection of objects they desire to traverse over. After that, the received
Iterator maintains the trail of the components in the underlying collection to make sure that the user will
traverse over each of the elements of the collection of objects.
If the user modifies the underlying collection while traversing over an Iterator leading to that collection,
then the Iterator will typically acknowledge it and will throw an exception in the next time when the
user will attempt to get the next component from the Iterator.
The following figure perfectly displays the class diagram of the Java Iterator interface. It contains a total
of four methods that are:
o hasNext()
o next()
o remove()
o forEachRemaining()
The forEachRemaining() method was added in the Java 8. Let's discuss each method in detail.
o boolean hasNext(): The method does not accept any parameter. It returns true if there are more
elements left in the iteration. If there are no more elements left, then it will return false.
If there are no more elements left in the iteration, then there is no need to call the next() method.
In simple words, we can say that the method is used to determine whether the next() method is
to be called or not.
o E next(): It is similar to hasNext() method. It also does not accept any parameter. It returns E,
i.e., the next element in the traversal. If the iteration or collection of objects has no more
elements left to iterate, then it throws the NoSuchElementException.
o default void remove(): This method also does not require any parameters. There is no return
type of this method. The main function of this method is to remove the last element returned by
the iterator traversing through the underlying collection. The remove () method can be requested
hardly once per the next () method call. If the iterator does not support the remove operation,
then it throws the UnSupportedOperationException. It also throws the IllegalStateException if
the next method is not yet called.
o default void forEachRemaining(Consumer action): It is the only method of Java Iterator that
takes a parameter. It accepts action as a parameter. Action is nothing but that is to be performed.
There is no return type of the method. This method performs the particularized operation on all
of the left components of the collection until all the components are consumed or the action
throws an exception. Exceptions thrown by action are delivered to the caller. If the action is null,
then it throws a NullPointerException.
Now it's time to execute a Java program to illustrate the advantage of the Java Iterator interface. The
below code produces an ArrayList of city names. Then we initialize an iterator applying the iterator ()
method of the ArrayList. After that, the list is traversed to represent each element.
import [Link].*;
import [Link].*;
[Link]("Delhi");
[Link]("Mumbai");
[Link]("Kolkata");
[Link]("Chandigarh");
[Link]("Noida");
while ([Link]())
[Link]([Link]() + " ");
[Link]();
}
}
Points to Remember
o The Java Iterator is an interface added in the Java Programming language in the Java 1.2
Collection framework. It belongs to [Link] package.
o It is one of the Java Cursors that are practiced to traverse the objects of the collection
framework.
o The Java Iterator is used to iterate the components of the collection object one by one.
o The Java Iterator is also known as the Universal cursor of Java as it is appropriate for all the
classes of the Collection framework.
o The Java Iterator also supports the operations like READ and REMOVE.
o The methods names of the Iterator class are very simple and easy to use compared to the method
names of Enumeration Iterator.
Java List
List in Java provides the facility to maintain the ordered collection. It contains the index-based methods
to insert, update, delete and search the elements. It can have the duplicate elements also. We can also
store the null elements in the list.
The List interface is found in the [Link] package and inherits the Collection interface. It is a factory of
ListIterator interface. Through the ListIterator, we can iterate the list in forward and backward
directions. The implementation classes of List interface are ArrayList, LinkedList, Stack and Vector.
The ArrayList and LinkedList are widely used in Java programming. The Vector class is deprecated
since Java 5.
Method Description
void add(int index, E element) It is used to insert the specified element at the
specified position in a list.
boolean addAll(Collection<? extends E> It is used to append all of the elements in the
c) specified collection to the end of a list.
boolean addAll(int index, Collection<? It is used to append all the elements in the
extends E> c) specified collection, starting at the specified
position of the list.
int hashcode() It is used to return the hash code value for a list.
boolean containsAll(Collection<?> c) It returns true if the list contains all the specified
element
void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list
operator) with the specified element.
void sort(Comparator<? super E> c) It is used to sort the elements of the list on the
basis of specified comparator.
List<E> subList(int fromIndex, int toIndex) It is used to fetch all the elements lies within the
given range.
The ArrayList and LinkedList classes provide the implementation of List interface. Let's see the
examples to create the List:
//Creating a List of type Book using ArrayList (Here Book is class type)
List<Book> list=new ArrayList<Book>();
//Creating a List of type String using LinkedList
List<String> list=new LinkedList<String>();
In short, you can create the List of any type. The ArrayList<T> and LinkedList<T> classes are used to
specify the type. Here, T denotes the type.
Let's see a simple example of List where we are using the ArrayList class as the implementation.
import [Link].*;
public class ListExample1{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
[Link]("Mango");
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Iterating the List element using for-each loop
for(String fruit:list)
[Link](fruit);
}
}
We can convert the Array to List by traversing the array and adding the element in list one by one using
[Link]() method. Let's see a simple example to convert array elements into List.
import [Link].*;
public class ArrayToListExample{
public static void main(String args[]){
//Creating Array
String[] array={"Java","Python","PHP","C++"};
[Link]("Printing Array: "+[Link](array));
//Converting Array to List
List<String> list=new ArrayList<String>();
for(String lang:array){
[Link](lang);
}
[Link]("Printing List: "+list);
}
}
We can convert the List to Array by calling the [Link]() method. Let's see a simple example to
convert list elements into array.
import [Link].*;
public class ListToArrayExample{
public static void main(String args[]){
List<String> fruitList = new ArrayList<>();
[Link]("Mango");
[Link]("Banana");
[Link]("Apple");
[Link]("Strawberry");
//Converting ArrayList to Array
String[] array = [Link](new String[[Link]()]);
[Link]("Printing Array: "+[Link](array));
[Link]("Printing List: "+fruitList);
}
}
The get() method returns the element at the given index, whereas the set() method changes or replaces
the element.
import [Link].*;
public class ListExample2{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
[Link]("Mango");
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//accessing the element
[Link]("Returning element: "+[Link](1));//it will return the 2nd element, because i
ndex starts from 0
//changing the element
[Link](1,"Dates");
//Iterating the List element using for-each loop
for(String fruit:list)
[Link](fruit);
}
}
There are various ways to sort the List, here we are going to use [Link]() method to sort the list
element. The [Link] package provides a utility class Collections which has the static method sort().
Using the [Link]() method, we can easily sort any List.
import [Link].*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
[Link]("Mango");
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Sorting the list
[Link](list1);
//Traversing list through the for-each loop
for(String fruit:list1)
[Link](fruit);
[Link]("Sorting numbers...");
//Creating a list of numbers
List<Integer> list2=new ArrayList<Integer>();
[Link](21);
[Link](11);
[Link](51);
[Link](1);
//Sorting the list
[Link](list2);
//Traversing list through the for-each loop
for(Integer number:list2)
[Link](number);
}
}
ListIterator Interface is used to traverse the element in a backward and forward direction.
Method Description
void add(E e) This method inserts the specified element into the list.
boolean hasNext() This method returns true if the list iterator has more elements while
traversing the list in the forward direction.
E next() This method returns the next element in the list and advances the
cursor position.
int nextIndex() This method returns the index of the element that would be returned
by a subsequent call to next()
boolean This method returns true if this list iterator has more elements while
hasPrevious() traversing the list in the reverse direction.
E previous() This method returns the previous element in the list and moves the
cursor position backward.
E previousIndex() This method returns the index of the element that would be returned
by a subsequent call to previous().
void remove() This method removes the last element from the list that was returned
by next() or previous() methods
void set(E e) This method replaces the last element returned by next() or previous()
methods with the specified element.
import [Link].*;
public class ListIteratorExample1{
public static void main(String args[]){
List<String> al=new ArrayList<String>();
[Link]("Amit");
[Link]("Vijay");
[Link]("Kumar");
[Link](1,"Sachin");
ListIterator<String> itr=[Link]();
[Link]("Traversing elements in forward direction");
while([Link]()){
[Link]("index:"+[Link]()+" value:"+[Link]());
}
[Link]("Traversing elements in backward direction");
while([Link]()){
[Link]("index:"+[Link]()+" value:"+[Link]());
}
}
}
import [Link].*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
[Link] = id;
[Link] = name;
[Link] = author;
[Link] = publisher;
[Link] = quantity;
}
}
public class ListExample5 {
public static void main(String[] args) {
//Creating list of Books
List<Book> list=new ArrayList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Graw Hill",4);
The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can
use all the methods of the List interface here. The ArrayList maintains the insertion order internally.
o Java ArrayList gets initialized by the size. The size is dynamic in the array list, which varies
according to the elements getting added or removed from the list.
Hierarchy of ArrayList class
As shown in the above diagram, the Java ArrayList class extends AbstractList class which implements
the List interface. The List interface extends the Collection and Iterable interfaces in hierarchical order.
Constructors of ArrayList
Constructor Description
ArrayList(Collection<? extends It is used to build an array list that is initialized with the
E> c) elements of the collection c.
ArrayList(int capacity) It is used to build an array list that has the specified
initial capacity.
Methods of ArrayList
Method Description
void add(int index, E element) It is used to insert the specified element at the
specified position in a list.
boolean add(E e) It is used to append the specified element at the end
of a list.
boolean addAll(Collection<? extends E> It is used to append all of the elements in the specified
c) collection to the end of this list, in the order that they
are returned by the specified collection's iterator.
boolean addAll(int index, Collection<? It is used to append all the elements in the specified
extends E> c) collection, starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
Iterator()
listIterator()
int lastIndexOf(Object o) It is used to return the index in this list of the last
occurrence of the specified element, or -1 if the list
does not contain this element.
boolean contains(Object o) It returns true if the list contains the specified element.
int indexOf(Object o) It is used to return the index in this list of the first
occurrence of the specified element, or -1 if the List
does not contain this element.
boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.
boolean removeIf(Predicate<? super E> It is used to remove all the elements from the list that
filter) satisfies the given predicate.
protected void removeRange(int It is used to remove all the elements lies within the
fromIndex, int toIndex) given range.
void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list with
operator) the specified element.
void retainAll(Collection<?> c) It is used to retain all the elements in the list that are
present in the specified collection.
E set(int index, E element) It is used to replace the specified element in the list,
present at the specified position.
void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of
the specified comparator.
List<E> subList(int fromIndex, int toIndex) It is used to fetch all the elements that lies within the
given range.
Let's see an example to traverse ArrayList elements using the Iterator interface.
import [Link].*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Mango");//Adding object in arraylist
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Traversing list through Iterator
Iterator itr=[Link]();//getting the Iterator
while([Link]()){//check if iterator has the elements
[Link]([Link]());//printing the element and move to next
}
}
}
Iterating ArrayList using For-each loop
Let's see an example to traverse the ArrayList elements using the for-each loop
import [Link].*;
public class ArrayListExample3{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Mango");//Adding object in arraylist
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Traversing list through for-each loop
for(String fruit:list)
[Link](fruit);
}
}
The get() method returns the element at the specified index, whereas the set() method changes the
element.
import [Link].*;
public class ArrayListExample4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
[Link]("Mango");
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//accessing the element
[Link]("Returning element: "+[Link](1));
//it will return the 2nd element, because
index starts from 0
//changing the element
[Link](1,"Dates");
//Traversing list
for(String fruit:al)
[Link](fruit);
}
}
The [Link] package provides a utility class Collections, which has the static method sort(). Using
the [Link]() method, we can easily sort the ArrayList.
import [Link].*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
[Link]("Mango");
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Sorting the list
[Link](list1);
//Traversing list through the for-each loop
for(String fruit:list1)
[Link](fruit);
[Link]("Sorting numbers...");
//Creating a list of numbers
List<Integer> list2=new ArrayList<Integer>();
[Link](21);
[Link](11);
[Link](51);
[Link](1);
//Sorting the list
[Link](list2);
//Traversing list through the for-each loop
for(Integer number:list2)
[Link](number);
}
}
Ways to iterate the elements of the collection in Java
1. By Iterator interface.
2. By for-each loop.
3. By ListIterator interface.
4. By for loop.
5. By forEach() method.
6. By forEachRemaining() method.
Let's see an example to traverse the ArrayList elements through other ways
import [Link].*;
class ArrayList4{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
[Link]("Ravi"); //Adding object in arraylist
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Let's see an example where we are storing Student class object in an array list.
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
[Link]=rollno;
[Link]=name;
[Link]=age;
}
}
import [Link].*;
class ArrayList5{
public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student(101,"Sonoo",23);
Student s2=new Student(102,"Ravi",21);
Student s2=new Student(103,"Hanumat",25);
//creating arraylist
ArrayList<Student> al=new ArrayList<Student>();
[Link](s1);//adding Student class object
[Link](s2);
[Link](s3);
//Getting Iterator
Iterator itr=[Link]();
//traversing elements of ArrayList object
while([Link]()){
Student st=(Student)[Link]();
[Link]([Link]+" "+[Link]+" "+[Link]);
}
}
}
import [Link].*;
class ArrayList7{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
[Link]("Initial list of elements: "+al);
//Adding elements to the end of the list
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("After invoking add(E e) method: "+al);
//Adding an element at the specific position
[Link](1, "Gaurav");
[Link]("After invoking add(int index, E element) method: "+al);
ArrayList<String> al2=new ArrayList<String>();
[Link]("Sonoo");
[Link]("Hanumat");
//Adding second list elements to the first list
[Link](al2);
[Link]("After invoking addAll(Collection<? extends E> c) method: "+al);
ArrayList<String> al3=new ArrayList<String>();
[Link]("John");
[Link]("Rahul");
//Adding second list elements to the first list at specific position
[Link](1, al3);
[Link]("After invoking addAll(int index, Collection<? extends E> c) method: "+al);
}
}
import [Link].*;
class ArrayList8 {
import [Link].*;
class ArrayList9{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
ArrayList<String> al2=new ArrayList<String>();
[Link]("Ravi");
[Link]("Hanumat");
[Link](al2);
[Link]("iterating the elements after retaining the elements of al2");
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Let's see an ArrayList example where we are adding books to the list and printing all the books.
import [Link].*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
[Link] = id;
[Link] = name;
[Link] = author;
[Link] = publisher;
[Link] = quantity;
}
}
public class ArrayListExample20 {
public static void main(String[] args) {
//Creating list of Books
List<Book> list=new ArrayList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Graw Hill",4);
Size and capacity of an array list are the two terms that beginners find confusing. Let's understand it in this
section with the help of some examples. Consider the following code snippet.
import [Link].*;
Output:
The size of the array is: 0
Explanation: The output makes sense as we have not done anything with the array list. Now observe
the following program.
import [Link].*;
Output:
Explanation: We see that the size is still 0, and the reason behind this is the number 10 represents the
capacity no the size. In fact, the size represents the total number of elements present in the array. As we
have not added any element, therefore, the size of the array list is zero in both programs.
Capacity represents the total number of elements the array list can contain. Therefore, the capacity of an
array list is always greater than or equal to the size of the array list. When we add an element to the
array list, it checks whether the size of the array list has become equal to the capacity or not. If yes, then
the capacity of the array list increases. So, in the above example, the capacity will be 10 till 10 elements
are added to the list. When we add the 11th element, the capacity increases. Note that in both examples,
the capacity of the array list is 10. In the first case, the capacity is 10 because the default capacity of the
array list is 10. In the second case, we have explicitly mentioned that the capacity of the array list is 10.
As shown in the above diagram, Java LinkedList class extends AbstractSequentialList class and
implements List and Deque interfaces.
In the case of a doubly linked list, we can add or remove elements from both sides.
Constructor Description
Method Description
void add(int index, E element) It is used to insert the specified element at the
specified position index in a list.
<T> T[] toArray(T[] a) It returns an array containing all the elements in the
proper sequence (from first to the last element); the
runtime type of the returned array is that of the
specified array.
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
import [Link].*;
public class LinkedList2{
public static void main(String args[]){
LinkedList<String> ll=new LinkedList<String>();
[Link]("Initial list of elements: "+ll);
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("After invoking add(E e) method: "+ll);
//Adding an element at the specific position
[Link](1, "Gaurav");
[Link]("After invoking add(int index, E element) method: "+ll);
LinkedList<String> ll2=new LinkedList<String>();
[Link]("Sonoo");
[Link]("Hanumat");
//Adding second list elements to the first list
[Link](ll2);
[Link]("After invoking addAll(Collection<? extends E> c) method: "+ll);
LinkedList<String> ll3=new LinkedList<String>();
[Link]("John");
[Link]("Rahul");
//Adding second list elements to the first list at specific position
[Link](1, ll3);
[Link]("After invoking addAll(int index, Collection<? extends E> c) method: "+ll);
//Adding an element at the first position
[Link]("Lokesh");
[Link]("After invoking addFirst(E e) method: "+ll);
//Adding an element at the last position
[Link]("Harsh");
[Link]("After invoking addLast(E e) method: "+ll);
}
}
import [Link].*;
public class LinkedList4{
public static void main(String args[]){
Java Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-number
of elements in it as there is no size limit. It is a part of Java Collection framework since Java 1.2. It is
found in the [Link] package and implements the List interface, so we can use all the methods of List
interface here.
It is recommended to use the Vector class in the thread-safe implementation only. If you don't need to
use the thread-safe implementation, you should use the ArrayList, the ArrayList will perform better in
such case.
The Iterators returned by the Vector class are fail-fast. In case of concurrent modification, it fails and
throws the ConcurrentModificationException.
o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a collections framework.
Vector class supports four types of constructors. These are given below:
Constructor Description
Vector( Collection<? extends E> c) It constructs a vector that contains the elements of
a collection c.
Method Description
addAll() It is used to append all of the elements in the specified collection to the
end of this Vector.
addElement() It is used to append the specified component to the end of this vector. It
increases the vector size by one.
containsAll() It returns true if the vector contains all of the elements in the specified
collection.
copyInto() It is used to copy the components of the vector into the specified array.
equals() It is used to compare the specified object with the vector for equality.
forEach() It is used to perform the given action for each element of the Iterable until
all elements have been processed or the action throws an exception.
indexOf() It is used to get the index of the first occurrence of the specified element in
the vector. It returns -1 if the vector does not contain the element.
insertElementAt() It is used to insert the specified object as a component in the given vector
at the specified index.
iterator() It is used to get an iterator over the elements in the list in proper sequence.
lastIndexOf() It is used to get the index of the last occurrence of the specified element in
the vector. It returns -1 if the vector does not contain the element.
listIterator() It is used to get a list iterator over the elements in the list in proper
sequence.
remove() It is used to remove the specified element from the vector. If the vector
does not contain the element, it is unchanged.
removeAll() It is used to delete all the elements from the vector that are present in the
specified collection.
removeAllElements() It is used to remove all elements from the vector and set the size of the
vector to zero.
removeIf() It is used to remove all of the elements of the collection that satisfy the
given predicate.
removeRange() It is used to delete all of the elements from the vector whose index is
between fromIndex, inclusive and toIndex, exclusive.
replaceAll() It is used to replace each element of the list with the result of applying the
operator to that element.
retainAll() It is used to retain only that element in the vector which is contained in the
specified collection.
set() It is used to replace the element at the specified position in the vector with
the specified element.
setElementAt() It is used to set the component at the specified index of the vector to the
specified object.
sort() It is used to sort the list according to the order induced by the specified
Comparator.
spliterator() It is used to create a late-binding and fail-fast Spliterator over the elements
in the list.
subList() It is used to get a view of the portion of the list between fromIndex,
inclusive, and toIndex, exclusive.
toArray() It is used to get an array containing all of the elements in this vector in
correct order.
trimToSize() It is used to trim the capacity of the vector to the vector's current size.
import [Link].*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new Vector<String>();
//Adding elements using add() method of List
[Link]("Tiger");
[Link]("Lion");
[Link]("Dog");
[Link]("Elephant");
//Adding elements using addElement() method of Vector
[Link]("Rat");
[Link]("Cat");
[Link]("Deer");
[Link]("Elements are: "+vec);
}
}
The stack is a linear data structure that is used to store the collection of objects. It is based on Last-In-
First-Out (LIFO). Java collection framework provides many interfaces and classes to store the
collection of objects. One of them is the Stack class that provides different operations such as push,
pop, search, etc.
In this section, we will discuss the Java Stack class, its methods, and implement the stack data
structure in a Java program. But before moving to the Java Stack class have a quick view of how the
stack works.
The stack data structure has the two most important operations that are push and pop. The push
operation inserts an element into the stack and pop operation removes an element from the top of the
stack. Let's see how they work on stack.
Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.
When we push an element into the stack the top is increased by 1. In the following figure,
In Java, Stack is a class that falls under the Collection framework that extends the Vector class. It also
implements interfaces List, Collection, Iterable, Cloneable, Serializable. It represents the LIFO stack
of objects. Before using the Stack class, we must import the [Link] package. The stack class arranged
in the Collections framework hierarchy, as shown below.
Stack Class Constructor
The Stack class contains only the default constructor that creates an empty stack.
public Stack()
Creating a Stack
If we want to create a stack, first, import the [Link] package and create an object of the Stack class.
Or
Where type denotes the type of stack like Integer, String, etc.
push(E item) E The method pushes (insert) an element onto the top of the
stack.
pop() E The method removes an element from the top of the stack
and returns the same element as the value of that function.
peek() E The method looks at the top element of the stack without
removing it.
search(Object int The method searches the specified object and returns the
o) position of the object.
Stack Class empty() Method
The empty() method of the Stack class check the stack is empty or not. If the stack is empty, it returns
true, else returns false. We can also use the isEmpty() method of the Vector class.
Syntax
Returns: The method returns true if the stack is empty, else returns false.
In the following example, we have created an instance of the Stack class. After that, we have invoked
the empty() method two times. The first time it returns true because we have not pushed any element
into the stack. After that, we have pushed elements into the stack. Again we have invoked the empty()
method that returns false because the stack is not empty.
import [Link];
public class StackEmptyMethodExample
{
public static void main(String[] args)
{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
// checking stack is empty or not
boolean result = [Link]();
[Link]("Is the stack empty? " + result);
// pushing elements into stack
[Link](78);
[Link](113);
[Link](90);
[Link](120);
//prints elements of the stack
[Link]("Elements in Stack: " + stk);
result = [Link]();
[Link]("Is the stack empty? " + result);
}
}
The method inserts an item onto the top of the stack. It works the same as the method addElement(item)
method of the Vector class. It passes a parameter item to be pushed into the stack.
Syntax
Returns: The method returns the argument that we have passed as a parameter.
The method removes an object at the top of the stack and returns the same object. It
throws EmptyStackException if the stack is empty.
Syntax
public E pop()
It looks at the element that is at the top in the stack. It also throws EmptyStackException if the stack is
empty.
Syntax
public E peek()
import [Link];
public class StackPeekMethodExample
{
public static void main(String[] args)
{
Stack<String> stk= new Stack<>();
// pushing elements into Stack
[Link]("Apple");
[Link]("Grapes");
[Link]("Mango");
[Link]("Orange");
[Link]("Stack: " + stk);
// Access element from the top of the stack
String fruits = [Link]();
//prints stack
[Link]("Element at top: " + fruits);
}
}
The method searches the object in the stack from the top. It parses a parameter that we want to search
for. It returns the 1-based location of the object in the stack. Thes topmost object of the stack is
considered at distance 1.
Suppose, o is an object in the stack that we want to search for. The method returns the distance from the
top of the stack of the occurrence nearest the top of the stack. It uses equals() method to search an
object in the stack.
Syntax
Returns: It returns the object location from the top of the stack. If it returns -1, it means that the object
is not on the stack.
import [Link];
public class StackSearchMethodExample
{
public static void main(String[] args)
{
Stack<String> stk= new Stack<>();
//pushing elements into Stack
[Link]("Mac Book");
[Link]("HP");
[Link]("DELL");
[Link]("Asus");
[Link]("Stack: " + stk);
// Search an element
int location = [Link]("HP");
[Link]("Location of Dell: " + location);
}
}
We can also find the size of the stack using the size() method of the Vector class. It returns the total
number of elements (size of the stack) in the stack.
Syntax
import [Link];
public class StackSizeExample
{
public static void main (String[] args)
{
Stack stk = new Stack();
[Link](22);
[Link](33);
[Link](44);
[Link](55);
[Link](66);
// Checks the Stack is empty or not
boolean rslt=[Link]();
[Link]("Is the stack empty or not? " +rslt);
// Find the size of the Stack
int x=[Link]();
[Link]("The stack size is: "+x);
}
}
Iterate Elements
Iterate means to fetch the elements of the stack. We can fetch elements of the stack using three different
methods are as follows:
It is the method of the Iterator interface. It returns an iterator over the elements in the stack. Before
using the iterator() method import the [Link] package.
Syntax
Iterator<T> iterator()
import [Link];
import [Link];
public class StackIterationExample1
{
public static void main (String[] args)
{
//creating an object of Stack class
Stack stk = new Stack();
//pushing elements into stack
[Link]("BMW");
[Link]("Audi");
[Link]("Ferrari");
[Link]("Bugatti");
[Link]("Jaguar");
//iteration over the stack
Iterator iterator = [Link]();
while([Link]())
{
Object values = [Link]();
[Link](values);
}
}
}
Java provides a forEach() method to iterate over the elements. The method is defined in
the Iterable and Stream interface.
Syntax
import [Link].*;
public class StackIterationExample2
{
public static void main (String[] args)
{
//creating an instance of Stack class
Stack <Integer> stk = new Stack<>();
//pushing elements into stack
[Link](119);
[Link](203);
[Link](988);
[Link]("Iteration over the stack using forEach() Method:");
//invoking forEach() method for iteration over the stack
[Link](n ->
{
[Link](n);
});
}
}
Using listIterator() Method
This method returns a list iterator over the elements in the mentioned list (in sequence), starting at the
specified position in the list. It iterates the stack from top to bottom.
Syntax
Returns: This method returns a list iterator over the elements, in sequence.
import [Link];
import [Link];
import [Link];
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
Note: Multiple inheritance is not supported in Java through class.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
class Animal
{
void eat()
{
[Link]("eating...");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("barking...");
}
}
class TestInheritance{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
[Link]();
}
}
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes.
If A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
error.
class A{
void msg(){[Link]("Hello");}
}
class B{
void msg(){[Link]("Welcome");}
}
class C extends A,B{
Method Overriding:
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
In this example, we have defined the run method in the subclass as defined in the parent class
but it has some specific implementation. The name and parameter of the method are the same,
and there is IS-A relationship between the classes, so there is method overriding.
Consider a scenario where Bank is a class that provides functionality to get the rate of interest.
However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS
banks could provide 8%, 7%, and 9% rate of interest.
Super Keyword:
The super keyword in Java is a reference variable which is used to refer immediate parent class
object. Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
[Link](color);//prints color of Dog class
[Link]([Link]);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}
In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property,
we need to use super keyword.
The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void eat(){[Link]("eating bread...");}
void bark(){[Link]("barking...");}
void work(){
[Link]();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}
In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given
to local.
The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:
class Animal{
Animal(){[Link]("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
[Link]("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Method overloading is used to increase the Method overriding is used to provide the
readability of the program. specific implementation of the method that is
already provided by its super class.
Method overloading is performed within class. Method overriding occurs in two classes that
have IS-A (inheritance) relationship.
In case of method overloading, parameter must In case of method overriding, parameter must
be different. be same.
Method overloading is the example of compile Method overriding is the example of run time
time polymorphism. polymorphism.
In java, method overloading can't be performed Return type must be same or covariant in
by changing return type of the method method overriding.
only. Return type can be same or different in
method overloading. But you must have to
change the parameter.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
If you overload a static method in Java, it is the example of compile time polymorphism.
Here, we will focus on runtime polymorphism in java.
In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.
Let's first understand the upcasting before Runtime Polymorphism.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
class A{}
class B extends A{}
A a=new B();//upcasting
In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike
class and overrides its run() method. We are calling the run method by the reference variable
of Parent class. Since it refers to the subclass object and subclass method overrides the Parent
class method, the subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.
class Bike
{
void run()
{
[Link]("running");
}
}
class Splendor extends Bike
{
void run()
{
[Link]("running safely with 60km");
}
}
class Demo
{
public static void main(String args[])
{
Bike b = new Splendor();//upcasting
[Link]();
}
}
Consider a scenario where Bank is a class that provides a method to get the rate of interest.
However, the rate of interest may differ according to banks. For example, SBI, ICICI, and
AXIS banks are providing 8.4%, 7.3%, and 9.7% rate of interest.
class Bank
{
float getRateOfInterest()
{return 0;}
}
class SBI extends Bank
{
float getRateOfInterest()
{return 8.4f;}
}
class ICICI extends Bank
{
float getRateOfInterest()
{return 7.3f;}
}
class AXIS extends Bank
{
float getRateOfInterest()
{return 9.7f;}
}
class TestPolymorphism
{
public static void main(String args[])
{
Bank b;
b=new SBI();
[Link]("SBI Rate of Interest: "+[Link]());
b=new ICICI();
[Link]("ICICI Rate of Interest: "+[Link]());
b=new AXIS();
[Link]("AXIS Rate of Interest: "+[Link]());
}
}
Abstract Class:
An abstract class in Java is one that is declared with the abstract keyword. It may have both
abstract and non-abstract methods (methods with bodies). An abstract is a java modifier
applicable for classes and methods in java but not for Variables.
In java, the following some important observations about abstract classes are as follows:
Example :
class Abstract
{
Final Keyword:
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block
only. We will have detailed learning of these. Let's first learn the basics of final keyword.
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
There is a final variable speedlimit, we are going to change the value of this variable, but It
can't be changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
[Link]();
}
}//end of class
Output:
Output:
Interface:
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
. There can be only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java
In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
There are mainly three reasons to use interface. They are given below.
An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public, static
and final by default. A class that implements an interface must implement all the methods
declared in the interface.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Since Java 8 , interface can have default and static methods which is discussed later.
Note: The Java compiler adds public and abstract keywords before the interface method.
Moreover, it adds public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and the methods are
public and abstract.
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
Java Interface Example
In this example, the Printable interface has only one method, and its implementation is provided
in the Demo class.
interface printable
{
void print();
}
class Demo implements printable
{
public void print()
{
[Link]("Hello");
}
public static void main(String args[])
{
Demo obj = new Demo();
[Link]();
}
}
Java Interface Example: Bank
Let's see another example of java interface which provides the implementation of Bank
interface.
interface Bank
{
float rateOfInterest();
}
class SBI implements Bank
{
public float rateOfInterest()
{return 9.15f;}
}
class PNB implements Bank
{
public float rateOfInterest()
{return 9.7f;}
}
class TestInterface2
{
public static void main(String[] args)
{
Bank b=new SBI();
[Link]("ROI: "+[Link]());
}
}
As we have explained in the inheritance chapter, multiple inheritance is not supported in the
case of class because of ambiguity. However, it is supported in case of an interface because
there is no ambiguity. It is because its implementation is provided by the implementation class.
For example:
interface Printable
{
void print();
}
interface Showable
{
void print();
}
As you can see in the above example, Printable and Showable interface have same methods
but its implementation is provided by class TestTnterface1, so there is no ambiguity.
Interface inheritance
Example:
interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
class TestInterface4 implements Showable
{
public void print()
{
[Link]("Hello");
}
public void show()
{
[Link]("Welcome");
}
public static void main(String args[])
{
TestInterface4 obj = new TestInterface4();
[Link]();
[Link]();
}
}
Since Java 8, we can have method body in interface. But we need to make it default method.
Let's see an example:
interface Drawable
{
void draw();
default void msg()
{
[Link]("default method");
}
}
class Rectangle implements Drawable
{
public void draw()
{
[Link]("drawing rectangle");
}
}
class TestInterfaceDefault
{
public static void main(String args[])
{
Drawable d=new Rectangle();
[Link]();
[Link]();
}
}
Since Java 8, we can have static method in interface. Let's see an example:
interface Drawable
{
void draw();
static int cube(int x)
{
return x*x*x;
}
}
class Rectangle implements Drawable
{
public void draw()
{
[Link]("drawing rectangle");
}
}
class TestInterfaceStatic
{
public static void main(String args[])
{
Drawable d=new Rectangle();
[Link]();
[Link]([Link](3));
}
}
An interface, i.e., declared within another interface or class, is known as a nested interface. The
nested interfaces are used to group related interfaces so that they can be easy to maintain. The
nested interface must be referred to by the outer interface or class. It can't be accessed directly.
Example:
interface Showable
{
void show();
interface Message
{
void msg();
}
}
class TestNestedInterface1 implements [Link]
{
public void msg()
{
[Link]("Hello nested interface");
}
class A
{
interface Message
{
void msg();
}
}
Yes, if we define a class inside the interface, the Java compiler creates a static nested class.
Let's see how we can define a class within the interface:
Syntax:
interface M
{
class A{}
}
But there are many differences between abstract class and interface that are given below.
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since
abstract methods. Java 8, it can have default and static
methods also.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.
7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves
fully abstraction (100%).
Java Package:
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
package mypack;
public class Fibonacci
{
int i,f1=0,f2=1,f3;
public void getFibonacci(int num)
{
[Link](f1+" "+f2);
for(i=2;i<num;i++)
{
f3=f1+f2;
[Link](" "+f3);
f1=f2;
f2=f3;
}
}
}
If you are not using any IDE, you need to follow the syntax given below:
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:\abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
There are three ways to access the package from outside the package.
1. import package.*;
2. import [Link];
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
import mypack.*;
public class Demo
{
public static void main(String args[])
{
Fibonacci f= new Fibonacci();
[Link](10);
}
}
Output: 0 1 1 2 3 5 8 13 21 34
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
import [Link];
public class Demo
{
public static void main(String args[])
{
Fibonacci f= new Fibonacci();
[Link](10);
}
}
Output: 0 1 1 2 3 5 8 13 21 34
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. [Link] and [Link]
packages contain Date class.
Output: 0 1 1 2 3 5 8 13 21 34
4. Exception Handling and Multithreading
Concept of exception:
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is why
we need to handle exceptions. Let's consider a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5;
the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements will be executed.
That is why we use exception handling in Java.
Hierarchy of Java Exception classes
The [Link] class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
Exception
The term exception is shorthand for the phrase exception event. It is an event that occurs
during the execution of the program and interrupts the normal flow of program instructions.
These are the errors that occur at compile time and run time. It occurs in the code written by
the developers. It can be recovered by using the try-catch block and throws keyword. There
are two types of exceptions i.e. checked and unchecked.
There are some important points that should be kept in mind while dealing with the
exception:
Advantages of Exceptions
o It separates error handling code from regular code.
o It has the ability to propagate error reporting up the call stack of methods.
o The grouping or categorizing of exceptions is a natural outcome of the class
hierarchy.
Example of Exception
import [Link];
public class ExcptionExample
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
[Link]("You have entered: "+number);
}
}
Let's run the above program and enter a float value deliberately to generate an exception.
It shows the InputMismatchExaception. Because the program accepts an integer value. We
observe that the next statement is skipped and the program is terminated.
Error
Errors
are problems that mainly occur due to the lack of system resources. It cannot be caught or
handled. It indicates a serious problem. It occurs at run time. These are always unchecked.
An example of errors is OutOfMemoryError, LinkageError, AssertionError, etc. are the
subclasses of the Error class.
Example of Error
In Java, Error, and Exception both are subclasses of the Java Throwable class that belongs to
[Link] package.
Type It can be classified into two All errors in Java are unchecked.
categories i.e. checked and
unchecked.
Known or Only checked exceptions are Errors will not be known to the
unknown known to the compiler. compiler.
1. Checked Exception
2. Unchecked Exception
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
Java provides five keywords that are used to handle the exception. The following table
describes each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must be
followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by
finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always
used with method signature.
Let's see an example of Java Exception Handling in which we are using a try-catch statement
to handle the exception.
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
//rest code of the program
[Link]("rest of the code...");
}
}
Output:
D:\>java JavaExceptionExample
[Link]: / by zero
There are given some scenarios where unchecked exceptions may occur. They are as follows:
int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
[Link]([Link]());//NullPointerException
3) A scenario where NumberFormatException occurs
String s="abc";
int i=[Link](s);//NumberFormatException
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may
be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following
statements.
Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
If an exception occurs at the particular statement in the try block, the rest of the block code
will not execute. So, it is recommended not to keep the code in try block that will not throw
an exception.
Java try block must be followed by either catch or finally block.
The catch block must be used after the try block only. You can use multiple catch block with
a single try block.
The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:
But if the application programmer handles the exception, the normal flow of the application
is maintained, i.e., rest of the code is executed.
D:\>javac [Link]
D:\>java TryCatchExample1
at [Link]([Link])
As displayed in the above example, the rest of the code is not executed (in such case,
the rest of the code statement is not printed).
There might be 100 lines of code after the exception. If the exception is not handled, all the
code below the exception won't be executed.
Let's see the solution of the above problem by a java try-catch block.
Output:
D:\>javac [Link]
D:\>java TryCatchExample2
[Link]: / by zero
rest of the code
As displayed in the above example, the rest of the code is executed, i.e., the rest of the
code statement is printed.
Example 3
Output:
D:\>javac [Link]
D:\>java TryCatchExample3
[Link]: / by zero
rest of the code
Example 4
Output:
D:\>javac [Link]
D:\>java TryCatchExample4
Can't divided by zero
Example 5
In this example, we handle the generated exception (Arithmetic Exception) with a different
type of exception class (ArrayIndexOutOfBoundsException).
Output:
D:\>javac [Link]
D:\>java TryCatchExample5
[Link]: Index 10 out of bounds for length 4
rest of the code
Example 6
import [Link];
Output:
D:\>javac [Link]
[Link][Link] error: unreported exception FileNotFoundException; must be
caught or declared to be thrown
pw = new PrintWriter("[Link]"); //may throw exception
^
1 error
In above example exception caught at compile time, we can handle it by using try
catch block. Let’s see using below example.
import [Link];
import [Link];
public class TryCatchExample6
{
public static void main(String[] args)
{
PrintWriter pw;
try {
pw = new PrintWriter("[Link]"); //may throw exception
[Link]("saved");
}
catch (FileNotFoundException e)
{
[Link](e);
}
[Link]("File saved successfully");
}
}
Output:
D:\>javac [Link]
D:\>java TryCatchExample6
A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Flowchart of Multi-catch Block
Example 1
D:\>javac [Link]
D:\>java MultipleCatchBlock1
In this example, try block contains two exceptions. But at a time only one exception
occurs and its corresponding catch block is executed.
Example 2
Output:
D:\>javac [Link]
D:\>java MultipleCatchBlock2
Parent Exception occurs
rest of the code
Example 3
Let's see an example, to handle the exception without maintaining the order of exceptions
(i.e. from most specific to most general).
class MultipleCatchBlock3
{
public static void main(String args[])
{
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e)
{
[Link]("common task completed");
}
catch(ArithmeticException e)
{
[Link]("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("task 2 completed");
}
[Link]("rest of the code...");
}
}
Output:
Compile-time error
Java finally block is a block used to execute important code such as closing the connection,
etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception
occurs or not.
The finally block follows the try-catch block.
Flowchart of finally block
Note: If you don't handle the exception, before terminating the program, JVM executes
finally block (if any).
o finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
o The important statements to be printed can be placed in the finally block.
Let's see the different cases where Java finally block can be used.
Let's see the below example where the Java program does not throw any exception, and the
finally block is executed after the try block.
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
//below code do not throw any exception
int data=25/5;
[Link](data);
}
//catch won't be executed
catch(ArithmeticException e)
{
[Link](e);
}
//executed regardless of exception occurred or not
finally
{
[Link]("finally block is always executed");
}
[Link]("rest of phe code...");
}
}
Output:
D:\>javac [Link]
D:\>java TestFinallyBlock`
5
finally block is always executed
rest of phe code...
D:\>
Case 2: When an exception occur but not handled by the catch block
Let's see the following example. Here, the code throws an exception however the catch block
cannot handle it. Despite this, the finally block is executed after the try block and then the
program terminates abnormally.
Example:
Let's see the following example where the Java code throws an exception and the catch block
handles the exception. Later the finally block is executed after the try-catch block. Further,
the rest of the code is also executed normally.
public class TestFinallyBlock2
{
public static void main(String args[])
{
try
{
[Link]("Inside try block");
Output:
D:\>javac [Link]
D:\>java TestFinallyBlock2
Inside try block
Exception handled
[Link]: / by zero
finally block is always executed
rest of the code...
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if the program exits (either by calling
[Link]() or by causing a fatal error that causes the process to abort).
We specify the exception object which is to be thrown. The Exception has some message
with it that provides the error description. These exceptions may be related to user inputs,
server, etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly
used to throw a custom exception. We will discuss custom exceptions later in this section.
We can also define our own set of conditions and throw an exception explicitly using throw
keyword. For example, we can throw ArithmeticException if we divide a number by another
number. Here, we just need to set the condition and throw exception using throw keyword.
In this example, we have created a method named validate() that accepts an integer as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print
a message welcome to vote.
[Link]
In this example, we have created the validate method that takes integer value as a parameter.
If the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
Output:
D:\>javac [Link]
D:\>java TestThrow1
Exception in thread "main" [Link]: Person is not eligible to vote
at [Link]([Link])
at [Link]([Link])
The above code throw an unchecked exception. Similarly, we can also throw unchecked and
user defined exceptions.
Note: If we throw unchecked exception from a method, it is must to handle the exception.
If we throw a checked exception using throw keyword, it is must to handle the exception
using catch block.
class TestExceptionPropagation1
{
void m()
{
int data=50/0;
}
void n()
{
m();
}
void p()
{
try
{
n();
}
catch(Exception e)
{
[Link]("exception handled");
}
}
public static void main(String args[])
{
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
[Link]("normal flow...");
}
}
Output:
D:\>javac [Link]
D:\>java TestExceptionPropagation1
exception handled
normal flow...
In the above example exception occurs in the m() method where it is not handled, so it is
propagated to the previous n() method where it is not handled, again it is propagated to the
p() method where exception is handled.
Exception can be handled in any method in call stack either in the main() method, p()
method, n() method or m() method.
Note: By default, Checked Exceptions are not forwarded in calling chain (propagated).
class TestExceptionPropagation2
{
void m()
{
throw new [Link]("device error");//checked exception
}
void n()
{
m();
}
void p()
{
try
{
n();
}
catch(Exception e)
{
[Link]("exception handeled");
}
}
public static void main(String args[])
{
TestExceptionPropagation2 obj=new TestExceptionPropagation2();
obj.p();
[Link]("normal flow");
}
}
Output:
D:\>javac [Link]
1 error
D:\>
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers' fault that he is not
checking the code before it being used.
Let's see the example of Java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import [Link];
class Testthrows1
{
void m()throws IOException
{
throw new IOException("device error");//checked exception
}
void n()throws IOException
{
m();
}
void p()
{
try
{
n();
}
catch(Exception e)
{
[Link]("exception handled");
}
}
public static void main(String args[])
{
Testthrows1 obj=new Testthrows1();
obj.p();
[Link]("normal flow...");
}
}
Output:
D:\>javac [Link]
D:\>java Testthrows1
exception handled
normal flow...
Rule: If we are calling a method that declares an exception, we must either caught or declare
the exception.
There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:
1. Definition Java throw keyword is used Java throws keyword is used in the
throw an exception explicitly method signature to declare an
in the code, inside the exception which might be thrown by
function or the block of code. the function while the execution of the
code.
4. Declaration throw is used within the throws is used with the method
method. signature.
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.
Java exceptions cover almost all the general type of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.
In order to create custom exception, we need to extend Exception class that belongs to
[Link] package.
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.
Program:
Output:
D:\>javac [Link]
D:\>java TestCustomException1
InvalidAgeException: age is not valid to vote
at [Link]([Link])
at [Link]([Link])
rest of the code...
Multithreading in Java:
However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching between
the threads takes less time than process.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
Multitasking
o Each process has an address in memory. In other words, each process allocates a separate
memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-switching
between the threads. There can be multiple processes inside the OS, and one process can have
multiple threads.
Note: At a time one thread is executed only.
and methods to create and perform operations on a thread. Thread class extends Object class
In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
New: Whenever a new thread is created, it is always in the new state. For a thread in the new
state, the code has not been run yet and thus has not begun its execution.
Active: When a thread invokes the start() method, it moves from the new state to the active state.
The active state contains two states within it: one is runnable, and the other is running.
o Runnable: A thread, that is ready to run is then moved to the runnable state. In the
runnable state, the thread may be running or may be ready to run at any given instant of
time. It is the duty of the thread scheduler to provide the thread time to run, i.e., moving
the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each individual
thread. Each and every thread runs for a short span of time and when that allocated time
slice is over, the thread voluntarily gives up the CPU to the other thread, so that the other
threads can also run for their slice of time. Whenever such a scenario occurs, all those
threads that are willing to run, waiting for their turn to run, lie in the runnable state. In the
runnable state, there is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the runnable to the running state.
Generally, the most common change in the state of a thread is from runnable to running
and again back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then,
either the thread is in the blocked state or is in the waiting state.
For example, a thread (let's say its name is A) may want to print some data from the printer.
However, at the same time, the other thread (let's say its name is B) is using the printer to print
some data. Therefore, thread A has to wait for thread B to use the printer. Thus, thread A is in the
blocked state. A thread in the blocked state is unable to perform any execution and thus never
consume any cycle of the Central Processing Unit (CPU). Hence, we can say that thread A
remains idle until the thread scheduler reactivates thread A, which is in the waiting or blocked
state.
When the main thread invokes the join() method then, it is said that the main thread is in the
waiting state. The main thread then waits for the child threads to complete their tasks. When the
child threads complete their job, a notification is sent to the main thread, which again moves the
thread from waiting to the active state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread
scheduler to determine which thread to choose and which one to reject, and the chosen thread is
then given the opportunity to run.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is
A) has entered the critical section of a code and is not willing to leave that critical section. In
such a scenario, another thread (its name is B) has to wait forever, which leads to starvation. To
avoid such scenario, a timed waiting state is given to thread B. Thus, thread lies in the waiting
state for a specific span of time, and not forever. A real example of timed waiting is when we
invoke the sleep() method on a specific thread. The sleep() method puts the thread in the timed
wait state. After the time runs out, the thread wakes up and start its execution from when it has
left earlier.
Terminated: A thread reaches the termination state because of the following reasons:
o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is
dead, and there is no way one can respawn (active after kill) the dead thread.
The following diagram shows the different states involved in the life cycle of a thread.
Implementation of Thread States
In Java, one can get the current state of a thread using the [Link]() method.
The [Link] class of Java provides the constants ENUM to represent the state of
a thread. These constants are:
It represents the runnable [Link] means a thread is waiting in the queue to run.
It represents the blocked state. In this state, the thread is waiting to acquire a lock.
It represents the timed waiting state. The main difference between waiting and timed waiting is
the time constraint. Waiting has no time constraint, whereas timed waiting has the time
constraint. A thread invoking the following method reaches the timed waiting state.
o sleep
o join with timeout
o wait with timeout
o parkUntil
o parkNanos
It represents the final state of a thread that is terminated or dead. A terminated thread means it
has completed its execution.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs the
following tasks:
A component of Java that decides which thread to run or execute and which thread to wait is
called a thread scheduler in Java. In Java, a thread is only chosen by a thread scheduler if it is
in the runnable state. However, if there is more than one thread in the runnable state, it is up to
the thread scheduler to pick one of the threads and ignore the other ones. There are some criteria
that decide which thread will execute first. There are two factors for scheduling a thread
i.e. Priority and Time of arrival.
Priority: Priority of each thread lies between 1 to 10. If a thread has a higher priority, it means
that thread has got a better chance of getting picked up by the thread scheduler.
Time of Arrival: Suppose two threads of the same priority enter the runnable state, then priority
cannot be the factor to pick a thread from these two threads. In such a case, arrival time of
thread is considered by the thread scheduler. A thread that arrived first gets the preference over
the other threads.
On the basis of the above-mentioned factors, the scheduling algorithm is followed by a Java
thread scheduler.
In this scheduling algorithm, the scheduler picks the threads thar arrive first in the runnable
queue. Observe the following table:
t1 0
t2 1
t3 2
t4 3
In the above table, we can see that Thread t1 has arrived first, then Thread t2, then t3, and at last
t4, and the order in which the threads will be processed is according to the time of arrival of
threads.
Hence, Thread t1 will be processed first, and Thread t4 will be processed last.
Time-slicing scheduling:
Usually, the First Come First Serve algorithm is non-preemptive, which is bad as it may lead to
infinite blocking (also known as starvation). To avoid that, some time-slices are provided to the
threads so that after some time, the running thread has to give up the CPU. Thus, the other
waiting threads also get time to run their job.
In the above diagram, each thread is given a time slice of 2 seconds. Thus, after 2 seconds, the
first thread leaves the CPU, and the CPU is then captured by Thread2. The same process repeats
for the other threads too.
Preemptive-Priority Scheduling:
The name of the scheduling algorithm denotes that the algorithm is related to the priority of the
threads.
Suppose there are multiple threads available in the runnable state. The thread scheduler picks
that thread that has the highest priority. Since the algorithm is also preemptive, therefore, time
slices are also provided to the threads to avoid starvation. Thus, after some time, even if the
highest priority thread has not completed its job, it has to release the CPU because of
preemption.
Let's understand the working of the Java thread scheduler. Suppose, there are five threads that
have different arrival times and different priorities. Now, it is the responsibility of the thread
scheduler to decide which thread will get the CPU first.
The thread scheduler selects the thread that has the highest priority, and the thread begins the
execution of the job. If a thread is already in runnable state and another thread (that has higher
priority) reaches in the runnable state, then the current thread is pre-empted from the processor,
and the arrived thread with higher priority gets the CPU time.
When two threads (Thread 2 and Thread 3) having the same priorities and arrival time, the
scheduling will be decided on the basis of FCFS algorithm. Thus, the thread that arrives first gets
the opportunity to execute first.
The Java Thread class provides the two variant of the sleep() method. First one accepts only an
arguments, whereas the other variant accepts two arguments. The method sleep() is being used to
halt the working of a thread for a given amount of time. The time up to which the thread remains
in the sleeping state is known as the sleeping time of the thread. After the sleeping time is over,
the thread starts its execution from where it has left.
The method sleep() with the one parameter is the native method, and the implementation
of the native method is accomplished in another programming language. The other methods
having the two parameters are not the native method. That is, its implementation is accomplished
in Java. We can access the sleep() methods with the help of the Thread class, as the signature of
the sleep() methods contain the static keyword. The native, as well as the non-native method,
throw a checked Exception. Therefore, either try-catch block or the throws keyword can work
here.
The [Link]() method can be used with any thread. It means any other thread or the main
thread can invoke the sleep() method.
Parameters:
mls: The time in milliseconds is represented by the parameter mls. The duration for which the
thread will sleep is given by the method sleep().
n: It shows the additional time up to which the programmer or developer wants the thread to be
in the sleeping state. The range of n is from 0 to 999999.
Whenever the [Link]() methods execute, it always halts the execution of the current
thread.
Whenever another thread does interruption while the current thread is already in the sleep mode,
then the InterruptedException is thrown.
If the system that is executing the threads is busy, then the actual sleeping time of the thread is
generally more as compared to the time passed in arguments. However, if the system executing
the sleep() method has less load, then the actual sleeping time of the thread is almost equal to the
time passed in the argument.
The following example shows how one can use the sleep() method on the custom thread.
The Thread class provides methods to change and get the name of a thread. By default, each
thread has a name, i.e. thread-0, thread-1 and so on. By we can change the name of the thread by
using the setName() method. The syntax of setName() and getName() methods are given below:
We can also set the name of a thread directly when we create a new thread using the constructor
of the class.
[Link]();
[Link]();
[Link]("Java");
[Link]("After changing name of t1:"+[Link]());
[Link]("No change of t2:"+[Link]());
}
}
One can also set the name of a thread at the time of the creation of a thread, without using the
setName() method. Observe the following code.
import [Link].*;
class ThreadName extends Thread
{
ThreadName(String threadName)
{
super(threadName);
}
public void run()
{
[Link](" The thread is executing....");
}
}
public class ThreadNaming2
{
public static void main (String argvs[])
{
ThreadName th1 = new ThreadName("Java");
[Link]( [Link]());
[Link]();
}
}
Current Thread
Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, the thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses. Note that not only JVM a Java programmer can also assign the
priorities of a thread explicitly in a Java program.
Let's discuss the setter and getter method of the thread priority.
public final int getPriority(): The [Link]() method returns the priority of
the given thread.
import [Link].*;
[Link](6);
[Link](3);
[Link](9);
// Main thread
[Link]("Currently Executing The Thread : " + [Link]().getName());
[Link]("Priority of the main thread is : " + [Link]().getPriority());
[Link]().setPriority(10);
[Link]("Priority of the main thread is : " + [Link]().getPriority());
}
}
The yield() method of thread class causes the currently executing thread object to temporarily
pause and allow other threads to execute.
Syntax
public static void yield()
Example
join(): When the join() method is invoked, the current thread stops its execution and the thread
goes into the wait state. The current thread remains in the wait state until the thread on which the
join() method is invoked has achieved its dead state. If interruption of the thread occurs, then it
throws the InterruptedException.
Syntax:
join(long mls): When the join() method is invoked, the current thread stops its execution and the
thread goes into the wait state. The current thread remains in the wait state until the thread on
which the join() method is invoked called is dead or the wait for the specified time frame(in
milliseconds) is over.
Syntax:
public final synchronized void join(long mls) throws InterruptedException, where mls is in mil
liseconds
join(long mls, int nanos): When the join() method is invoked, the current thread stops its
execution and go into the wait state. The current thread remains in the wait state until the thread
on which the join() method is invoked called is dead or the wait for the specified time frame(in
milliseconds + nanos) is over.
Syntax:
public final synchronized void join(long mls, int nanos) throws InterruptedException, where
mls is in
Example of join() Method in Java
try
{
[Link]();
}
catch(Exception e)
{
[Link]("The exception has been caught " + e);
}
Daemon thread in Java is a service provider thread that provides services to the user thread. Its
life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this
thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
The sole purpose of the daemon thread is that it provides services to user thread for background
supporting task. If there is no user thread, why should JVM keep running this thread. That is why
JVM terminates the daemon thread if there is no user thread.
The [Link] class provides two methods for java daemon thread.
1) public void setDaemon(boolean is used to mark the current thread as daemon thread or
status) user thread.
2) public boolean isDaemon() is used to check that current is daemon.
Example 1:
Example 2:
}
}
Java Thread suspend() method
The suspend() method of thread class puts the thread from running to waiting state. This method
is used if you want to stop the thread execution and start it again when a certain event occurs.
This method allows a thread to temporarily cease execution. The suspended thread can be
resumed using the resume() method.
Syntax
public final void suspend()
Return
Example 1:
The resume() method of thread class is only used with suspend() method. This method is used to
resume a thread which was suspended using suspend() method. This method allows the
suspended thread to start again.
Syntax
public final void resume()
Example 1:
try
[Link](500);
[Link]([Link]().getName());
}catch(InterruptedException e){[Link](e);}
[Link](i);
}
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
The stop() method of thread class terminates the thread execution. Once a thread is stopped, it
cannot be restarted by start() method.
Syntax
public final void stop()
Example 1:
}
}
public static void main(String args[])
{
// creating three threads
StopExp t1=new StopExp ();
StopExp t2=new StopExp ();
StopExp t3=new StopExp ();
[Link]();
[Link]();
[Link]();
[Link]("Thread t3 is stopped");
}
}
Thread Synchronization
Synchronization in Java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Types of Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. It can
be achieved by using the following three ways:
Synchronization is built around an internal entity known as the lock or monitor. Every object has
a lock associated with it. By convention, a thread that needs consistent access to an object's fields
has to acquire the object's lock before accessing them, and then release the lock when it's done
with them.
In this example, there is no synchronization, so output is inconsistent. Let's see the example:
Program:
class BookTheaterSeat
{
int total_seats=10;
void bookSeat(int seats)
{
if (total_seats>=seats)
{
[Link](seats+"seats booked Sucessfully");
total_seats=total_seats-seats;
[Link]("seats Left : "+total_seats);
}
else
{
[Link]("Sorry seats cannot be booked.....!!");
[Link]("seats Left : "+total_seats);
}
}
}
Output:
7seats booked Sucessfully
6seats booked Sucessfully
seats Left : 3
seats Left : -3
Java Synchronized Method
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
Program:
class BookTheaterSeat
{
int total_seats=10;
synchronized void bookSeat(int seats)
{
if (total_seats>=seats)
{
[Link](seats+"seats booked Sucessfully");
total_seats=total_seats-seats;
[Link]("seats Left : "+total_seats);
}
else
{
[Link]("Sorry seats cannot be booked.....!!");
[Link]("seats Left : "+total_seats);
}
}
}
Output:
7seats booked Sucessfully
seats Left : 3
Sorry seats cannot be booked.....!!
seats Left : 3
Synchronized block can be used to perform synchronization on any specific resource of the
method.
Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines, in
such cases, we can use synchronized block.
If we put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
Points to Remember
Syntax
class BookTheaterSeat
{
int total_seats=10;
void bookSeat(int seats)
{
[Link]("hi : "+[Link]().getName());
[Link]("hi : "+[Link]().getName());
[Link]("hi : "+[Link]().getName());
[Link]("hi : "+[Link]().getName());
[Link]("hi : "+[Link]().getName());
synchronized(this)
{
if (total_seats>=seats)
{
[Link](seats+"seats booked Sucessfully");
total_seats=total_seats-seats;
[Link]("seats Left : "+total_seats);
}
else
{
[Link]("Sorry seats cannot be booked.....!!");
[Link]("seats Left : "+total_seats);
}
}
[Link]("hi : "+[Link]().getName());
[Link]("hi : "+[Link]().getName());
[Link]("hi : "+[Link]().getName());
[Link]("hi : "+[Link]().getName());
[Link]("hi : "+[Link]().getName());
}
}
class MovieBookApp extends Thread
{
static BookTheaterSeat b;
int seats;
public void run()
{
[Link](seats);
}
public static void main(String args[])
{
b=new BookTheaterSeat();
MovieBookApp om= new MovieBookApp();
[Link]=7;
[Link]();
Output:
hi : Thread-0
hi : Thread-1
hi : Thread-0
hi : Thread-1
hi : Thread-0
hi : Thread-1
hi : Thread-0
hi : Thread-0
hi : Thread-1
7seats booked Sucessfully
hi : Thread-1
seats Left : 3
Sorry seats cannot be booked.....!!
hi : Thread-0
seats Left : 3
hi : Thread-0
hi : Thread-1
hi : Thread-0
hi : Thread-1
hi : Thread-0
hi : Thread-1
hi : Thread-1
hi : Thread-0
hi : Thread-1
Static Synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
Suppose there are two objects of a shared class (e.g. Table) named object1 and object2. In case
of synchronized method and synchronized block there cannot be interference between t1 and t2
or t3 and t4 because t1 and t2 both refers to a common object that have a single lock. But there
can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3
acquires another lock. We don't want interference between t1 and t3 or t2 and t4. Static
synchronization solves this problem.
In this example we have used synchronized keyword on the static method to perform static
synchronization.
Program:
class BookTheaterSeat
{
static int total_seats=20;
static synchronized void bookSeat(int seats)
{
if (total_seats>=seats)
{
[Link](seats+"seats booked Sucessfully");
total_seats=total_seats-seats;
[Link]("seats Left : "+total_seats);
}
else
{
[Link]("Sorry seats cannot be booked.....!!");
[Link]("seats Left : "+total_seats);
}
}
}
class MovieBookApp
{
public static void main(String args[])
{
BookTheaterSeat b1=new BookTheaterSeat();
MyThread1 t1= new MyThread1(b1,7);
[Link]();
//----------------------------------------------------------------------------------------------
Output:
o wait()
o notify()
o notifyAll()
1) wait() method
The wait() method causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified amount of
time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation.
Syntax:
public final void notify()
3) notifyAll() method
Syntax:
public final void notifyAll()
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
Let's see the important differences between wait and sleep methods.
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release the lock.
It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.
Program:
Output: