Core Java
Core Java
Core Java
Java was developed by James Ghosling, Patrick Naughton, Mike Sheridan at Sun
Microsystems Inc. in 1991. It took 18 months to develop the first working version.
The initial name was Oak but it was renamed to Java in 1995
Java is one of the world's most important and widely used computer languages, and
it has held this distinction for many years. Unlike some other computer languages
whose influence has weared with passage of time, while Java's has grown.
Java is a high level, robust, object-oriented and a secure and stable programming
language but it is not a pure object-oriented language because it supports primitive
data types like int, char etc.
Core java is the one which is in standard edition and it is used to develop standalone
applications,system software.
Java is a platform-independent language because it has runtime environment i.e JRE and
API. Here platform means a hardware or software environment in which anapplication runs.
Java codes are compiled into byte code or machine-independent code. This byte code is run
on JVM (Java Virtual Machine).
Next major release was Java SE 7 which included many new changes, like :
And the latest addition to the lot is, Java SE 8, it was released on March 18, 2014.
Some of the major new features introduced in JAVA 8 are,
Lambda Expressions
New Collection Package java.util.stream to provide Stream API.
Enhanced Security
Nashorn Javascript Engine included
Parallel Array Sorting
The JDBC-ODBC Bridge has been removed etc.
the main areas which Java improved were Memory Management and mishandled
Exceptions by introducing automatic Garbage Collector and Exception Handling.
Java multithreading feature makes it possible to write program that can do many
tasks simultaneously. Benefit of multithreading is that it utilizes same memory and
other resources to execute multiple threads at the same time, like While typing,
grammatical errors are checked along.
LATEST VERSION OF JAVA 16V.
Microservices Introduction
A microservice is a small, loosely coupled distributed service. Microservice
Architectures evolved as a solution to the scalability and innovation challenges with
Monolith architectures (Monolith applications are typically huge – more 100, 000 line
of code). It allows you to take a large application and decompose or break into easily
manageable small components with narrowly defined responsibilities.
Reasons for using Microservice:
In monolith application, there are few challenges:
1 For a large application, it is difficult to understand the complexity and make code
changes fast and correctly, sometimes it becomes hard to manage the code.
2 Applications need extensive manual testing to ensure the impact of changes.
3 For small change, the whole application needs to be built and deployed.
4 The heavy application slows down start-up time.
Microservice Frameworks for Java:
There are several microservices frameworks that you can use for developing for
Java. Some of these are:
1 Spring Boot –
This is probably the best Java microservices framework that works on top of
languages for Inversion of Control, Aspect Oriented Programming, and others.
2 Dropwizard –
Dropwizard pulls together stable, mature libraries from the Java ecosystem into
a simple, light-weight package that lets you focus on getting things done.
3 Restlet –
Restlet Framework helps Java developers build better web APIs that follow the
REST architecture style.
4 Spark –
A micro-framework for creating web applications in Kotlin and Java 8 with
minimal effort.
New Features of JAVA 8
Below mentioned are some of the core upgrades done as a part of Java 8 release. Just go through
them quickly, we will explore them in details later.
Streams etc.
Ease of Use
programming technique.
INSIDE INSPECTION:
PROCESS OF A JAVA PROGRAM:
1.FIRST THE PROGRAM IS TYPED ACCORDING TO THE NORMS OF THE JAVA LANG
COMPILATION STAGE:
2.THEN IT IS SAVED AS .JAVA FILE AND THEN COMPILED(CHECKING THE SYNTAX OF THE PROGRAM)
EXECUTION STAGE(PROCESS OF RUNNING THE COMPILED CODE AND CHECK FOR OUTPUT):
ii)linking process(linking the loaded file into current running prg where they are needed using linker)
TRANSLATORS:
1.COMPILER: translate the whole program at a time.
Java has(compiler+interpreter)
How is Java platform independent?
The meaning of platform-independent is that the java compiled code(byte code) can
run on all operating systems.
A program is written in a language that is a human-readable language. It may
contain words, phrases, etc which the machine does not understand. For the source
code to be understood by the machine, it needs to be in a language understood by
machines, typically a machine-level language. So, here comes the role of a compiler.
The compiler converts the high-level language (human language) into a format
understood by the machines. Therefore, a compiler is a program that translates the
source code for another program from a programming language into executable
code.
This executable code may be a sequence of machine instructions that can be
executed by the CPU directly, or it may be an intermediate representation that is
interpreted by a virtual machine. This intermediate representation in Java is the Java
Byte Code.
Step by step Execution of Java Program:
Whenever, a program is written in JAVA, the javac compiles it.
The result of the JAVA compiler is the .class file or the bytecode and not the
machine native code (unlike C compiler).
The bytecode generated is a non-executable code and needs an interpreter to execute
on a machine. This interpreter is the JVM and thus the Bytecode is executed by the
JVM.
And finally program runs to give the desired output.
In case of C or C++ (language that are not platform independent), the compiler
generates an .exe file which is OS dependent. When we try to run this .exe file on
another OS it does not run, since it is OS dependent and hence is not compatible
with the other OS.
1.variables
2.methods
3.constructors
4.blocks
5.classes
6.interface
7.abstract class
JVM :
JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM
is the one that actually calls the main method present in a java code. JVM is a part
of JRE(Java Runtime Environment).
Java applications are called WORA (Write Once Run Anywhere). This means a
programmer can develop Java code on one system and can expect it to run on any
other Java enabled system without any adjustment. This is all possible because of
JVM.
When we compile a .java file, .class files(contains byte-code) with the same class
names present in .java file are generated by the Java compiler. This .class file goes
into various steps when we run it. These steps together describe the whole JVM.
In general, there are three class loaders :
Bootstrap class loader : Every JVM implementation must have a bootstrap
class loader, capable of loading trusted classes. It loads core java API
classes present in JAVA_HOME/jre/lib directory. This path is popularly
known as bootstrap path. It is implemented in native languages like C,
C++.
Extension class loader : It is child of bootstrap class loader. It loads the
classes present in the extensions
directories JAVA_HOME/jre/lib/ext(Extension path) or any other directory
specified by the java.ext.dirs system property. It is implemented in java by
the sun.misc.Launcher$ExtClassLoader class.
System/Application class loader : It is child of extension class loader. It is
responsible to load classes from application class path. It internally
uses Environment Variable which mapped to java.class.path. It is also
implemented in Java by the sun.misc.Launcher$AppClassLoader class.
The JVM is called a virtual machine because the JVM definition defines an
abstract machine. This includes registers, stack, etc, and the byte code that Java source is
compiled to is practically machine code for this virtual machine. The JVM then interprets or
compiles this byte code into native machine instructions.
JIT stands for Just In time compilation and JVM stands for Java Virtual Machine. JVM is a
virtual machine used in Java programming platform to execute or run Java programs. The
main advantage of JVM is that JVM makes Java platform-independent by executing
bytecodes.
The JIT (just in time compiler )helps improve the performance of Java programs by
compiling bytecodes into native machine code at run time. The JIT compiler is enabled
by default. When a method has been compiled, the JVM calls the compiled code of that
method directly instead of interpreting it.
Native code is computer programming (code) that is compiled to run with a particular
processor (such as an Intel x86-class processor) and its set of instructions. If the same
program is run on a computer with a different processor, software can be provided so that
the computer emulates the original processor.
JDK : The JDK also called Java Development Kit is a superset of the JRE, and contains
everything that is in the JRE, plus tools such as the compilers and debuggers necessary for
developing applets and applications.
JVM Memory
Method area :In method area, all class level information like class name,
immediate parent class name, methods and variables information etc. are
stored, including static variables. There is only one method area per JVM, and it
is a shared resource.
Heap area :Information of all objects is stored in heap area. There is also one Heap
Area per JVM. It is also a shared resource.
Stack area :For every thread, JVM create one run-time stack which is stored here.
Every block of this stack is called activation record/stack frame which store
methods calls. All local variables of that method are stored in their corresponding
frame. After a thread terminate, it’s run-time stack will be destroyed by JVM. It is
not a shared resource.
Native method stacks :For every thread, separate native stack is created. It stores
native method information.
Execution Engine
Execution engine execute the .class (bytecode). It reads the byte-code line by line,
use data and information present in various memory area and execute instructions. It
can be classified in three parts :-
Interpreter : It interprets the bytecode line by line and then executes. The
disadvantage here is that when one method is called multiple times, every time
interpretation is required.
Just-In-Time Compiler(JIT) : It is used to increase efficiency of interpreter.It
compiles the entire bytecode and changes it to native code so whenever
interpreter see repeated method calls,JIT provide direct native code for that part
so re-interpretation is not required,thus efficiency is improved.
Garbage Collector : It destroy un-referenced objects.
class Main {
public static void main(String args[])
{
System.out.println("Hello");
}
Output:
Hello
Does JVM create an object of class Main?
The answer is “No”. We have studied that the reason for main() static in Java is to
make sure that the main() can be called without any instance. To justify the same,
we can see that the following program compiles and runs fine.
{
System.out.println("Hello");
}
Output:
Hello
Since we can’t create object of abstract classes in Java, it is guaranteed that object
of class with main() is not created by JVM.
The Java virtual machine only performs two operations directly on Java Stacks: it pushes
and pops frames. And stack for a particular thread may be termed as Run – Time Stack.
Each and every method call performed by that thread is stored in the corresponding run time
stack including parameters, local variables, intermediate computations, and other data. After
completing a method, corresponding entry from the stack is removed. After completing all
method calls the stack becomes empty and that empty stack is destroyed by the JVM just
before terminating the thread. The data stored in the stack is available for the
corresponding thread and not available to the remaining threads. Hence we can say
local data is thread safe. Each entry in the stack is called Stack Frame or Activation
Record.
Stack Frame Structure
The stack frame basically consists of three parts: Local Variable Array, Operand
Stack & Frame Data. When JVM invokes a Java method, first it checks the class
data to determine the number of words (size of the local variable array and operand
stack, which are measured in words for each individual method) required by the
method in the local variables array and operand stack. It creates a stack frame of the
proper size for invoked method and pushes it onto the Java stack.
}
}
JVM
JRE
1 JDK is for development purpose whereas JRE is for running the java
programs.
2 JDK and JRE both contains JVM so that we can run our java program.
3 JVM is the heart of java programming language and provides platform
independence.
Just-in-time Compiler (JIT)
Sometimes we heard this term and being it a part of JVM it confuses us.
JIT is part of JVM that optimizes byte code to machine specific language
compilation by compiling similar byte codes at the same time, hence
reducing overall time taken for the compilation of byte code to machine
specific language.
Java Stack memory is used for the execution of a thread. They contain
method-specific values that are short-lived and references to other objects
in the heap that is getting referred from the method.
Stack memory is always referenced in LIFO (Last-In-First-Out) order.
Whenever a method is invoked, a new block is created in the stack memory
for the method to hold local primitive values and reference to other objects
in the method.
As soon as the method ends, the block becomes unused and becomes
available for the next method.
Stack memory size is very less compared to Heap memory.
Heap and Stack Memory in Java Program
Let’s understand the Heap and Stack memory usage with a simple
program.
package com.journaldev.test;
The below image shows the Stack and Heap memory with reference to the
above program and how they are being used to store primitive, Objects and
reference variables.
1 Heap memory is used by all the parts of the application whereas stack
memory is used only by one thread of execution.
2 Whenever an object is created, it’s always stored in the Heap space and
stack memory contains the reference to it. Stack memory only contains
local primitive variables and reference variables to objects in heap space.
3 Objects stored in the heap are globally accessible whereas stack memory
can’t be accessed by other threads.
4 Memory management in stack is done in LIFO manner whereas it’s more
complex in Heap memory because it’s used globally. Heap memory is
divided into Young-Generation, Old-Generation etc, more details at Java
Garbage Collection.
5 Stack memory is short-lived whereas heap memory lives from the start till
the end of application execution.
6 We can use -Xms and -Xmx JVM option to define the startup size and
maximum size of heap memory. We can use -Xss to define the stack
memory size.
7 When stack memory is full, Java runtime
throws java.lang.StackOverFlowError whereas if heap memory is full, it
throws java.lang.OutOfMemoryError: Java Heap Space error.
8 Stack memory size is very less when compared to Heap memory. Because
of simplicity in memory allocation (LIFO), stack memory is very fast when
compared to heap memory.
Static variable:
The static variable is used to refer to the common property of all objects (that is not
unique for each object), e.g., The company name of employees, college name of
students, etc. Static variable gets memory only once in the class area at the time of
class loading. Using a static variable makes your program more memory efficient (it
saves memory). Static variable belongs to the class rather than the object.
// Test.java
class Main {
// swap() doesn't swap i and j
public static void swap(Integer i, Integer j)
{
Integer temp = new Integer(i);
i = j;
j = temp;
}
public static void main(String[] args)
{
Integer i = new Integer(10);
Integer j = new Integer(20);
swap(i, j);
System.out.println("i = " + i + ", j = " + j);
}
Op:10 20
javaw.exe
This non-console version of the application launcher is used to launch java
applications usually with graphical user interfaces (GUIs). These applications have
windows with menus, buttons and other interactive elements. Essentially, Use
javaw.exe when you don’t want a command prompt window to appear either to take
further input or showing output.
java.exe
java.exe is very similar to javaw.exe. The console version of the launcher is used for
applications with text-based interfaces or that output text. Any application launched
with “java” will cause the command-line waits for the application response till it
closes.
When launched using javaw, the application launches and the command line exits
immediately and ready for next command.
Little-Endian and Big-Endian in Java
These two terms are related to the direction of bytes in a word within CPU architecture.
Computer memory is referenced by addresses that are positive integers. It is “natural” to
store numbers with the least significant byte coming before the most significant byte in the
computer memory. Sometimes computer designers prefer to use a reversed order version of
this representation.
The “natural” order, where less significant byte comes before more significant
byte in memory, is called little-endian. Many vendors like IBM, CRAY, and Sun
preferred the reverse order that, of course, is called big-endian.
For example, the 32-bit hex value 0x45679812 would be stored in memory as follows:
Address 00 01 02 03
-------------------------------
Little-endian 12 98 67 45
Big-endian 45 67 98 12
The problem comes when you must exchange data files with some program not
written in Java that uses little-endian order, most commonly a program written in C.
Some platforms use big-endian order internally (Mac, IBM 390); some uses little-
endian order (Intel).
Main.java
package app;
public class Main
{
{
System.out.println( args[i] );
}
}
Console
$ java Main 1 2 3 4
#prints
1
3. Summary
Command line args can be used to specify configuration information while launching
the application.
There is no restriction on the maximum number of arguments. We can specify any
number of arguments.
Arguments are passed as strings.
Passed arguments are retrieved as the string array in the main() method
argument.
Reference: A reference is a variable that refers to something else and can be used
as an alias for that something else.
Pointer: A pointer is a variable that stores a memory address, for the purpose of
acting as an alias to what is stored at that address.
So, a pointer is a reference, but a reference is not necessarily a pointer. Pointers are
a particular implementation of the concept of a reference, and the term tends to be
used only for languages that give you direct access to the memory address.
Let’s discuss some keypoints about pointers and references in context of C/C+
+ and Java:
C/C++ allows pointer arithmetic but Java Pointers (References) not: The term
“pointer” is strongly associated with the C/C++ concept of pointers, which are variables
which store memory addresses and can be modified arithmetically to point to arbitrary
addresses.
In Java, pointers only exist as an implementation detail for References. A copy of the
reference is copied to the stack of a called function, pointing to the same object as the
calling function and allowing you to manipulate that object. However you cannot
change the object the calling function refers to.
Java doesn’t support pointer explicitly, But java uses pointer implicitly: Java use
pointers for manipulations of references but these pointers are not available for outside
use. Any operations implicitly done by the language are actually NOT visible.
Pointers can do arithmetic, References can’t: Memory access via pointer
arithmetic is fundamentally unsafe and for safe guarding, Java has a robust security
model and disallows pointer arithmetic for this reason. Users cannot manipulate
pointers no matter what may ever is the case.
Pointing objects: In C, we can add or subtract address of a pointer to point to things.
In Java, a reference points to one thing only. You can make a variable hold a different
reference, but such c manipulations to pointers are not possible.
References are strongly typed: Type of a reference is much more strictly controlled
in Java than the type of a pointer is in C. In C you can have an int* and cast it to a
char* and just re-interpret the memory at that location. That re-interpretation doesn’t
work in Java: you can only interpret the object at the other end of the reference as
something that it already is (i.e. you can cast a Object reference to String reference
only if the object pointed to is actually a String).
Manipulation of pointers can be dangerous: On one hand, it can be good and
flexible to have control over pointers by user but it may also prove to be dangerous.
They may turn out to be big source of problems, because if used incorrectly they can
easily break assumptions that your code is built around. And it’s pretty easy to use
them incorrectly.
BASIC FAQ’S:
Is main method compulsory in Java?
The answer to this question depends on the version of java you are using. Prior to
JDK 7, the main method was not mandatory in a java program.
You could write your full code under static block and it ran normally.
The static block is first executed as soon as the class is loaded before the main(); the
method is invoked and therefore before the main() is called. main is usually declared
as static method and hence Java doesn’t need an object to call the main method.
When you will give the run command(i.e java Test in the below-mentioned program in
notepad), so compiler presumes Test is that class in which main() is there and since
compiler load, the main() method, static blocks are ready to get executed. So here, it
will run static block first and then it will see no main() is there. Therefore it will
give “exception”, as exception comes while execution. However, if we don’t want an
exception, we can terminate the program by
System.exit(0);
Here you have 2 projects proj1 and proj2. proj1 contains src and classes. In the src
directory, we will keep .java files that are source files and in classes directory, we will
keep .classes files that are files generated after compiling the project.
Myth about the file name and class name in Java
The first lecture note given during java class is “In java file name and class name
should be the same”. When the above law is violated a compiler error message will
appear as below
System.out.println("Hello world");
}
Output:
javac Trial.java
Trial.java:9: error: class Geeks is public, should be
declared in a file named Geeks.java
public class Geeks
^
1 error
But the myth can be violated in such a way to compile the above file.
class Geeks
System.out.println("Hello world");
}
Now this .class file can be executed. By the above features some more
miracles can be done. It is possible to have many classes in a java file. For
debugging purposes this approach can be used. Each class can be executed
separately to test their functionalities(only on one condition: Inheritance
concept should not be used).
But in general it is good to follow the myth.
For example:
1
/*** File name: Trial.java ***/
2
class ForGeeks
3
{
4
public static void main(String[] args){
5
System.out.println("For Geeks class");
6
}
7
}
8
9
class GeeksTest
10
{
11
public static void main(String[] args){
12
System.out.println("Geeks Test class");
13
}
14
}
15
o/p:
For Geeks class
methods are directly read from the libraries, and there is no need to create header files with
declarations. Java uses naming scheme where package and public class names must follow
directory and file names respectively. This naming scheme allows Java compiler to locate
library files.
EG:
In Java, methods and data members of a class/interface can have one of the
following four access specifiers. The access specifiers are listed according to their
restrictiveness order.
1) private
2) default (when no access specifier is specified)(package level access modifier)
3) protected
4) public
But, the classes and interfaces themselves can have only two access specifiers
when declared outside any other class.
1) public
2) default (when no access specifier is specified)
We cannot declare class/interface with private or protected access specifiers. For
example, following program fails in compilation.
//filename: Main.java
protected class Test {}
public class Main {
public static void main(String args[]) {
}
}
2. Reference Variable value: Any reference variable in Java has default value null.
public class Test
{
private static Object obj;
public static void main(String args[])
{
// it will print null;
System.out.println("Value of object obj is : " + obj);
}
}
Output:
Value of object obj is : null
3. Type of null: Unlike common misconception, null is not Object or neither a type.
It’s just a special value, which can be assigned to any reference type and you can
type cast null to any type
Examples:
// null can be assigned to String
String str = null;
instanceof operator: The java instanceof operator is used to test whether the object is an
instance of the specified type (class or subclass or interface). At run time, the result of the
This is an important property of instanceof operation which makes it useful for type casting
checks.
7.== and != The comparison and not equal to operators are allowed with null in Java.
1.oops
2.exception handling
3.multi threading
4.java collection framework
5.gui(AWT,swing,applet,javafx)
OBJECT:
What is instance class in Java?
Instance of a class in java is the object of that class itself. Instance is something
which represents the type of a particular java class.
It is a basic unit of Object Oriented Programming and represents the real life entities.
A typical Java program creates many objects, which as you know, interact by
invoking methods. An object consists of :
1 State : It is represented by attributes of an object. It also reflects the properties
of an object.
2 Behavior : It is represented by methods of an object. It also reflects the
response of an object with other objects.
3 Identity : It gives a unique name to an object and enables one object to interact
with other objects.
4 OBJECTS ARE STORED IN HEAP,ONLY WHEN NEW KEYWORD IS USED.
IMMUTABLE OBJECT:
An immutable object is an object that will not change its internal state
after creation.
Immutable objects are very useful in multithreaded applications because
they can be shared between threads without synchronization.
Immutable objects are always thread safe.
public DateContainer() {
this.date = new Date();
}
....
public DateContainer() {
this.date = new Date();
}
....
DateContainer dateContainer = new DateContainer();
System.out.println(dateContainer.getDate());
dateContainer.getDate().setTime(dateContainer.getDate().getTime() + 1000);
System.out.println(dateContainer.getDate());
// Now dateContainer date is not changed because we changed the copy,
// not the original date
....
....
2) New Instance
We can use it to create the Object of a Class. Class.forName actually loads the Class in
Java but doesn’t create any Object. To Create an Object of the Class you have to use the
new Instance Method of the Class.
public class NewInstance
{
String a = "studytonight";
public static void main(String[] args)
{
try
{
Class b = Class.forName("NewInstance");
NewInstance c = (NewInstance) b.newInstance();
System.out.println(c.a);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
}
3) Clone() method
In Java, clone() is called on an object. When a clone() method is called JVM creates
a new object and then copy all the content of the old object into it. When an object is
created using the clone() method, a constructor is not invoked. To use the clone()
method in a program the class implements the cloneable and then define the clone()
method.
Example:
// an Object.
import java.io.*;
DeserializationExample(String name)
{
this.name = name;
}
{
try
{
DeserializationExample d =
new DeserializationExample("GeeksForGeeks");
oos.writeObject(d);
oos.close();
f.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
// using Deserialization.
import java.io.*;
{
try
{
DeserializationExample d;
d = (DeserializationExample)oos.readObject();
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println(d.name);
}
Output:
GeeksForGeeks
Anonymous objects
Anonymous objects are the objects that are instantiated but are not stored in a
reference variable.
They are used for immediate method calling.
They will be destroyed after method calling.
They are widely used in different libraries. For example, in AWT libraries, they
are used to perform some action on capturing an event(eg a key press).
In example below, when a key is button(referred by the btn) is pressed, we are
simply creating anonymous object of EventHandler class for just calling handle
method.
btn.setOnAction(new EventHandler()
{
public void handle(ActionEvent event)
{
System.out.println("Hello World!");
}
});
How to swap or exchange objects in Java?
1.when the class attributes are known:
class Car
{
int no;
Car(int no) { this.no = no; }
}
// A class that uses Car objects
class Main
{
// To swap c1 and c2
public static void swap(Car c1, Car c2)
{
int temp = c1.no;
c1.no = c2.no;
c2.no = temp;
}
// Driver method
public static void main(String[] args)
{
Car c1 = new Car(1);
Car c2 = new Car(2);
swap(c1, c2);
System.out.println("c1.no = " + c1.no);
System.out.println("c2.no = " + c2.no);
}
}
o/p:
c1.no = 2
c2.no = 1
class Sample
// Class Declaration
class Student
// Class Declaration
class Test
{
}
For Compiling:
javac Test.java
After compilation there will be 3 class files in corresponding folder named as:
Sample.class
Student.class
Test.class
A single class file structure contains attributes that describe a class file.
Java Class
A class is declared using class keyword. A class contain both data and code that
operate on that data. The data or variables defined within a class are
called instance variables and the code that operates on this data is known
as methods. Thus, the instance variables and methods are known as class
members. class is also known as a user defined datatype.
A class and an object can be related as follows: Consider an ice tray(like of cube
shape) as a class. Then ice cubes can be considered as the objects which is a
blueprint of its class i.e of ice tray.
It must have the class keyword, and class must be followed by a legal identifier.
It may optionally extend one parent class. By default, it will extend java.lang.Object.
The class's variables and methods are declared within a set of curly braces {}.
Each .java source file may contain only one public class. A source file may contain
Finally, the source file name must match the public class name and it must have a
.java suffix.
A simple class example
Suppose, Student is a class and student's name, roll number, age will be its
property. Lets see this in Java syntax
class Student.
{
String name;
int rollno;
int age;
}
When a reference is made to a particular student with its property then it becomes
an object, physical existence of Student class.
Student std=new Student();
why private methods are not declared always as final and do the compiler treats
private methods as final?
In java, if a method is private or it is final then it can not be overridden by the
subclasses. So if a method is declared as private then it is unnecessary to make it
final.
Yes, the compiler treats private methods as final because the compiler does not allow a private
method to override and it also safe the subclasses for overriding final method.
1 Question : Can we have our class name as one of the predefined class name in our
program?
Answer : Yes we can have it. Below is example of using Number as user defined
class
{
System.out.println("It works");
}
Output:
It works
2 Using String as User Defined Class:
{
}
However, in this case you will get run-time error like this :
Error: Main method not found in class String, please define
the main method as:
public static void main(String[] args)
Explanation : This is because Main thread is looking for main method() with
predefined String class array argument. But here, it got main method() with
user defined String class. Whenever Main thread will see a class name, it tries
to search that class scope by scope. First it will see in your program, then in
your package.If not found, then JVM follows delegation hierarchy principle to
load that class.Hence you will get run-time error.
To run above program, we can also provide full path of String class,
i.e. java.lang.String .
{
}
Output:
I got confused
Using predefined class name as User defined Variable name
Question : Can we have a variable name as one of the predefined class name in
our program?
Answer : Yes we can have it.
{
System.out.println(Number);
System.out.println(Number.Number);
}
Output:
Number@15db9742
20
Clone() Method
In Java, cloning an object means to create a copy of an object. The copied object
has a new instance object and all initialized field with the contents. An assignment
operator is used for creating a copy of the reference variable.
Example:
class Add
{
int x, y;
Add()
Java INNER CLASS:
Java inner class or nested class is a class which is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
Additionally, it can access all the members of outer class including private data members and
methods.
1 class Java_Outer_class{
2 //code
3 class Java_Inner_class{
4 //code
5 }
6 }
1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
1 class TestMemberOuter1{
2 private int data=30;
3 class Inner{
4 void msg(){System.out.println("data is "+data);}
5 }
6 public static void main(String args[]){
7 TestMemberOuter1 obj=new TestMemberOuter1();
8 TestMemberOuter1.Inner in=obj.new Inner();
9 in.msg();
10 }
11 }
12 data is 30
The java compiler creates two class files in case of inner class. The class file name of
inner class is "Outer$Inner". If you want to instantiate inner class, you must have to
create the instance of outer class. In such case, instance of inner class is created inside
the instance of outer class.
interface Eatable{
3 void eat();
4 }
5 class TestAnnonymousInner1{
6 public static void main(String args[]){
7 Eatable e=new Eatable(){
8 public void eat(){System.out.println("nice fruits");}
9 };
10 e.eat();
11 }
12 }
13 nice fruits
1 abstract class Person{
2 abstract void eat();
3 }
4 class TestAnonymousInner{
5 public static void main(String args[]){
6 Person p=new Person(){
7 void eat(){System.out.println("nice fruits");}
8 };
9 p.eat();
10 }
11 }
Nice fruits
1 class localInner2{
2 private int data=30;//instance variable
3 void display(){
4 int value=50;//local variable must be final till jdk 1.7 only
5 class Local{
6 void msg(){System.out.println(value);}
7 }
8 Local l=new Local();
9 l.msg();
10 }
11 public static void main(String args[]){
12 localInner2 obj=new localInner2();
13 obj.display();
14 }
15 }
Test it Now
Output:
50
12 In this example, you need to create the instance of static nested class because it
has instance method msg(). But you don't need to create the object of Outer
class because nested class is static and static properties, methods or classes can
be accessed without object.
1 class TestOuter2{
2 static int data=30;
3 static class Inner{
4 static void msg(){System.out.println("data is "+data);}
5 }
6 public static void main(String args[]){
7 TestOuter2.Inner.msg();//no need to create the instance of static nested class
8 }
9 }
10 Output:
11 data is 30
o Nested interface must be public if it is declared inside the interface but it can
have any access modifier if declared within the class.
o Nested interfaces are declared static implicitely.
o interface Showable{
o void show();
o interface Message{
o void msg();
o }
o }
o class TestNestedInterface1 implements Showable.Message{
o public void msg(){System.out.println("Hello nested interface");}
o public static void main(String args[]){
o Showable.Message message=new TestNestedInterface1();//upcasting here
o message.msg();
o }
o }
o Output:hello nested interface
As you can see in the above example, we are acessing the Message interface by its outer interface Sh
cannot be accessed directly. It is just like almirah inside the room, we cannot access the almirah dire
enter the room first. In collection frameword, sun microsystem has provided a nested interface Entry
subinterface of Map i.e. accessed by Map.Entry.
Example of nested interface which is declared within the
class
Let's see how can we define an interface inside the class and how can we access it.
1 class A{
2 interface Message{
3 void msg();
4 }
5 }
6
7 class TestNestedInterface2 implements A.Message{
8 public void msg(){System.out.println("Hello nested interface");}
9
10 public static void main(String args[]){
11 A.Message message=new TestNestedInterface2();//upcasting here
12 message.msg();
13 }
14 }
Can we define a class inside the interface?
Yes, If we define a class inside the interface, java compiler creates a static nested class.
Let's see how can we define a class within the interface:
1 interface M{
2 class A{}
3 }
Java MAIN METHOD:
A second way to answer this is another question, why not public? All methods and
constructors in java have some access modifier. main() method also need one. There is no
reason why it should not be public, and be any other modifier(default/protected/private).
The only thing application would like to communicate to the invoking process is
normal or abnormal termination. This is already possible using System.exit(int). A
non-zero value means abnormal termination otherwise everything was fine.
A Java program can run without the main method. You need a static block for that,
and You need to put your executable code in that static block and execute it. The
sequence goes something like this:
However, if you are planning to run your program directly from the command-line
without using static block, and with the use of JVM, then your program must be
required to have the main() method. This is because the Java Virtual Machine keeps
looking for the main().
DATA TYPES:
Java has a wrapper class named Integer, which defines two constants to represent maximum and
minimum values for the int data type, Integer.MAX_VALUE and Integer.MIN_VALUE. It is object
representation of an int value.
int max = Integer.MAX_VALUE; // Assigns maximum int value to max
An integer literal of type long always ends with ‘L’ (or lowercase ‘l’).
long num1 = 0L;
If you want to assign the value of a long variable to an int variable, you have to explicitly
mention this fact in your code, so that Java makes sure you are aware that there may be data
overflow. You do this using “cast” in Java, like so:
long num1 = (int) num2; // Now it is fine because of the "(int)" cast
By writing (int)num2, you are instructing Java to treat the value stored in num2 as an int. At runtime,
Java will use only the 32 least significant bits of num2, and assign the value stored in those 32 bits
to num1. If num2 has a value that is outside the range of the int data type, you would not get the sam
value in num1 and it will result in data loss.
Java has a class Long (note the upper case L in Long), which defines two constants to represent
maximum and minimum values of long data type, Long.MAX_VALUE and Long.MIN_VALUE.
long max = Long.MAX_VALUE;
byte b1 = 125;
byte b2 = -11;
Java has a class Byte (note the upper case B in Byte), which defines two constants to
represent maximum and minimum values of the byte data
type, Byte.MAX_VALUE and Byte.MIN_VALUE.
byte max = Byte.MAX_VALUE;
The short data type is a 16-bit signed Java primitive integer data type. Its range is
-32768 to 32767 (or -215 to 215 – 1).
Unlike int and long literals, there is no short literal.
However, you can assign any int literal that falls in the range of short (-32768 to 32767)
to a short variable.
short s1 = 12905; // ok
short s2 = -11890; // ok
Short Wrapper Class
Java has a class called Short (note the upper case S in Short), which defines two
constants to represent maximum and minimum values of short data
type, Short.MAX_VALUE and Short.MIN_VALUE.
short max = Short.MAX_VALUE;
char c1 = 'A';
char c2 = 'L';
char c3 = '5';
char c4 = '/';
‘\n’ A linefeed
‘\b’ A backspace
‘\t’ A tab
‘\\’ A backslash
These are only eight character escape sequences in Java. You cannot define your own
character escape sequences.
The float data type uses 32 bits to store a floating-point number in the IEEE 754
standard format (single-precision floating-point number). It can represent a real
number as small as 1.4 x 10-45 and as big as 3.4 x 1038 (approx.) in magnitude. The
range includes only the magnitude. It could be positive or negative.
All real numbers that end with ‘f’ or ‘F’ are called float literals.
float f1 = 8F;
float f2 = 8.F;
float f3 = 8.0F;
The double data type uses 64 bits to store a floating-point number in the ‘IEEE 754 standard format
A floating-point number represented in 64 bits according to IEEE 754 standard is also known as
a double-precision floating-point number.
All real numbers are called double literals. A double literal may optionally end with ‘d’ or ‘D’, for
example, 19.27d. However, the suffix d or D is optional in double literals. That is, both 19.27 and
19.27d represent the same double literal.
double d1 = 8D
double d2 = 8.;
double d3 = 8.0;
double d4 = 8.D;
WRAPPER CLASS:
A wrapper class wraps (encloses) around a data type and gives it an object
appearance. Wherever, the data type is required as an object, this object can be used.
Wrapper classes include methods to unwrap the object and give back the data type.
double Double
float Float
long Long
int Integer
short Short
byte Byte
char Character
boolean Boolean
When two methods wants to refer to the same instance of an primitive type, then pass
wrapper class as method argument.
Generics in Java works only with object and does not support primitive types.
Collections in Java deal only with objects; to store a primitive type in one of these
classes, you need to wrap the primitive type in a class.
When you want to refer null from data type, the you need object. Primitives cannot
have null as value.
There are two ways for converting a primitive type into an object of corresponding
wrapper class –
1 using constrcutors
2 using static factory methods such as valueOf() (except Character)
// 1. using constructor
Integer object = new Integer(10);
// 2. using static factory method
Converting from wrapper to primitive type is simple. We can use the corresponding
methods to get the primitive type. e.g. intValue(), doubleValue(), shortValue() etc.
Integer object = new Integer(10);
int val = object.intValue(); //wrapper to primitive
4. AUTOBOXING(REF TO 2)
integerList is a list of Integer objects, not a list of primitive type int values. Compiler
automatically creates an Integer object from i and adds the object to integerList.
Thus, the previous code turn into the following at runtime:
List<Integer> integerList = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
{
integerList.add(Integer.valueOf(i)); //autoboxing
}
5. UNBOXING(REF TO 3)
In above example, the remainder (%) and unary plus (+=) operators does not apply on
Integer objects. The compiler automatically converts an Integer to an int at runtime
by invoking the intValue() method.
STRING :
What is String Pool?
String pool is the space reserved in the heap memory that can be used to store the
strings. The main advantage of using the String pool is whenever we create a string
literal; the JVM checks the "string constant pool" first. If the string already exists in the
pool, a reference to the pooled instance is returned. If the string doesn't exist in the
pool, a new string instance is created and placed in the pool. Therefore, it saves the
memory by avoiding the duplicacy.
The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.
String literal
1 String literals are stored in String pool, a special memory area created by
JVM. There can be only one instance of one String. Any second String with
same character sequence will have the reference of first string stored in string
pool. It makes efficient to work with Strings and saves lots of physical memory
in runtime.
String object
At times, we may wish to create separate instance for each separate string in
memory. We can create one string object per string value using new keyword.
String objects created using new keyword – are stored in heap memory.
In above example, there will be 3 separate instances of String with same value in
heap memory.
1 String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is returned. If the
string doesn't exist in the pool, a new string instance is created and placed in the pool.
String objects are stored in a special memory area known as the string constant
pool For example:
1 String s1="Welcome";
2 String s2="Welcome";//It doesn't create a new instance
2) By new keyword
1 String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory,
and the literal "Welcome" will be placed in the constant string pool. The variable s will
refer to the object in a heap (non-pool).
Only one object will be created using the above code because strings in Java are
immutable.
More details.
More details.
The return value is 0 if the argument string is equal to this string; a value less
than 0 if this string is lexicographically less than the string argument; and a
value greater than 0 if this string is lexicographically greater than the string
argument.
String blogName = "howtodoinjava.com";
6 boolean startsWith(String prefix, int offset) – Checks whether the String is having
the specified prefix or not – starting from the specified offset index.
8 boolean endsWith(String suffix) – Checks whether the string ends with the specified
suffix.
10 int indexOf(int ch) – Returns the index of first occurrence of the specified character
argument in the string.
14 int lastIndexOf(int ch) – Returns the last occurrence of the character 'ch' in the
string.
18 String substring(int beginIndex) – Returns the substring of the string. The substring
starts with the character at the specified index.
20 String concat(String str) – Concatenates the specified string argument at the end of
the string.
21 String replace(char oldChar, char newChar) – Returns the new updated string after
changing all the occurrences of oldChar with the newChar arguments.
22 String replace(String target, String replacement) – Returns the new updated string
after changing all the occurrences of target with the replacement argument.
28 String toUpperCase(Locale locale) – Converts the string to upper case string using
the rules defined by specified locale.
public class InternExample{
public static void main(String args[]){
String s1=new String("hello");
String s2="hello";
String s3=s1.intern();//returns string from pool, now it will be same as s2
System.out.println(s1==s2);//false because reference variables are pointing to different
instance
System.out.println(s2==s3);//true because reference variables are pointing to same inst
ance
}}
Op:
false
true
33 boolean isEmpty() – Returns true if the given string has 0 length else returns false.
"".isEmpty(); //true
34 static String join() – Joins the given strings using the specified delimiter and returns
the concatenated Java String literal.
String name="sonoo";
System.out.println(sf1);
System.out.println(sf2);
System.out.println(sf3);
}}
name is sonoo
value is 32.334340
value is 32.334340000000
36 String trim() – Removes leading and trailing white spaces from the Java string.
System.out.println(s1.trim()+"javatpoint");//with trim()
}}
op
hello stringjavatpoint
eg2:
System.out.println(s1.length());
String tr = s1.trim();
System.out.println(tr.length());
22
17
HASHCODE:
It provides memory identification number which is gn by JVM with out checking the content.
EG 1:
Class Test{
Int sid;
String str;
System.out.print(“t ”+t);
E g 2:
Class Test{
Int sid;
String str;
This.sid=sid;
This.str=name;
//@override
System.out.print(“t1 ”+t1.hashCode());
//by calling the hashcode method the JVM simply generates a identification number so even
though the values in the object are same it generates different id number. op: t 1233434
IN ORDER TO AVOID ABOVE CONFUSION : we want the JVM to check the content and provide the id
num.
Class Test{
Int sid;
String str;
This.sid=sid;
This.str=name;
//@override
Return sid+str.hashCode();
//r a m
// 2 1 0(powers)
//112771
//override equals
Else{
Return false;
System.out.print(“t ”+t);
System.out.print(“t1 ”+t1.hashCode());//112771
System.out.print(“t2 ”+t2.hashCode());//112771
// In this we get the output as FALSE because the internal JVM has the method
Syste.identifyHashCode(t1) it generates different numbers so it display false.
System.out.print(“whether the two values are same in the two objects”+t1.equals(t2));// TRUE
String Conversion
1.string to int: Integer.parseInt(string) and Integer.valueOf(string)
Class c=Class.forName("java.lang.String");
12.int to long
i)long=int and Long =Long.valueof(int)
13.long to int
13.BINARY TO DECIMAL:
1 String binaryString="1010";
2 int decimal=Integer.parseInt(binaryString,2);
parseInt(int i) − This returns an integer, given a string representation of decimal, binary,
octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input.
OR
1 int temp = binary%10;
2 decimal += temp*Math.pow(2, n);
3 binary = binary/10;
4 n++;
14.decimal to binary:
Integer.toBinaryString(int)
Or
1 public static void toBinary(int decimal){
2 int binary[] = new int[40];
3 int index = 0;
4 while(decimal > 0){
5 binary[index++] = decimal%2;
6 decimal = decimal/2;
7 }
8 for(int i = index-1;i >= 0;i--){
9 System.out.print(binary[i]);
10 }
11 System.out.println();//new line
12 }
15.HEX TO DECIMAL:
Integer.parseInt(hex,16);
OR
1 public static int getDecimal(String hex){
2 String digits = "0123456789ABCDEF";
3 hex = hex.toUpperCase();
4 int val = 0;
5 for (int i = 0; i < hex.length(); i++)
6 {
7 char c = hex.charAt(i);
8 int d = digits.indexOf(c);
9 val = 16*val + d;
10 }
11 return val;
12 }
16.DECIMAL TO HEX:
Integer.toHexString(10)
OR
1 public static String toHex(int decimal){
2 int rem;
3 String hex="";
4 char hexchars[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
5 while(decimal>0)
6 {
7 rem=decimal%16;
8 hex=hexchars[rem]+hex;
9 decimal=decimal/16;
10 }
11 return hex;
12 }
17.OCTAL TO DECIMAL:
Integer.parseInt(octalString,8);
OR
1 public static int getDecimal(int octal){
2 //Declaring variable to store decimal number
3 int decimal = 0;
4 //Declaring variable to use in power
5 int n = 0;
6 //writing logic
7 while(true){
8 if(octal == 0){
9 break;
10 } else {
11 int temp = octal%10;
12 decimal += temp*Math.pow(8, n);
13 octal = octal/10;
14 n++;
15 }
16 }
17 return decimal;
18 }
18.DECIMAL TO OCTAL
(Integer.toOctalString(8)
OR
1 public static String toOctal(int decimal){
2 int rem; //declaring variable to store remainder
3 String octal=""; //declareing variable to store octal
4 //declaring array of octal numbers
5 char octalchars[]={'0','1','2','3','4','5','6','7'};
6 //writing logic of decimal to octal conversion
7 while(decimal>0)
8 {
9 rem=decimal%8;
10 octal=octalchars[rem]+octal;
11 decimal=decimal/8;
12 }
13 return octal;
14 }
TO STUDY ABOUT THE STRNIG METHODS AND THE VARIOUS CONVERISONS VISIT THIS WEBSITE:
https://howtodoinjava.com/java-string/
STRING BUFFER(SYNCHRONIZED):
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer
class in java is same as String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it
is safe and will result in an order.
1.
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
2.
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
3.
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
4.
sb.delete(1,3);
System.out.println(sb);//prints Hlo
5.
sb.reverse();
System.out.println(sb);//prints olleH
6.
The capacity() method of StringBuffer class returns the current capacity of the buffer.
The default capacity of the buffer is 16. If the number of character increases from its
current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
7.
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
StringBuffer HashCode Test
System.out.println("Hashcode test of StringBuffer:");
System.out.println(sb.hashCode());
sb.append("tpoint");
System.out.println(sb.hashCode());
118352462
118352462
STRING TOKENIZER:
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc.
Constructor Description
RULES:
There are many immutable classes like String, Boolean, Byte, Short, Integer, Long,
Float, Double etc. In short, all the wrapper classes and String class is immutable.
1 public final class Employee{
2 final String pancardNumber;
3
4 public Employee(String pancardNumber){
5 this.pancardNumber=pancardNumber;
6 }
7
8 public String getPancardNumber(){
9 return pancardNumber;
10 }
11
12 }
o The instance variable of the class is final i.e. we cannot change the value of it
after creating an object.
o The class is final so we cannot create the subclass.
o There is no setter methods i.e. we have no option to change the value of the
instance variable.
Apart from your written classes, JDK itself has lots of immutable classes. Given is such
a list of immutable classes in Java.
1 String
2 Wrapper classes such as Integer, Long, Double etc.
3 Immutable collection classes such as Collections.singletonMap() etc.
4 java.lang.StackTraceElement
5 Java enums (ideally they should be)
6 java.util.Locale
7 java.util.UUID
1. Class
In Java, a Class is a collection of objects. It is a logical entity. Class is also known as
blueprint for which an individual object is created. Class does not occupy any space.
Following are the components which a class includes:
i. Modifiers
Modifiers are used to define the scope of the class. A class can be public, private or
protected.
ii. Class name
The name of the class should begin with a letter. The name of the class and the
program is always the same.
iii. Superclass(if any)
Superclass is the Parent class. If any child class inherits the superclass then extends
keyword is used.
iv. Body
The body of the class is surrounded by the braces {}.
2. Object
In Java, An Object is an entity which has state and behaviour. It is an instance of a
class. It is a physical entity. An object contains an address which takes memory
space. Objects do not contain details of data or code. Following are the things which
an object contains:
i. State
It is used to represent the attributes of the object
ii. Behaviour
It is used to represent the methods of the object.
iii. Identity
It is the unique name of an object.
3. Polymorphism
If a task can be performed in many different ways then it is known as polymorphism.
To achieve polymorphism in java we use method overloading(Static
polymorphism or early binding) and method overriding(Dynamic
polymorphism or late binding).
Compile time polymorphism(method overloading)
call to a method is done at compile time so it is called compile time
polymorphism
Eg:static polymorphism or method overloading(same name but different
parameters)
4.ABSTRACTION:
Partially completed methods and class.
Abstraction enables you to focus on what the object does instead of how it
does it. Abstraction lets you focus on what the object does instead of how it does it.
o Abstract Class
o Interface
Abstraction means to hide internal details and showing only important functionalities.
To achieve abstraction, abstract class and interface are used. And 100% abstraction
is achieved from the interface.
Abstract classes and Abstract methods :
1 An abstract class is a class that is declared with abstract keyword.
2 An abstract method is a method that is declared without an implementation.
3 An abstract class may or may not have all abstract methods. Some of them can be
concrete methods
4 A method defined abstract must always be redefined in the subclass,thus
making overriding compulsory OR either make subclass itself abstract.
5 Any class that contains one or more abstract methods must also be declared with
abstract keyword.
6 There can be no object of an abstract class.That is, an abstract class can not be
directly instantiated with the new operator.bcz of the abstract methods (partial
methods,closed with the terminator “ ; ” )
7 An abstract class can have parametrized constructors and default constructor is
always present in an abstract class.
8 Abstract class can contain ZERO abstract methods such as in web app side,httpservlet
is abstract and has no abstract methods.
Encapsulation vs Data Abstraction
1 Encapsulation is data hiding(information hiding) while Abstraction is detail
hiding(implementation hiding).
2 While encapsulation groups together data and methods that act upon the data, data
abstraction deals with exposing the interface to the user and hiding the details of
implementation.
Advantages of Abstraction
1 It reduces the complexity of viewing the things.
2 Avoids code duplication and increases reusability.
3 Helps to increase security of an application or program as only important details are
provided to the user.
Can we create object for abstract class if not?
An abstract class is a special type of class which cannot be initialized and it only
acts as a base class for other classes. An object of abstract class cannot
be created because this is how the abstract class is defined. We can create sub-
types of it, but not of that type itself. The CLI will not let you do this.
Can abstract class have Constructor in Java
Yes, an abstract class can have a constructor in Java. You can either explicitly provide a
constructor to abstract class or if you don't, the compiler will add default constructor of no
argument in abstract class. This is true for all classes and it also applies to an abstract class.
For those who want to recall what is an abstract class in Java, it's a class which can not be
instantiated with new() operator or any other ways. In order to use an abstract class in
Java, You need to extend it and provide a concrete class. Abstract class is commonly used to
define a base class for a type hierarchy with default implementation, which is applicable to all
child classes.
Read more: https://www.java67.com/2013/02/can-abstract-class-have-constructor-in-
java.html#ixzz6M3G51M2o
EG for abstraction:
// Abstract class
// Regular method
System.out.println("Zzz");
class MyMainClass {
myPig.sleep();
In this example we declared ANIMAL SOUND as abstract bcz when the method
is called then the function is executed,but don’t want the internal operation.
For better understanding it is like atm pin typing and the backend process
takes place and we receive the amount.
MAIN CLASS PROVIDING ABSTRACT METHOD DEFINITION:
1 abstract class Calculate
2 {
3 abstract int multiply(int a, int b);
4 }
5
6 public class Main
7 {
8 public static void main(String[] args)
9 {
10 int result = new Calculate()
11 {
12 @Override
13 int multiply(int a, int b)
14 {
15 return a*b;
16 }
17 }.multiply(12,32);
18 System.out.println("result = "+result);
19 }
20 }
Yes, the program is written correctly. The Main class provides the definition of abstract
method multiply declared in abstract class Calculation. The output of the program will
be:
Output
384
Purpose of Inheritance
1 It promotes the code reusabilty i.e the same methods and variables which are
Disadvantages of Inheritance
Main disadvantage of using inheritance is that the two classes (parent and child
class) gets tightly coupled.
This means that if we change code of parent class, it will affect to all the child
classes which is inheriting/deriving the parent class, and hence, it cannot be
independent of each other.
System.out.println("Parent method");
}
System.out.println("Child method");
Child method
Parent method
Types of Inheritance
1 Single Inheritance
2 Multilevel Inheritance
3 Heirarchical Inheritance
To remove ambiguity.
super keyword
In Java, super keyword is used to refer to immediate parent class of a child class. In
other words super keyword is used by a subclass whenever it need to refer to its
immediate super class.
Example of Child class referring Parent class property
using super keyword
In this examle we will only focus on accessing the parent class property or variables.
class Parent
String name;
String name;
name = "Child";
String name;
name = "Parent";
System.out.println(name);
String name;
name = "Child";
System.out.println(name);
cobj.details();
}
Parent
Child
String name;
public Parent(String n)
name = n;
String name;
this.name = n2;
}
public static void main(String[] args)
cobj.details();
Note: When calling the parent class constructor from the child class using super
keyword, super keyword should always be the first line in the method/constructor of
the child class.
The above code is legal syntax because of IS-A relationship is there between class
A and Class B.
Default methods enable you to add new functionality to the interfaces and ensure
backward compatibility for existing classes which implement that interface.
As their name implies, default methods in interfaces are methods which will
be invoked by default – if not overridden in implementing classes. Let’s
understand with an example.
Moveable interface is some existing interface and wants to add a new
method moveFast(). If it adds moveFast() method using old technique, then all
classes implemeting Moveable will also be changed. So, let’s add moveFast() method
as default method.
Moveable.java
public interface Moveable
{
default void moveFast()
{
System.out.println("I am moving fast, buddy !!");
}
}
Animal.java
public class Animal implements Moveable
{
public static void main(String[] args)
{
Animal tiger = new Animal();
//Call default method using instance reference
tiger.moveFast();
}
}
6. Encapsulation(data hiding)
Encapsulation simply means binding object state(fields) and
behaviour(methods) together. If you are creating class, you are doing
encapsulation.
Encapsulation means wrapping up code into a single unit. The best example of
encapsulation is the Java Class and also the Java bean. Java bean is totally
encapsulated class. Encapsulation is also known as data hiding because here the
data is hidden in a class.
Java virtual Machine(JVM) is a virtual Machine that provides runtime environment to execute
java byte code. The JVM doesn't understand Java typo, that's why you compile
your *.java files to obtain *.class files that contain the bytecodes understandable by
the JVM.
class EncapsulationDemo{
private int ssn;
private String empName;
private int empAge;
7.INTERFACE:
ANY SERVICE REQUIREMENT SPECIFICATION(SRS)
interface are implicitly(DEFAULT) public static final and the methods in an
interface are by default public.
Interface does not have constructor.
2) Java does not support "multiple inheritance" (a class can only inherit from
one superclass). However, it can be achieved with interfaces, because the
class can implement multiple interfaces. Note: To implement multiple
interfaces, separate them with a comma (see example below).
So if you use multiple inheritance in abstract class A having method ‘a’ with one
definition and abstract Class B having method ‘a’ with another definition and Class
c inherits A and B then while choosing the method ‘a’ of both A and B, JVM will get
confused, this will cause ambiguity.
Example
// interface
interface Animal {
Example
// Interface
interface Animal {
}
// Pig "implements" the Animal interface
System.out.println("Zzz");
class MyMainClass {
myPig.animalSound();
myPig.sleep();
Run example »
Multiple Interfaces
To implement multiple interfaces, separate them with a comma:
Example
interface FirstInterface {
public void myMethod(); // interface method
interface SecondInterface {
System.out.println("Some text..");
class MyMainClass {
myObj.myMethod();
myObj.myOtherMethod();
There is only one scenario when you implement an interface and do not override the
method i.e. declare the implementing class itself abstract.
Abstract class
public abstract class TestMain implements TestInterface
{
//No need to override implement Me
}
Otherwise, you must implement the method implementMe() in you class without any
other exception.
Non-abstract class
public class TestMain implements TestInterface
{
@Override
public void implementMe() {
// TODO Auto-generated method stub
}
}
8.INTERFACE VS ABSTRACT:
Abstract classes and interfaces are the two main building blocks of most Java APIs.
Next, a question may come if we have abstract methods and main class both, we may
try to call the abstract method from main(). But this attempt will fail,
as main() method is always static and abstract methods can never be static, so you
can never access any non-static method inside the static method.
Now, only one big difference remains that you cannot extend multiple classes whereas
you can implement multiple interfaces.
1. extends keyword
In Java, we can inherit the fields and methods of a class by extending it
using extends keyword. Please note that in Java, a class can extend maximum one
class only.
So essentially ArrayList class has methods and behaviors of both it’s parent classes
AbstractList and AbstractCollection.
ArrayList.java
public class ArrayList<E> extends AbstractList<E>
//code
Let’s create something from scratch to better understand how Java inheritance
using extends keyword works. I have created two classes
– ParentClass and ChildClass, where ChildClass extends ParentClass.
ParentClass.java
public class ParentClass {
return this.dataVal;
}
}
ChildClass.java
public class ChildClass extends ParentClass
I have not added any field or method to ChildClass just to show that even if we
don’t add anything to it, it still has behavior of it’s parent class.
Main.java
public class Main
{
System.out.println( child.dataVal );
System.out.println( child.getDataVal() );
}
Program output.
Console
100
100
2. implements keyword
Interfaces are way to enforce a contract in Java. They force the implementing class to
provide a certain behavior. To implement an interface, class must use implements
keyword.
In Java, we can implement more than one interfaces. In this case, class must
implement all the methods from all the interfaces. (or declare itself abstract).
Look at the ArrayList class declaration one more time. It implements 4 interfaces
i.e. List, RandomAccess, Cloneable and Serializable. It has implemented all the
methods in given interfaces.
Similar to previous example, lets create something basic to understand how interface
implementations look like. I have created two interfaces Movable and Swimmable. Both
interfaces define one method.
Movable.java
public interface Movable {
Swimmable.java
public interface Swimmable
Human.java
public class Human implements Movable, Swimmable
@Override
System.out.println("I am swimming");
}
@Override
System.out.println("I am moving");
}
}
Now we will test the human class and it’s enforced behavior.
Main.java
public class Main
{
obj.move();
obj.swim();
}
Program output.
Console
I am moving
I am swimming
Clearly, Human class implemented both interfaces and defined their behavior. That’s
whole purpose of interfaces in Java.
1 extends keyword is used to inherit a class; while implements keyword is used to inherit
the interfaces.
2 A class can extend only one class; but can implement any number of interfaces.
3 A subclass that extends a superclass may override some of the methods from
superclass. A class must implement all the methods from interfaces.
It returns –
true – if variable is instance of specified class, it’s parent class or implement specified
interface or it’s parent interface
false – if variable is not instance of the class or implement the interface; or variable is
null
10.(HAS A REALTION)Association,
Composition and Aggregation in Java
In UML diagrams, relationships are used to link several things. It is a connection
between structural, behavioral, or grouping things. Following are the standard UML
relationships enlisted below:
o Association
o Dependency
o Generalization
o Realization
Association
Association relationship is a structural relationship in which different objects are
linked within the system. It exhibits a binary relationship between the objects
representing an activity. It depicts the relationship between objects, such as a
teacher, can be associated with multiple teachers.
Example:
The composition and aggregation are two subsets of association. In both of the cases,
the object of one class is owned by the object of another class; the only difference is
that in composition, the child does not exist independently of its parent, whereas in
aggregation, the child is not dependent on its parent i.e., standalone. An aggregation
is a special form of association, and composition is the special form of aggregation.
Aggregation
Aggregation is a subset of association, is a collection of different things. It represents
has a relationship. It is more specific than an association. It describes a part-whole or
part-of relationship. It is a binary association, i.e., it only involves two classes. It is a
kind of relationship in which the child is independent of its parent.
For example:
Here we are considering a car and a wheel example. A car cannot move without a wheel.
But the wheel can be independently used with the bike, scooter, cycle, or any other
vehicle. The wheel object can exist without the car object, which proves to be an
aggregation relationship.
Composition
The composition is a part of aggregation, and it portrays the whole-part relationship. It
depicts dependency between a composite (parent) and its parts (children), which means
that if the composite is discarded, so will its parts get deleted. It exists between similar
objects.
As you can see from the example given below, the composition association relationship
connects the Person class with Brain class, Heart class, and Legs class. If the person is
destroyed, the brain, heart, and legs will also get discarded.
Method Overriding & Overloading
in Java
call-by-value and call-by-reference
There are two ways to pass an argument to a method
1 call-by-value : In this approach copy of an argument value is pass to a method.
Changes made to the argument value inside the method will have no effect on the
arguments.
changes made inside the method will affect the agrument value.
Example of call-by-value
public class Test
{
public void callByValue(int x)
{
x=100;
}
public static void main(String[] args)
{
int x=50;
Test t = new Test();
t.callByValue(x); //function call
System.out.println(x);
}
50
Can we modify the throws clause of the superclass method while overriding it
in the subclass?
When a class extends a super class it can also override methods of the super
class. ... If superclass method has not declared any exception using throws
clause then subclass overridden method can't declare any checked exception
though it can declare unchecked exception with the throws clause.
Yes, we can modify the throws clause of the superclass method while overriding it in the
subclass. However, there are some rules which are to be followed while overriding in
case of exception handling.
Java virtual:
In Java there is no keyword names “virtual“. Definition of Virtual from wiki: In
object-oriented programming, a virtual function or virtual method is a function or
method whose behaviour can be overridden within an inheriting class by a function
with the same signature to provide the polymorphic behavior.
In Java, methods are virtual by default and can be made non-virtual by
using final keyword. For example, in the following java program, show() is by default
virtual and the program prints “Derived::show() called”
class Base {
// virtual by default
public void show() {
System.out.println("Base::show() called");
}
}
class Derived extends Base {
public void show() {
System.out.println("Derived::show() called"); <-output
}
}
public class Main {
public static void main(String[] args) {
Base b = new Derived();//UPCASTING
b.show();
}
}
Unlike C++ non-virtual behavior, if we add final before definition of show() in Base ,
then the above program fails in compilation.
Explanation
The method of Base class, i.e., baseMethod() is overridden in Derived class. In Test
class, the reference variable b (of type Base class) refers to the instance of the Derived
class. Here, Runtime polymorphism is achieved between class Base and Derived. At
compile time, the presence of method baseMethod checked in Base class, If it presence
then the program compiled otherwise the compiler error will be shown. In this case,
baseMethod is present in Base class; therefore, it is compiled successfully. However, at
runtime, It checks whether the baseMethod has been overridden by Derived class, if so
then the Derived class method is called otherwise Base class method is called. In this
case, the Derived class overrides the baseMethod; therefore, the Derived class method is
called.
Animal myType()
1 class A{
2 A get(){return this;}
3 }
4
5 class B1 extends A{
6 B1 get(){return this;}
7 void message(){System.out.println("welcome to covariant return type");}
8
9 public static void main(String args[]){
10 new B1().get().message();
11 }
12 }
Output: welcome to covariant return type
class Calculating {
}
}
int a = calc.AddNum(24,36);
double b = calc.AddNum(22.50,17.35);
System.out.println(a);//output 60
System.out.println(b);//output 39.85
Eg:another eg of overriding
class Animal{
System.out.println("*silence*");
System.out.println("Wouf!");
}}
//Outputs Wouf!
System.out.println( "Meov!");
}}
//Outputs Meov!
bobby.making_sound();//outout wouf!
lemis.making_sound();//output meov!
prototype.making_sound();//silence
Parameter must be different and name must Both name and parameter must be same.
be same.
Access specifier can be changed. Access specifier cannot be more restrictive than original
method(can be less restrictive).
It should have methods with the same name It should have methods with same name and signature.
but a different signature.
It can not have the same return type. It should always have the same return type.
It can be performed using the static method It can not be performed using the static method
Access modifiers and Non-access modifiers Access modifiers and Non-access modifiers can not be
can be changed. changed.
No keywords are used while defining the Virtual keyword is used in the base class and overrides
method. keyword is used in the derived class.
Private, static, final methods can be Private, static, final methods can not be overloaded
overloaded
It is also known as Compile time polymorphism It is also known as Run time polymorphism or Dynamic
or static polymorphism or early binding polymorphism or Late binding
Example Example:
class Demo{
private double a, b;
this.a = b;
this.a = b;
}
}
if (obj1 == obj2)
else
}
In the above example, we can see that the output is wrong because
obj1 and obj2 refer to two different objects that is why (obj1 = = obj2)
is false.
Constructors in Java
A constructor is a special method that is used to initialize an object.Every class
has a constructor,if we don't explicitly declare a constructor for any java class the
compiler builds a default constructor for that class. A constructor does not have any
return type.
A constructor executed when the object is created.
this and super can be used only in CONSTRUCTOR BUT NOT IN THE NORMAL
METHODS.
CONSTRUCTOR IN EXCEPTION HANDLING THE CHILD CLASS
CONSTRUCTOR SHOULD THROWS SAME EXCEPTION DECLARED BY THE
PARENT CLASS CONSTRUCTOR.
A constructor has same name as the class in which it resides. Constructor in Java
can not be abstract, static, final or synchronized. These modifiers are not
allowed for constructor.
class Car
{
String name ;
String model;
Car( ) //Constructor
{
name ="";
model="";
}
}
Rules of constructor:
1.name of the constructor and the class same
2.return type is not allowed even void(if it was declared the COMPILER treats that constructor as
normal method)
3. Constructor in Java can not be abstract, static, final or synchronized are not allowed but
public,private,default and protected are allowed.
4.the first line of the constructor should be this() or super().
5. we cannot use this() and super() simulataneously. If we use then ->Op:call to this
must be In first line
Rules for this() and super()
Types of Constructor
There are two types of constructors:
same class).
i)the DC contain only one line it is super() and it calls the parent class
constructor.
protected)
NOtE:when we are creating child class object automatically parent class constructor
will be executed.
Parameterized constructor
Each time a new object is created at least one constructor will be invoked.
Car c = new Car() //Default constructor invoked
Car c = new Car(name); //Parameterized constructor invoked
Constructor Overloading
Like methods, a constructor can also be overloaded. Overloaded constructors are
differentiated on the basis of their type of parameters or number of parameters.
Constructor overloading is not much different than method overloading. In case of
method overloading you have multiple methods with same name but different
signature, whereas in Constructor overloading you have multiple constructor with
different signature but only difference is that Constructor doesn't have return type in
Java.
Output:
111 Karan
111 Karan
Private Constructors
In Java, private constructors are used in singleton class. In private constructor, only
one object can be created and the object is created within the class and also all the
methods are static. An object can not be created if a private constructor is present
inside a constructor. A class which have a private constructor and all the methods
are static then it is class Utility class.
Example:
}
class PrivateConDemo
{
public static void main(String as[])
{
abc.add(4, 5);
abc.sub(5, 3);
}
}
Singleton Class
In Java, a Singleton class is used when we want to create only one object at a
time. To create a singleton class we have to create a private constructor and
methods of the class should be static. The concept of Lazy initialization is used
for creating a static method. The main difference between a normal class and a
singleton class is that in normal class we use constructor and in singleton class, we
use getInstance() method. The getInstance() method creates an object with the
name of the class.
Below is an example using getInstance() method
Example:
import java.io.*;
class MySingleton
private MySingleton() { }
if (instance == null)
return instance;
// Driver Class
class Main
MySingleton a = MySingleton.getInstance();
MySingleton b = MySingleton.getInstance();
Op:
20
20
Class parent{
Parent(){
Child(int i){
P s v m(s[] a){
Child c=new c();//this will give error bcz child is parameterized and the parent class constructor will
not be inherited.
Class test{
Test(){
This(10);//1
}
Test(int d){
This();//2
P s v m(s[] a){
//IN THIS WE DID NOT CREATE ANY OBJECT EVEN THOUGH THE COMPILER LOOKS FOR RECURSIVE
CONSTRUCTOR CALLS 1 AND 2. SO HELLO WILL NOT BE PRINTED INSTEAD COMPILE TIME ERROR
OCCURS
s.o.p(“hello”);
}}
P(int i){
//1.overcome
P(){
//here DC will be created and SUPER() with no argument insidewill be called to parent class but
there is p(int i) with argument so it will throw compile time error.
Java keyword’S:
Note : this() is different from this and also super() is diff from super
ParentClass.java
public class ParentClass
{
{
System.out.println("In ParentClass");
}
ChildClass.java
public class ChildClass extends ParentClass
{
System.out.println("In ChildClass");
}
this.showMyName();
super.showMyName();
}
Main.java
public class Main
{
childObj.test();
}
Program output.
Console
In ChildClass
The final variable which is not assigned to any value can only be assigned through the class
constructor.
Static in Java
1. Static Variable
The most important thing about static variables is that they belong to class level.
What it means is that there can be only one copy of variable in runtime.
When you define a static variable in class definition, each instance of class will have
access to that single copy. Separate instances of class will not have their own local
copy, like they have for non-static variables.
public class JavaStaticExample
{
public static void main(String[] args)
{
DataObject objOne = new DataObject();
objOne.staticVar = 10;
objOne.nonStaticVar = 20;
DataObject objTwo = new DataObject();
System.out.println(objTwo.staticVar); //10
System.out.println(objTwo.nonStaticVar); //null
DataObject.staticVar = 30; //Direct Access
System.out.println(objOne.staticVar); //30
System.out.println(objTwo.staticVar); //30
}
}
class DataObject {
public static Integer staticVar;
public Integer nonStaticVar;
}
Output:
10
null
30
30
Notice how we changed the value to 30, and both objects now see the updated value
which is 30.
Another thing you should have noticed that how we are able to access static
variable with its classname i.e. DataObject.staticVar. We don’t need to create any
instance to access static variables. It clearly shows that static variables belong to
class scope.
Additional points on static variable:
Note: A static variable can never be defined inside a method i.e it can never be a
local variable.
Example:
Suppose you make 2 objects of class Student and you change the value of static
variable from one object. Now when you print it from other object, it will display the
changed value. This is because it was declared static i.e it is constant for every
object created.
package studytonight;
class Student{
int a;
static int id = 35;
void change(){
System.out.println(id);
}
}
o1.change();
Student.id = 1;
o2.change();
}
}
Output:
35
1
Accessed using class name (can be accessed using Accessed using object
object name as well)
Allocated memory only once Allocated new memory each time a new
object is created
int y = 100;
x++; y++;
t1.increment();
t2.increment();
System.out.println(t2.y);
101
102
See the difference in value of two variable. Static variable x shows the changes
made to it by increment() method on the different object. While instance
variable y show only the change made to it by increment() method on that particular
instance.
Restrictions
There are two main restrictions. 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.
1 Instance variables
2 Static Variables
3 Local Variables
Eg:instance var
2.Static Method in Java
A method can also be declared as static. Static methods do not need instance of its
class for being accessed. main() method is the most common example of static
method. main() method is declared as static because it is called before any object of
the class is created.
Let's take an Example:
class Test
System.out.println(x*x);
64
1 You can access only static variables inside static methods. If you try to access
any non-static variable, the compiler error will be generated with message
“Cannot make a static reference to the non-static field nonStaticVar“.
2 Static methods can be accessed via it’s class reference, and there is no need to
create an instance of class. Though you can access using instance reference as
well but it will have not any difference in comparison to access via class
reference.
3 Static methods also belong to class level scope.
3.Static IMPORT in Java
The normal import declaration imports classes from packages, so that they can be used
without package reference. Similarly the static import declaration imports static
members from classes and allowing them to be used without class reference.
A static import declaration also comes in two flavors: single-static import and static-
import-on-demand. A single-static import declaration imports one static member
from a type. A static-import-on-demand declaration imports all static members of a
type. The general syntax of static import declaration is as follows:
//Single-static-import declaration:
import static <<package name>>.<<type name>>.<<static member name>>;
//Static-import-on-demand declaration:
import static <<package name>>.<<type name>>.*;
You code can now use the name out to mean System.out in your program. The
compiler will use the static import declaration to resolve the
name out to System.out.
public class StaticImportTest {
}
int eid;
String name;
static {
se1.eid = 104;
se1.name = "Abhijit";
se1.show();
int x;
x = 10;
compiler error: non-static variable count cannot be referenced from a static context
int x;
{
System.out.println( DataObject.StaticInnerClas.innerStaticVar );
}
class DataObject
}
Please note that an static inner class cannot access the non-static members of outer
class. It can access only static members from outer class.
public class JavaStaticExample
{
DataObject.StaticInnerClas.accessOuterClass();
}
}
class DataObject
static {
staticVar = 40;
}
public static Integer getStaticVar(){
return staticVar;
}
{
{
}
}
Output:
40
Enumeration in Java
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism
that binds together code and the data it manipulates.Other way to think about encapsulation
is, it is a protective shield that prevents the data from being accessed by the code outside
this shield.
Encapsulation can be achieved by: Declaring all the variables in the class as private
and writing public methods in the class to set and get the values of variables.
public class Encapsulate
{
// private variables declared
// these can only be accessed by
// public methods of class
private String geekName;
private int geekRoll;
private int geekAge;
// get method for age to access
// private variable geekAge
public int getAge()
{
return geekAge;
}
// get method for name to access
// private variable geekName
public String getName()
{
return geekName;
}
// get method for roll to access
// private variable geekRoll
public int getRoll()
{
return geekRoll;
}
// set method for age to access
// private variable geekage
public void setAge( int newAge)
{
geekAge = newAge;
}
// set method for name to access
// private variable geekName
public void setName(String newName)
{
geekName = newName;
}
// set method for roll to access
// private variable geekRoll
public void setRoll( int newRoll)
{
geekRoll = newRoll;
}
}
// class keyword)
enum Color
{
Color c1 = Color.RED;
System.out.println(c1);
}
Output :
RED
// be assigned to enums.
enum TrafficSignal
{
return this.action;
}
{
this.action = action;
}
// Driver code
{
{
}
}
Output:
name : RED action: STOP
name : GREEN action: GO
name : ORANGE action: SLOW DOWN
10
20
30
40
Jagged Array
Jagged means to have an uneven edge or surface. In java, a jagged array means to
have a multi-dimensional array with uneven size of rows in it.
Initialization of Jagged Array
new operator is used to initialize an array.
Example:
int[ ][ ] arr = new int[3][ ]; //there will be 10 arrays whose size is variable
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[5];
Arithmetic operators
Relation operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Misc operators
instanceOf operator
This operator is used for object reference variables. The operator checks whether
the object is of particular type (class type or interface type)
Example:
class instanceof_operators1{
public static void main(String as[])
{
String a = "Studytonight";
boolean b = a instanceof String;
System.out.println( b );
}
}
Nested try block
In Java, there can be multiple try blocks. A try block within another try block is known
as nested try block. In a program when any block of code can cause an error and the
entire program can cause another error then try blocks are made
Example:
class NestedDemo1
{
public static void main(String args[])
{
try{
try{
System.out.println("Divide 39/0");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try{
inta[]=new int[8];
a[8]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
For Loop
1 Simple for loop
2 For-each loop
3 labelled for loop
labelname:
for(initialization;condition;incr/decr)
{
//code for execution
}
Example:
public class LabeledForDemo1
{
public static void main(String[] args)
{
num:
for(inti=1;i<=5;i++)
{
num1:
for(int j=1;j<=5;j++)
{
if(i==2&&j==2)
{
break num;
}
System.out.println(i+" "+j);
}
}
}
}
Goto statement
In Java, the goto statement is not supported. Its is a reserved keyword which can be
added in the future versions of java. But the label is supported in Java and it can be
placed before a nested loop statement.
In the below example, label and break are used instead of the goto statement.
Example:
The core advantage of exception handling is to maintain the normal flow of the
application.
Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be
executed. If we perform exception handling, the rest of the statement will be executed.
That is why we use exception handling in Java.
Note: if exception occurs, the remaining statement will not exceute
The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions
are checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.
3) Error
Keyword Description
At a time only one exception occurs and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
The try block contains two exceptions. But at a time only one exception occurs and its
corresponding catch block is invoked.
1 int a[]=new int[5];
2 a[5]=30/0;
3 }
4 catch(Exception e){System.out.println("common task completed");}
5 catch(ArithmeticException e){System.out.println("task1 is completed");}
6 catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
import java.lang.*;
class Main{
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
//int a=10/0;
System.out.println("other statement");
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
THE OUTPUT IS :
going to divide
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 5
other statement
normal flow..
going to divide
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 5
handeled
normal flow..
FINALLY
1 public class TestFinallyBlock2{
2 public static void main(String args[]){
3 try{
4 int data=25/0;
5 System.out.println(data);
6 }
7 catch(ArithmeticException e){System.out.println(e);}
8 finally{System.out.println("finally block is always executed");}
9 System.out.println("rest of the code...");
10 }
11 }
Op:
12 Output:Exception in thread main java.lang.ArithmeticException:/ by
zero
13 finally block is always executed
14 rest of the code...
Java throw keyword
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The
throw keyword is mainly used to throw custom exception.
1 public class TestThrow1{
2 static void validate(int age){
3 if(age<18)
4 throw new ArithmeticException("not valid");
5 else
6 System.out.println("welcome to vote");
7 }
8 public static void main(String args[]){
9 validate(13);
10 System.out.println("rest of the code...");
11 }
12 }
Output:
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
performing check up before the code being used.
CASE1:
3 import java.io.*;
4 class M{
5 void method()throws IOException{
6 throw new IOException("device error");
7 }
8 }
9 public class Testthrows2{
10 public static void main(String args[]){
11 try{
12 M m=new M();
13 m.method();
14 }catch(Exception e){System.out.println("exception handled");}
15
16 System.out.println("normal flow...");
17 }
18 }
Output:exception handled
normal flow...
CASE 2:
o A)In case you declare the exception, if exception does not occur, the code will be
executed fine.
o B)In case you declare the exception if exception occures, an exception will be
thrown at runtime because throws does not handle the exception.
1 import java.io.*;
2 class M{
3 void method()throws IOException{
4 throw new IOException("device error");
5 }
6 }
7 class Testthrows4{
8 public static void main(String args[])throws IOException{//declare exception
9 M m=new M();
10 m.method();
11
12 System.out.println("normal flow...");
13 }
14 }
Output:Runtime Exception
1 class TestExceptionPropagation1{
2 void m(){
3 int data=50/0;
4 }
5 void n(){
6 m();
7 }
8 void p(){
9 try{
10 n();
11 }catch(Exception e){System.out.println("exception handled");}
12 }
13 public static void main(String args[]){
14 TestExceptionPropagation1 obj=new TestExceptionPropagation1();
15 obj.p();
16 System.out.println("normal flow...");
17 }
18 }
Output:exception handled
normal flow...
1 class TestExceptionPropagation2{
2 void m(){
3 throw new java.io.IOException("device error");//checked exception
4 }
5 void n(){
6 m();
7 }
8 void p(){
9 try{
10 n();
11 }catch(Exception e){System.out.println("exception handeled");}
12 }
13 public static void main(String args[]){
14 TestExceptionPropagation2 obj=new TestExceptionPropagation2();
15 obj.p();
16 System.out.println("normal flow");
17 }
18 }
1) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare th
exception.
1 import java.io.*;
2 class Parent{
3 void msg(){System.out.println("parent");}
4 }
5
6 class TestExceptionChild extends Parent{
7 void msg()throws IOException{
8 System.out.println("TestExceptionChild");
9 }
10 public static void main(String args[]){
11 Parent p=new TestExceptionChild();
12 p.msg();
13 }
14 }
Test it Now
2) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare th
exception but can declare unchecked exception.
1 import java.io.*;
2 class Parent{
3 void msg(){System.out.println("parent");}
4 }
5
6 class TestExceptionChild1 extends Parent{
7 void msg()throws ArithmeticException{
8 System.out.println("child");
9 }
10 public static void main(String args[]){
11 Parent p=new TestExceptionChild1();
12 p.msg();
13 }
14 }
Test it Now
Output:child
1) Rule: If the superclass method declares an exception, subclass overridden method can declare same, subcla
no exception but cannot declare parent exception.
Output:child
Output:child
Example in case subclass overridden method declares no exception
1 import java.io.*;
2 class Parent{
3 void msg()throws Exception{System.out.println("parent");}
4 }
5
6 class TestExceptionChild5 extends Parent{
7 void msg(){System.out.println("child");}
8
9 public static void main(String args[]){
10 Parent p=new TestExceptionChild5();
11 try{
12 p.msg();
13 }catch(Exception e){}
14 }
15 }
1 class TestCustomException1{
2
3 static void validate(int age)throws InvalidAgeException{
4 if(age<18)
5 throw new InvalidAgeException("not valid");
6 else
7 System.out.println("welcome to vote");
8 }
9
10 public static void main(String args[]){
11 try{
12 validate(13);
13 }catch(Exception m){System.out.println("Exception occured: "+m);}
14
15 System.out.println("rest of the code...");
16 }
17 }
Test it Now
Output:Exception occured: InvalidAgeException:not valid
rest of the code...
Java Regex
The Java Regex or Regular Expression is an API to define a pattern for searching or
manipulating strings.
It is widely used to define the constraint on strings such as password and email
validation. After learning Java regex tutorial, you will be able to test your regular
expressions by the Java Regex Tester Tool.
The Matcher and Pattern classes provide the facility of Java regular expression. The
java.util.regex package provides following classes and interfaces for regular expressions.
1 MatchResult interface
2 Matcher class
3 Pattern class
4 PatternSyntaxException class
Matcher class
It implements the MatchResult interface. It is a regex engine which is used to perform
match operations on a character sequence.
Pattern class
It is the compiled version of a regular expression. It is used to define a pattern for the
regex engine.
1 import java.util.regex.*;
2 public class RegexExample1{
3 public static void main(String args[]){
4 //1st way
5 Pattern p = Pattern.compile(".s");//. represents single character
6 Matcher m = p.matcher("as");
7 boolean b = m.matches();
8 //2nd way
9 boolean b2=Pattern.compile(".s").matcher("as").matches();
10 //3rd way
11 boolean b3 = Pattern.matches(".s", "as"); //2nd character is s so true if it was some other it would
//be false
12 System.out.println(b+" "+b2+" "+b3);
13 }}
Output
5 [a-z&&[def]] d, e, or f (intersection)
Output:
Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread can be in one of the five states. According to sun, there is only 4 states
in thread life cycle in java new, runnable, non-runnable and terminated. There is no
running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
How to create thread
There are two ways to create a thread:
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thre
class and implements Runnable interface.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be exec
Runnable interface have only one method named run().
1 public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
1 class Multi extends Thread{
2 public void run(){
3 System.out.println("thread is running...");
4 }
5 public static void main(String args[]){
6 Multi t1=new Multi();
7 t1.start();
8 }
9 }
Output:thread is running...
1 class Multi3 implements Runnable{
2 public void run(){
3 System.out.println("thread is running...");
4 }
5
6 public static void main(String args[]){
7 Multi3 m1=new Multi3();
8 Thread t1 =new Thread(m1); //Thread(new Multi3())
9 t1.start();
10 }
11 }
Output:thread is running...
If you are not extending the Thread class,your class object would not be treated as a thread object.So you
need to explicitely create Thread class object.We are passing the object of your class that implements
Runnable so that your class run() method may execute.
next →← prev
There is no guarantee that which runnable thread will be chosen to run by the thread
scheduler.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule
the threads.
1 public class TestThreadTwice1 extends Thread{
2 public void run(){
3 System.out.println("running...");
4 }
5 public static void main(String args[]){
6 TestThreadTwice1 t1=new TestThreadTwice1();
7 t1.start();
8 t1.start();
9 }
10 }
Test it Now
running
Exception in thread "main" java.lang.IllegalThreadStateException
THREAD SLEEP:
import java.lang.*;
Thread t;
System.out.println(Thread.currentThread().getName() + "
" + i);
try {
// thread to sleep for 1000 milliseconds
Thread.sleep(1000);
} catch (Exception e) {
System.out.println(e);
}
}
}
Let us compile and run the above program, this will produce the following result −
Thread-0 10
Thread-1 10
Thread-0 11
Thread-1 11
Thread-0 12
Thread-1 12
next →← prev
1 class TestCallRun1 extends Thread{
2 public void run(){
3 System.out.println("running...");
4 }
5 public static void main(String args[]){
6 TestCallRun1 t1=new TestCallRun1();
7 t1.run();//fine, but does not start a separate call stack
8 }
9 }
Test it Now
Output:running...
1 class TestCallRun2 extends Thread{
2 public void run(){
3 for(int i=1;i<5;i++){
4 try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
5 System.out.println(i);
6 }
7 }
8 public static void main(String args[]){
9 TestCallRun2 t1=new TestCallRun2();
10 TestCallRun2 t2=new TestCallRun2();
11
12 t1.run();
13 t2.run();
14 }
15 }
Test it Now
Output:1
2
3
4
5
1
2
3
4
5
As you can see in the above program that there is no context-switching because here t1 and t2 w
object not thread object.
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate yield() method
// in Java
import java.lang.*;
{
System.out.println(Thread.currentThread().getName()
}
// Driver Class
{
t.start();
{
Thread.yield();
System.out.println(Thread.currentThread().getName()
}
}
Output:
Thread-0 in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
main in control
main in control
main in control
main in control
main in control
Output may vary in machine to machine but chances of execution of yield() thread first is hi
because main thread is always pausing its execution and giving chance to child thread(with
Note:
Once a thread has executed yield method and there are many threads with same priority is wa
can't specify which thread will get execution chance first.
The thread which executes the yield method will enter in the Runnable state from Running sta
Once a thread pauses its execution, we can't specify when it will get chance again it depends
Underlying platform must provide support for preemptive scheduling if we are using yield meth
2 sleep(): This method causes the currently executing thread to sleep for the specified number of mil
precision and accuracy of system timers and schedulers.
Syntax:
3 // sleep for the specified number of milliseconds
4 public static void sleep(long millis) throws InterruptedException
5
6 //sleep for the specified number of milliseconds plus nano seconds
7 public static void sleep(long millis, int nanos)
throws InterruptedException
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate
import java.lang.*;
Thread t;
{
{
System.out.println(Thread.currentThread().getName()
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
{
// call run() function
t.start();
t2.start();
}
Output:
Thread-0 0
Thread-1 0
Thread-0 1
Thread-1 1
Thread-0 2
Thread-1 2
Thread-0 3
Thread-1 3
Note:
Based on the requirement we can make a thread to be in sleeping state for a specified period
Sleep() causes the thread to definitely stop executing for a given amount of time; if no other th
run, the CPU will be idle (and probably enter a power saving mode).
yield() vs sleep()
yield:() indicates that the thread is not doing anything particularly important and if any other thre
be run, they can. Otherwise, the current thread will continue to run.
sleep(): causes the thread to definitely stop executing for a given amount of time; if no other thre
run, the CPU will be idle (and probably enter a power saving mode).
8 join(): The join() method of a Thread instance is used to join the start of a thread’s execution to end
such that a thread does not start running until another thread ends. If join() is called on a Thread ins
thread will block until the Thread instance has finished executing.
The join() method waits at most this much milliseconds for this thread to die. A timeout of 0 means
Syntax:
9 // waits for this thread to die.
10 public final void join() throws InterruptedException
11
12 // waits at most this much milliseconds for this thread to die
13 public final void join(long millis)
14 throws InterruptedException
15
16 // waits at most milliseconds plus nanoseconds for this thread to die.
The java.lang.Thread.join(long millis, int nanos)
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate join() method in Java
import java.lang.*;
{
Thread t = Thread.currentThread();
+ t.getName());
+ t.isAlive());
}
{
t.start();
t.join(1000);
t.getName());
}
Output:
Current thread: Thread-0
Is Alive? true
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
There are many java daemon threads running automatically e.g. gc, finalizer etc.
You can see all the detail by typing the jconsole in the command prompt. The jconsole
tool provides information about the loaded classes, memory usage, running threads etc.
1 public class TestDaemonThread1 extends Thread{
2 public void run(){
3 if(Thread.currentThread().isDaemon()){//checking for daemon thread
4 System.out.println("daemon thread work");
5 }
6 else{
7 System.out.println("user thread work");
8 }
9 }
10 public static void main(String[] args){
11 TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
12 TestDaemonThread1 t2=new TestDaemonThread1();
13 TestDaemonThread1 t3=new TestDaemonThread1();
14
15 t1.setDaemon(true);//now t1 is daemon thread
16
17 t1.start();//starting threads
18 t2.start();
19 t3.start();
20 }
21 }
Test it Now
Output
daemon thread work
user thread work
user thread work
Note: If you want to make a user thread as Daemon, it must not be started
otherwise it will throw IllegalThreadStateException.
File: MyThread.java
1 class TestDaemonThread2 extends Thread{
2 public void run(){
3 System.out.println("Name: "+Thread.currentThread().getName());
4 System.out.println("Daemon: "+Thread.currentThread().isDaemon());
5 }
6
7 public static void main(String[] args){
8 TestDaemonThread2 t1=new TestDaemonThread2();
9 TestDaemonThread2 t2=new TestDaemonThread2();
10 t1.start();
11 t1.setDaemon(true);//will throw exception here
12 t2.start();
13 }
14 }
Test it Now
Output:exception in thread main: java.lang.IllegalThreadStateException
Java Thread pool represents a group of worker threads that are waiting for the job and
reuse many times.
In case of thread pool, a group of fixed size threads are created. A thread from the
thread pool is pulled out and assigned a job by the service provider. After completion of
the job, thread is contained in the thread pool again.
Better performance It saves time because there is no need to create new thread.
It is used in Servlet and JSP where container creates a thread pool to process the
request.
File: WorkerThread.java
1 import java.util.concurrent.ExecutorService;
2 import java.util.concurrent.Executors;
3 class WorkerThread implements Runnable {
4 private String message;
5 public WorkerThread(String s){
6 this.message=s;
7 }
8 public void run() {
9 System.out.println(Thread.currentThread().getName()+" (Start) message =
"+message);
10 processmessage();//call processmessage method that sleeps the thread for 2 seco
nds
11 System.out.println(Thread.currentThread().getName()+" (End)");//prints thread na
me
12 }
13 private void processmessage() {
14 try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace()
; }
15 }
16 }
File: JavaThreadPoolExample.java
1 public class TestThreadPool {
2 public static void main(String[] args) {
3 ExecutorService executor = Executors.newFixedThreadPool(5);//creating a pool of
5 threads
4 for (int i = 0; i < 10; i++) {
5 Runnable worker = new WorkerThread("" + i);
6 executor.execute(worker);//calling execute method of ExecutorService
7 }
8 executor.shutdown();
9 while (!executor.isTerminated()) { }
10
11 System.out.println("Finished all threads");
12 }
13 }
download this example
Output:
Constructo Description
r
File: ThreadGroupDemo.java
1 public class ThreadGroupDemo implements Runnable{
2 public void run() {
3 System.out.println(Thread.currentThread().getName());
4 }
5 public static void main(String[] args) {
6 ThreadGroupDemo runnable = new ThreadGroupDemo();
7 ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
8
9 Thread t1 = new Thread(tg1, runnable,"one");
10 t1.start();
11 Thread t2 = new Thread(tg1, runnable,"two");
12 t2.start();
13 Thread t3 = new Thread(tg1, runnable,"three");
14 t3.start();
15
16 System.out.println("Thread Group Name: "+tg1.getName());
17 tg1.list();
18
19 }
20 }
Output:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
Thread[one,5,Parent ThreadGroup]
Thread[two,5,Parent ThreadGroup]
Thread[three,5,Parent ThreadGroup]
For Example :
{
Runtime.getRuntime().addShutdownHook(new Thread()
{
{
}
} );
}
When we run the above code, you will see that the shutdown hook is getting called
by the JVM when it finishes execution of the main method.
Output:
Application Terminating ...
Shutdown Hook is running !
While it is pretty simple to write a shutdown hook, one needs to know the internals
behind the shutdown hooks to make use of those properly.
HOW TO PERFORM SINGLE TASK BY MULTIPLE THREADS:
If you have to perform single task by many threads, have only one run() method.For example:
1 class TestMultitasking1 extends Thread{
2 public void run(){
3 System.out.println("task one");
4 }
5 public static void main(String args[]){
6 TestMultitasking1 t1=new TestMultitasking1();
7 TestMultitasking1 t2=new TestMultitasking1();
8 TestMultitasking1 t3=new TestMultitasking1();
9
10 t1.start();
11 t2.start();
12 t3.start();
13 }
14 }
Test it Now
Output:task one
task one
task one
Program of performing single task by multiple threads
1 class TestMultitasking2 implements Runnable{
2 public void run(){
3 System.out.println("task one");
4 }
5
6 public static void main(String args[]){
7 Thread t1 =new Thread(new TestMultitasking2());//passing annonymous object of Test
Multitasking2 class
8 Thread t2 =new Thread(new TestMultitasking2());
9
10 t1.start();
11 t2.start();
12
13 }
14 }
Test it Now
Output:task one
task one
If you have to perform multiple tasks by multiple threads,have multiple run() methods.For example:
1 class Simple1 extends Thread{
2 public void run(){
3 System.out.println("task one");
4 }
5 }
6
7 class Simple2 extends Thread{
8 public void run(){
9 System.out.println("task two");
10 }
11 }
12
13 class TestMultitasking3{
14 public static void main(String args[]){
15 Simple1 t1=new Simple1();
16 Simple2 t2=new Simple2();
17
18 t1.start();
19 t2.start();
20 }
21 }
Test it Now
Output:task one
task two
1 class TestMultitasking4{
2 public static void main(String args[]){
3 Thread t1=new Thread(){
4 public void run(){
5 System.out.println("task one");
6 }
7 };
8 Thread t2=new Thread(){
9 public void run(){
10 System.out.println("task two");
11 }
12 };
13
14
15 t1.start();
16 t2.start();
17 }
18 }
Test it Now
Output:task one
task two
1) By nulling a reference:
1 Employee e=new Employee();
2 e=null;
2) By assigning a reference to another:
1 Employee e1=new Employee();
2 Employee e2=new Employee();
3 e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
1 new Employee();
3 Increases memory efficiency and decreases the chances for memory leak.
finalize() method
Sometime an object will need to perform some specific task before it is destroyed
such as closing an open connection or releasing any resources held. To handle such
situation finalize() method is used. finalize() method is called by garbage collection
thread before collecting object. Its the last chance for any object to perform cleanup
utility.
Signature of finalize() method
protected void finalize()
//finalize-code
Collector)thread.
gc() method
gc() method is used to call garbage collector explicitly. However gc() method does
not guarantee that JVM will perform the garbage collection. It only request the JVM
for garbage collection. This method is present in System and Runtime class.
Example for gc() method
Let's take an example and understand the functioning of the gc() method.
public class Test
{
Test t = new Test();
t=null;
System.gc();
System.out.println("Garbage Collected");
Garbage Collected
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
There are two types of synchronization
1 Process Synchronization
2 Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1 Mutual Exclusive
1.1 Synchronized method.
1.2 Synchronized block.
1.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. This can be done by three ways in java:
1 by synchronized method
2 by synchronized block
3 by static synchronization
When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.
1 //example of java synchronized method
2 class Table{
3 synchronized void printTable(int n){//synchronized method
4 for(int i=1;i<=5;i++){
5 System.out.println(n*i);
6 try{
7 Thread.sleep(400);
8 }catch(Exception e){System.out.println(e);}
9 }
10
11 }
12 }
13
14 class MyThread1 extends Thread{
15 Table t;
16 MyThread1(Table t){
17 this.t=t;
18 }
19 public void run(){
20 t.printTable(5);
21 }
22
23 }
24 class MyThread2 extends Thread{
25 Table t;
26 MyThread2(Table t){
27 this.t=t;
28 }
29 public void run(){
30 t.printTable(100);
31 }
32 }
33
34 public class TestSynchronization2{
35 public static void main(String args[]){
36 Table obj = new Table();//only one object
37 MyThread1 t1=new MyThread1(obj);
38 MyThread2 t2=new MyThread2(obj);
39 t1.start();
40 t2.start();
41 }
42 }
Output: 5
10
15
20
25
100
200
300
400
500
1 //Program of synchronized method by using annonymous class
2 class Table{
3 synchronized void printTable(int n){//synchronized method
4 for(int i=1;i<=5;i++){
5 System.out.println(n*i);
6 try{
7 Thread.sleep(400);
8 }catch(Exception e){System.out.println(e);}
9 }
10
11 }
12 }
13
14 public class TestSynchronization3{
15 public static void main(String args[]){
16 final Table obj = new Table();//only one object
17
18 Thread t1=new Thread(){
19 public void run(){
20 obj.printTable(5);
21 }
22 };
23 Thread t2=new Thread(){
24 public void run(){
25 obj.printTable(100);
26 }
27 };
28
29 t1.start();
30 t2.start();
31 }
32 }
Output: 5
10
15
20
25
100
200
300
400
500
Static Synchronization
If you make any static method as synchronized, the lock will be on the class not on
object.
Problem without static synchronization
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.I want no interference
between t1 and t3 or t2 and t4.Static synchronization solves this problem.
1 class Table{
2
3 synchronized static void printTable(int n){
4 for(int i=1;i<=10;i++){
5 System.out.println(n*i);
6 try{
7 Thread.sleep(400);
8 }catch(Exception e){}
9 }
10 }
11 }
12
13 public class TestSynchronization5 {
14 public static void main(String[] args) {
15
16 Thread t1=new Thread(){
17 public void run(){
18 Table.printTable(1);
19 }
20 };
21
22 Thread t2=new Thread(){
23 public void run(){
24 Table.printTable(10);
25 }
26 };
27
28 Thread t3=new Thread(){
29 public void run(){
30 Table.printTable(100);
31 }
32 };
33
34 Thread t4=new Thread(){
35 public void run(){
36 Table.printTable(1000);
37 }
38 };
39 t1.start();
40 t2.start();
41 t3.start();
42 t4.start();
43
44 }
45 }
Test it Now
Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
1 static void printTable(int n) {
2 synchronized (Table.class) { // Synchronized block on class A
3 // ...
4 }
5 }
Deadlock in java
Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a
thread is waiting for an object lock, that is acquired by another thread and second
thread is waiting for an object lock that is acquired by first thread. Since, both threads
are waiting for each other to release the lock, the condition is called deadlock.
o wait()
o notify()
o notifyAll()
Interrupting a Thread:
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() m
breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sle
calling the interrupt() method performs normal behaviour and doesn't interrupt the thread but sets th
Let's first see the methods provided by the Thread class for thread interruption.
Let's understand the java reentrant monitor by the example given below:
1 class Reentrant {
2 public synchronized void m() {
3 n();
4 System.out.println("this is m() method");
5 }
6 public synchronized void n() {
7 System.out.println("this is n() method");
8 }
9 }
In this class, m and n are the synchronized methods. The m() method internally calls the
n() method.
Now let's call the m() method on a thread. In the class given below, we are creating
thread using annonymous class.
1 public class ReentrantExample{
2 public static void main(String args[]){
3 final ReentrantExample re=new ReentrantExample();
4
5 Thread t1=new Thread(){
6 public void run(){
7 re.m();//calling method of Reentrant class
8 }
9 };
10 t1.start();
11 }}
Test it Now
Output: this is n() method
this is m() method
Java package:
Package in Java is a mechanism to encapsulate a group of classes, sub packages
and interfaces. Packages are used for:
Preventing naming conflicts. For example there can be two classes with name
Employee in two packages, college.staff.cse.Employee and college.staff.ee.Employee
Making searching/locating and usage of classes, interfaces, enumerations and
annotations easier
Providing controlled access: protected and default have package level access control.
A protected member is accessible by classes in the same package and its subclasses.
A default member (without any access specifier) is accessible by classes in the same
package only.
Packages can be considered as data encapsulation (or data-hiding).
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of
the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
https://www.geeksforgeeks.org/java-lang-package-java/
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
https://www.geeksforgeeks.org/java-util-package-java/
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with
the console.
1 System.out.println("simple message");
2 System.err.println("error message");
1 int i=System.in.read();//returns ASCII code of 1st character
2 System.out.println((char)i);//will print the character
next →← prev
Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached
with the console.
1 System.out.println("simple message");
2 System.err.println("error message");
1 int i=System.in.read();//returns ASCII code of 1st character
2 System.out.println((char)i);//will print the character
Do You Know?
o How to write a common data to multiple files using a single stream only?
o How can we access multiple files by a single stream?
o How can we improve the performance of Input and Output operation?
o How many ways can we read data from the keyboard?
o What does the console class?
o How to compress and uncompress the data of a file?
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:
OutputStream
Java application uses an output stream to write data to a destination; it may be a file,
an array, peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure
given below.
next →← prev
Java I/O Tutorial
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the cl
output operations.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because
that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
1 System.out.println("simple message");
2 System.err.println("error message");
1 int i=System.in.read();//returns ASCII code of 1st character
2 System.out.println((char)i);//will print the character
Do You Know?
o How to write a common data to multiple files using a single stream only?
o How can we access multiple files by a single stream?
o How can we improve the performance of Input and Output operation?
o How many ways can we read data from the keyboard?
o What does the console class?
o How to compress and uncompress the data of a file?
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array, perip
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array, peripher
Let's understand the working of Java OutputStream and InputStream by the figure given below.
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an output stre
stream accepts output bytes and sends them to some sink.
1) public void write(int)throws IOException is used to write a byte to the current out
OutputStream Hierarchy
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input stream
1) public abstract int read()throws reads the next byte of data from the input stream
IOException of the file.
3) public void close()throws IOException is used to close the current input stream.
InputStream Hierarchy
Java PrintWriter class
Java PrintWriter class is the implementation of Writer class. It is used to print the
formatted representation of objects to the text-output stream.
Class declaration
Let's see the declaration for Java.io.PrintWriter class:
1 public class PrintWriter extends Writer
2 import java.io.File;
3 import java.io.PrintWriter;
4 public class PrintWriterExample {
5 public static void main(String[] args) throws Exception {
6 //Data to write on Console using PrintWriter
7 PrintWriter writer = new PrintWriter(System.out);
8 writer.write("Javatpoint provides tutorials of all technology.");
9 writer.flush();
10 writer.close();
11 //Data to write in File using PrintWriter
12 PrintWriter writer1 =null;
13 writer1 = new PrintWriter(new File("D:\\testout.txt"));
14 writer1.write("Like Java, Spring, Hibernate, Android, PHP etc.");
15 writer1.flush();
16 writer1.close();
17 }
18 }
Outpt
The content of a text file testout.txt is set with the data Like Java, Spring,
Hibernate, Android, PHP etc.
4)deserializabilty
next →← prev
Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is main
RMI, JPA, EJB and JMS technologies.
It is mainly used to travel object's state on the network (which is known as marshaling).
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java classe
these classes may get a certain capability. The Cloneable and Remote are also marker interfaces.
The String class and all the wrapper classes implement the java.io.Serializable interface by default.
1 import java.io.Serializable;
2 public class Student implements Serializable{
3 int id;
4 String name;
5 public Student(int id, String name) {
6 this.id = id;
7 this.name = name;
8 }
9 }
In the above example, Student class implements Serializable interface. Now its objects can be conve
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to an OutputSt
support the java.io.Serializable interface can be written to streams.
Constructor
1) public ObjectOutputStream(OutputStream out) throws creates an ObjectOutputStream
IOException {} specified OutputStream.
Important Methods
Method Description
1) public final void writeObject(Object obj) throws IOException writes the specified object
{} ObjectOutputStream.
ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.
Constructor
1) public creates an ObjectInputStream that reads from the
ObjectInputStream(InputStream specified InputStream.
in) throws IOException {}
Important Methods
Method Description
1) public final Object reads an object from the input
readObject() throws stream.
IOException,
ClassNotFoundException{}
1 import java.io.*;
2 class Persist{
3 public static void main(String args[]){
4 try{
5 //Creating the object
6 Student s1 =new Student(211,"ravi");
7 //Creating stream and writing the object
8 FileOutputStream fout=new FileOutputStream("f.txt");
9 ObjectOutputStream out=new ObjectOutputStream(fout);
10 out.writeObject(s1);
11 out.flush();
12 //closing the stream
13 out.close();
14 System.out.println("success");
15 }catch(Exception e){System.out.println(e);}
16 }
17 }
Output:
Success
1 import java.io.*;
2 class Depersist{
3 public static void main(String args[]){
4 try{
5 //Creating stream to read the object
6 ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
7 Student s=(Student)in.readObject();
8 //printing the data of the serialized object
9 System.out.println(s.id+" "+s.name);
10 //closing the stream
11 in.close();
12 }catch(Exception e){System.out.println(e);}
13 }
14 }
Output:
211 ravi
1 class Employee implements Serializable{
2 int id;
3 String name;
4 static String company="SSS IT Pvt Ltd";//it won't be serialized
5 public Student(int id, String name) {
6 this.id = id;
7 this.name = name;
8 }
9 }
{
x = 10;
y = 30;
}
}
class CloneDemo1
{
public static void main(String[] args)
{
Add obj = new Add();
System.out.println("Object 1");
System.out.println("**********************");
System.out.println("X = "+obj.x);
System.out.println("Y = "+obj.y);
int z = obj.x + obj.y;
System.out.println("Total = "+z);
System.out.println("**********************");
System.out.println("**********************");
Add obj1 = obj;
obj1.x=20;
obj1.y=5;
System.out.println("Object 2");
System.out.println("X = "+obj1.x);
System.out.println("Y = "+obj1.y);
int z1 = obj1.x + obj1.y;
System.out.println("Total = "+z1);
System.out.println("**********************");
}
public static void change(Add obj)
{
obj.x = 10;
obj.y = 10;
}
}
Java Networking
Collections in Java
A collection — sometimes called a container — is simply an object that groups multiple elements into a
single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. Typically,
they represent data items that form a natural group, such as a poker hand (a collection of cards), a mail
folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers).
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).
What Is a Collections Framework?
A collections framework is a unified architecture for representing and manipulating collections. All
collections frameworks contain the following:
Interfaces: These are abstract data types that represent collections. Interfaces allow collections to
be manipulated independently of the details of their representation. In object-oriented languages,
interfaces generally form a hierarchy.
Implementations: These are the concrete implementations of the collection interfaces. In
essence, they are reusable data structures.
Algorithms: These are the methods that perform useful computations, such as searching and
sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic:
that is, the same method can be used on many different implementations of the appropriate
collection interface. In essence, algorithms are reusable functionality.
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.
In given example, first two add() methods are allowed. Third one will not compile and
will give error – “The method put(Integer, String) in the
type HashMap<Integer,String> is not applicable for the arguments (String, String)”. It
helps in detecting incompatible types early to prevent unpredictable behavior in
runtime.
Generic HashMap
HashMap<Integer, String> map = new HashMap<>();
map.put("3", "C"); //NOT allowed - Key is string
All Java wrapper classes and String class override these functions with their specific
implementation so they behave correctly in such collections. we need to make sure
that these functions are overridden correctly in our user defined custom classes as
well.
SortedSet HashMap
SortedSet<Integer> sortedSet = new TreeSet<>();
sortedSet.add(2);
sortedSet.add(1);
sortedSet.add(1);
sortedSet.add(3);
System.out.println(sortedSet); //[1,2,3]
Java 8 Collections
Java 8 was a major release which introduced lambda style of programming in Java.
Collections classes was also improved as a result. For example, we can iterate over
collections in single line and perform an action on all elements of collection
using forEach statement.
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.forEach(System.out::print);
The code is easier to read as well because of consistent class and method
names.
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.
1 List <data-type> list1= new ArrayList();
2 List <data-type> list2 = new LinkedList();
3 List <data-type> list3 = new Vector();
4 List <data-type> list4 = new 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.
1 import java.util.*;
2 class TestJavaCollection1{
3 public static void main(String args[]){
4 ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5 list.add("Ravi");//Adding object in arraylist
6 list.add("Vijay");
7 list.add("Ravi");
8 list.add("Ajay");
9 //Traversing list through Iterator
10 Iterator itr=list.iterator();
11 while(itr.hasNext()){
12 System.out.println(itr.next());
13 }
14 }
15 }
Output:
Ravi
Vijay
Ravi
Ajay
Create ArrayList
Usually we will create either an empty list and add elements to it. Or we will create an
arraylist with another exising collection.
Create arraylist
//Empty arraylist
//Arraylist initialized with another collection
Iterate
Iterate arraylist
ArrayList<Integer> digits = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
Iterator<Integer> iterator = digits.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
METHODS:
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.
1 import java.util.*;
2 public class TestJavaCollection2{
3 public static void main(String args[]){
4 LinkedList<String> al=new LinkedList<String>();
5 al.add("Ravi");
6 al.add("Vijay");
7 al.add("Ravi");
8 al.add("Ajay");
9 Iterator<String> itr=al.iterator();
10 while(itr.hasNext()){
11 System.out.println(itr.next());
12 }
13 }
14 }
Output:
Ravi
Vijay
Ravi
Ajay
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.
1 import java.util.*;
2 public class TestJavaCollection3{
3 public static void main(String args[]){
4 Vector<String> v=new Vector<String>();
5 v.add("Ayush");
6 v.add("Amit");
7 v.add("Ashish");
8 v.add("Garima");
9 Iterator<String> itr=v.iterator();
10 while(itr.hasNext()){
11 System.out.println(itr.next());
12 }
13 }
14 }
Output:
Ayush
Amit
Ashish
Garima
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.
1 import java.util.*;
2 public class TestJavaCollection4{
3 public static void main(String args[]){
4 Stack<String> stack = new Stack<String>();
5 stack.push("Ayush");
6 stack.push("Garvit");
7 stack.push("Amit");
8 stack.push("Ashish");
9 stack.push("Garima");
10 stack.pop();
11 Iterator<String> itr=stack.iterator();
12 while(itr.hasNext()){
13 System.out.println(itr.next());
14 }
15 }
16 }
Output:
Ayush
Garvit
Amit
Ashish
Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list
that is used to hold the elements which are about to be processed. There are various
classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue
interface.
1 Queue<String> q1 = new PriorityQueue();
2 Queue<String> q2 = new ArrayDeque();
There are various classes that implement the Queue interface, some of them are given
below.
PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow null
values to be stored in the queue.
1 import java.util.*;
2 public class TestJavaCollection5{
3 public static void main(String args[]){
4 PriorityQueue<String> queue=new PriorityQueue<String>();
5 queue.add("Amit Sharma");
6 queue.add("Vijay Raj");
7 queue.add("JaiShankar");
8 queue.add("Raj");
9 System.out.println("head:"+queue.element());
10 System.out.println("head:"+queue.peek());
11 System.out.println("iterating the queue elements:");
12 Iterator itr=queue.iterator();
13 while(itr.hasNext()){
14 System.out.println(itr.next());
15 }
16 queue.remove();
17 queue.poll();
18 System.out.println("after removing two elements:");
19 Iterator<String> itr2=queue.iterator();
20 while(itr2.hasNext()){
21 System.out.println(itr2.next());
22 }
23 }
24 }
Output:
head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj
Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the
elements from both the side. Deque stands for a double-ended queue which enables us
to perform the operations at both the ends.
1 Deque d = new ArrayDeque();
ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque.
Unlike queue, we can add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
Consider the following example.
1 import java.util.*;
2 public class TestJavaCollection6{
3 public static void main(String[] args) {
4 //Creating Deque and adding elements
5 Deque<String> deque = new ArrayDeque<String>();
6 deque.add("Gautam");
7 deque.add("Karan");
8 deque.add("Ajay");
9 //Traversing elements
10 for (String str : deque) {
11 System.out.println(str);
12 }
13 }
14 }
Output:
Gautam
Karan
Ajay
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface.
It represents the unordered set of elements which doesn't allow us to store the duplicate
items. We can store at most one null value in Set. Set is implemented by HashSet,
LinkedHashSet, and TreeSet.
1 Set<data-type> s1 = new HashSet<data-type>();
2 Set<data-type> s2 = new LinkedHashSet<data-type>();
3 Set<data-type> s3 = new TreeSet<data-type>();
HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash
table for storage. Hashing is used to store the elements in the HashSet. It contains
unique items.
1 import java.util.*;
2 public class TestJavaCollection7{
3 public static void main(String args[]){
4 //Creating HashSet and adding elements
5 HashSet<String> set=new HashSet<String>();
6 set.add("Ravi");
7 set.add("Vijay");
8 set.add("Ravi");
9 set.add("Ajay");
10 //Traversing elements
11 Iterator<String> itr=set.iterator();
12 while(itr.hasNext()){
13 System.out.println(itr.next());
14 }
15 }
16 }
Output:
Vijay
Ravi
Ajay
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It
extends the HashSet class and implements Set interface. Like HashSet, It also contains
unique elements. It maintains the insertion order and permits null elements.
1 import java.util.*;
2 public class TestJavaCollection8{
3 public static void main(String args[]){
4 LinkedHashSet<String> set=new LinkedHashSet<String>();
5 set.add("Ravi");
6 set.add("Vijay");
7 set.add("Ravi");
8 set.add("Ajay");
9 Iterator<String> itr=set.iterator();
10 while(itr.hasNext()){
11 System.out.println(itr.next());
12 }
13 }
14 }
Output:
Ravi
Vijay
Ajay
SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its elements.
The elements of the SortedSet are arranged in the increasing (ascending) order. The
SortedSet provides the additional methods that inhibit the natural ordering of the
elements.
1 SortedSet<data-type> set = new TreeSet();
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like
HashSet, TreeSet also contains unique elements. However, the access and retrieval time
of TreeSet is quite fast. The elements in TreeSet stored in ascending order.
1 import java.util.*;
2 public class TestJavaCollection9{
3 public static void main(String args[]){
4 //Creating and adding elements
5 TreeSet<String> set=new TreeSet<String>();
6 set.add("Ravi");
7 set.add("Vijay");
8 set.add("Ravi");
9 set.add("Ajay");
10 //traversing elements
11 Iterator<String> itr=set.iterator();
12 while(itr.hasNext()){
13 System.out.println(itr.next());
14 }
15 }
16 }
Output:
Ajay
Ravi
Vijay