Nothing Special   »   [go: up one dir, main page]

Core Java

Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 266

JAVA INTRODUCTION:

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 :

 Now String can be used to control Switch statement.


 Multi Catch Exception
 try-with-resource statement
 Binary Integer Literals
 Underscore in numeric literals, etc.

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.

 Enhanced Productivity by providing Optional Classes feature, Lamda Expressions,

Streams etc.

 Ease of Use

 Improved Polyglot programming. A Polyglot is a program or script, written in a form

which is valid in multiple programming languages and it performs the same

operations in multiple programming languages. So Java now supports such type of

programming technique.

 Improved Security and performance.

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)

3.THEN BYTE CODE IS GENERATED( .CLASS) FILE

EXECUTION STAGE(PROCESS OF RUNNING THE COMPILED CODE AND CHECK FOR OUTPUT):

4.IN JVM THERE ARE THREE MAIN STAGES

i)loading process(loading required files into current program using loader)

ii)linking process(linking the loaded file into current running prg where they are needed using linker)

iii)execution process(afeter the above process it produces the output)

TRANSLATORS:
1.COMPILER: translate the whole program at a time.

2.Interpreter:translate line by line.

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.

Java is platform-independent but JVM is platform dependent


In Java, the main point here is that the JVM depends on the operating system – so if
you are running Mac OS X you will have a different JVM than if you are running
Windows or some other operating system. This fact can be verified by trying to
download the JVM for your particular machine – when trying to download it, you will
be given a list of JVMs corresponding to different operating systems, and you will
obviously pick whichever JVM is targeted for the operating system that you are
running. So we can conclude that JVM is platform-dependent and it is the reason
why Java is able to become “Platform Independent”.
Important Points:
 In the case of Java, it is the magic of Bytecode that makes it platform
independent.
 This adds to an important feature in the JAVA language termed as portability. Every
system has its own JVM which gets installed automatically when the jdk software is
installed. For every operating system separate JVM is available which is capable to
read the .class file or byte code.
 An important point to be noted is that while JAVA is platform-independent language,
the JVM is platform-dependent. Different JVM is designed for different OS and byte
code is able to run on different OS.
Programming components:

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.

In java, data types are classified into two catagories :

1 Primitive Data type-


byte(1),short(2),int(4),long(8),float(4),double(8),char(2byte)
2 Non-Primitive Data type

OBJECT CODE VS BYTE CODE:


1.ob code is in the c++ and c
2.byte code is in java
JAVA CLASS NOT FOUND EXCEPTION:
JVM follow (AUTHORIZED)Delegation-Hierarchy principle to load classes.
System class loader delegate load request to extension class loader and extension
class loader delegate request to boot-strap class loader. If class found in boot-
strap path, class is loaded otherwise request again transfers to extension
class loader and then to system class loader. At last if system class loader fails to
load class, then we get run-time exception java.lang.ClassNotFoundException.

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.

PC Registers :Store address of current execution instruction of a thread. Obviously


each thread has separate PC Registers.

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.

Java Native Interface (JNI) :


It is an interface which interacts with the Native Method Libraries and provides the
native libraries(C, C++) required for the execution. It enables JVM to call C/C++
libraries and to be called by C/C++ libraries which may be specific to hardware.
Native Method Libraries :
It is a collection of the Native Libraries(C, C++) which are required by the Execution
Engine.

Does JVM create object of Main class (the class


with main())?
Consider following program.

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.

// Note Main is abstract

abstract class Main {

    public static void main(String args[])

    {

        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.

1. Local Variable Array (LVA):


 The local variables part of stack frame is organized as a zero-based array of
words.
 It contains all parameters and local variables of the method.
 Each slot or entry in the array is of 4 Bytes.
 Values of type int, float, and reference occupy 1 entry or slot in the array i.e. 4
bytes.
 Values of double and long occupy 2 consecutive entries in the array i.e. 8 bytes
total.
 Byte, short and char values will be converted to int type before
storing and occupy 1 slot i.e. 4 Bytes.
 But the way of storing Boolean values is varied from JVM to JVM. But most of
the JVM gives 1 slot for Boolean values in the local variable array.
 The parameters are placed into the local variable array first, in the order in
which they are declared.
For Example: Let us consider a class Example having a method bike() then

local variable array will be as shown in below diagram:
// Class Declaration
class Example
{
public void bike(int i, long l, float f,
double d, Object o, byte b)
{

}
}

2. Operand Stack (OS):


 JVM uses operand stack as work space like rough work or we can say for
storing intermediate calculation’s result.
 Operand stack is organized as array of words like local variable array. But this
is not accessed by using index like local variable array rather it is accessed by
some instructions that can push the value to the operand stack and some
instructions that can pop values from operand stack and some instructions that
can perform required operations.
 For Example: Here is how a JVM will use this below code that would subtract
two local variables that contain two ints and store the int result in a third local
variable:
 So here first two instructions iload_0 and iload_1 will push the values in
operand stack from local variable array. And instruction isub will subtract these
two values and stores the result back to the operand stack and
after istore_2 the result will pop out from the operand stack and will store into
local variable array at position 2.

3. Frame Data (FD):


 It contains all symbolic reference (constant pool resolution) and normal method
return related to that particular method.
 It also contains a reference to Exception table which provide the corresponding
catch block information in the case of exceptions.

JVM VS JDK VS JRE:


 JDK – Java Development Kit (in short JDK) is Kit which provides the
environment to develop and execute(run) the Java program. JDK is a kit(or
package) which includes two things
1 Development Tools(to provide an environment to develop your java
programs)
2 JRE (to execute your java program).
Note : JDK is only used by Java Developers.
 JRE – Java Runtime Environment (to say JRE) is an installation package
which provides environment to only run(not develop) the java program(or
application)onto your machine. JRE is only used by them who only wants to run
the Java Programs i.e. end users of your system.
 JVM – Java Virtual machine(JVM) is a very important part of both JDK and
JRE because it is contained or inbuilt in both. Whatever Java program you run
using JRE or JDK goes into JVM and JVM is responsible for executing the
java program line by line hence it is also known as interpreter.
JDK

Java Development Kit is the core component of Java Environment and


provides all the tools, executables and binaries required to compile, debug
and execute a Java Program. JDK is a platform-specific software and
that’s why we have separate installers for Windows, Mac, and Unix
systems. We can say that JDK is the superset of JRE since it contains
JRE with Java compiler, debugger, and core classes. The current
version of JDK is 11 also known as Java 11.

JVM

JVM is the heart of Java programming language. When we run a program,


JVM is responsible for converting Byte code to the machine specific code.
JVM is also platform dependent and provides core java functions like
memory management, garbage collection, security etc. JVM is
customizable and we can use java options to customize it, for example
allocating minimum and maximum memory to JVM. JVM is
called virtual because it provides an interface that does not depend on the
underlying operating system and machine hardware. This independence
from hardware and the operating system is what makes java program write-
once-run-anywhere.

JRE

JRE is the implementation of JVM, it provides a platform to execute java


programs. JRE consists of JVM and java binaries and other classes to
execute any program successfully. JRE doesn’t contain any
development tools like java compiler, debugger etc. If you want to execute
any java program, you should have JRE installed but we don’t need JDK
for running any java program.
Let’s look at some of the important difference between JDK, JRE, and JVM.

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.

HEAP AND STACK MEMORY AREA:


Java Heap Space

Java Heap space is used by java runtime to allocate memory to Objects


and JRE classes. Whenever we create an object, it’s always created in the
Heap space.
Garbage Collection runs on the heap memory to free the memory used by
objects that don’t have any reference. Any object created in the heap space
has global access and can be referenced from anywhere of the application.

Java Stack Memory

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;

public class Memory {

public static void main(String[] args) { // Line 1


int i=1; // Line 2
Object obj = new Object(); // Line 3
Memory mem = new Memory(); // Line 4
mem.foo(obj); // Line 5
} // Line 9

private void foo(Object param) { // Line 6


String str = param.toString(); //// Line 7
System.out.println(str);
} // Line 8

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.

Let’s go through the steps of the execution of the program.


 As soon as we run the program, it loads all the Runtime classes into the
Heap space. When the main() method is found at line 1, Java Runtime
creates stack memory to be used by main() method thread.
 We are creating primitive local variable at line 2, so it’s created and stored
in the stack memory of main() method.
 Since we are creating an Object in the 3rd line, it’s created in heap memory
and stack memory contains the reference for it. A similar process occurs
when we create Memory object in the 4th line.
 Now when we call the foo() method in the 5th line, a block in the top of the
stack is created to be used by the foo() method. Since Java is pass-by-
value, a new reference to Object is created in the foo() stack block in the
6th line.
 A string is created in the 7th line, it goes in the String Pool in the heap
space and a reference is created in the foo() stack space for it.
 foo() method is terminated in the 8th line, at this time memory block
allocated for foo() in stack becomes free.
 In line 9, main() method terminates and the stack memory created for
main() method is destroyed. Also, the program ends at this line, hence
Java Runtime frees all the memory and ends the execution of the program.

Difference between Java Heap Space and Stack Memory

Based on the above explanations, we can easily conclude the following


differences between Heap and Stack memory.

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.

Java is Pass by Value and Not Pass by Reference


Consider the following Java program that passes a primitive type to function.

public class Main


{
    public static void main(String[] args)
    {
        int x = 5;
        change(x);
        System.out.println(x);
    }
    public static void change(int x)
    {
        x = 10;
    }
}
Output:
5
We pass an int to the function “change()” and as a result the change in the value of
that integer is not reflected in the main method. Like C/C++, Java creates a copy of
the variable being passed in the method and then do the manipulations. Hence the
change is not reflected in the main method.

How about objects or references?


In Java, all primitives like int, char, etc are similar to C/C++, but all non-primitives (or
objects of any class) are always references. So it gets tricky when we pass object
references to methods. Java creates a copy of references and pass it to method, but
they still point to same memory reference. Mean if set some other object to reference
passed inside method, the object from calling method as well its reference will
remain unaffected.
The changes are not reflected back if we change the object itself to refer some
other location or object
If we assign reference to some other location, then changes are not reflected back in
main().

// A Java program to show that references are also passed


// by value.
class Test
{
    int x;
    Test(int i) { x = i; }
    Test()      { x = 0; }
}
  
class Main
{
    public static void main(String[] args)
    {
        // t is a reference
        Test t = new Test(5);
  
        // Reference is passed and a copy of reference
        // is created in change()
        change(t);
  
        // Old value of t.x is printed
        System.out.println(t.x);
    }
    public static void change(Test t)
    {
        // We changed reference to refer some other location
        // now any changes made to reference are not reflected
        // back in main
        t = new Test();
  
        t.x = 10;
    }
}
Output:
5
Changes are reflected back if we do not assign reference to a new location or
object:
If we do not change the reference to refer some other object (or memory location),
we can make changes to the members and these changes are reflected back.

// A Java program to show that we can change members using using


// reference if we do not change the reference itself.
class Test
{
    int x;
    Test(int i) { x = i; }
    Test()      { x = 0; }
}
  
class Main
{
    public static void main(String[] args)
    {
        // t is a reference
        Test t = new Test(5);
  
        // Reference is passed and a copy of reference
        // is created in change()
        change(t);
  
        // New value of x is printed
        System.out.println(t.x);
    }
  
    // This change() doesn't change the reference, it only
    // changes member of object referred by reference
    public static void change(Test t)
    {
        t.x = 10;
    }
}
Output:
10

Exercise: Predict the output of following Java program

//  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

Difference between java.exe and javaw.exe:


“java.exe” and “javaw.exe”, both are Java executables on the Windows platform.
These files are nearly identical versions of the Java Application Launcher utility. Both
versions of the launcher take the same arguments and options. The launcher is
invoked with “java” or “javaw” followed by launcher options, the class or Java archive
(JAR) file name and application arguments.

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

Everything in Java binary format files is stored in big-endian order. This is


sometimes called network order. This means that if you use only Java, all files are
done the same way on all platforms: Mac, PC, UNIX, etc. You can freely exchange
binary data electronically without any concerns about endian-ness.

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).

Java command line arguments


The program arguments passed at launching the Java program are called command
line arguments.

A Java program can be launched either from console or from an editor. To launch a


program we have to use "java className" command from command prompt or
system console. While launching the program we can pass additional arguments (no
limit of numbers of arguments) in below syntax.
1. Command line arguments syntax
In given below syntax, we are passing 5 arguments to the Main class MyClass.
MyClass has the main() method which accepts these arguments in form of
an String array.
$ java MyClass arg1 arg2 arg3 arg4 arg5

2. Java command line arguments example


Let’s create an example to understand how command line program arguments work
in Java. This class simple accepts the arguments and print them in console.

As a programmer, we can use these arguments as startup parameters to customize


the behavior of application in runtime.

Main.java
package app;

 
public class Main

  public static void main(String[] args)

  {

    for(int i = 0; i< args.length; i++)

    {

      System.out.println( args[i] );

    }

  }

Now run this class from console.

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.

Java References Vs C/C++ Pointers


Java doesn’t have pointers; Java has references.

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);

How to run java class file which is in different


directory?
In this article, we will learn about how to use other project’s utilities, classes, and
members. Before proceeding let’s learn about some keywords.
classpath
Classpath is the location from where JVM starts execution of a program. Similar to
the classic dynamic loading behavior, when executing Java programs, the Java
Virtual Machine finds and loads classes lazily (it loads the bytecode of a class only
when the class is first used). The classpath tells Java where to look in the filesystem
for files defining these classes. Variables and methods which are accessible and
available at classpath are known as classpath variables. By default JVM always
access the classpath classes while executing a program. JVM always go into the
deep of classpath to search for a class or resource.
The JVM searches for and loads classes in this order:
1 bootstrap classes: the classes that are fundamental to the Java Platform (comprising
the public classes of the Java Class Library, and the private classes that are necessary
for this library to be functional).
2 extension classes: packages that are in the extension directory of the JRE or JDK,
jre/lib/ext/ user-defined packages and libraries
Using import keyword
import keyword is used in Java to import classes from current project’s classpath.
You can import classes from different packages but from same classpath. It is to be
remembered that packaging of a class starts from classpath. Suppose you have
directory structure as follows:
a > b > c > d > class A
and your classpath starts from c, then your class should be in package d not in
a.b.c.d.
Using classpath -cp option
import keyword can import classes from the current classpath, outside the classpath
import can’t be used. Now suppose you already have a project in which you have
used some utility classes, which you need in your second project also. Then in this
situation import keyword doesn’t work because your first project is at another
classpath. In that case, you can use -cp command while compiling and executing
your program.
Let’s proceed with the following example. Create a directory structure as shown in
the figure below.

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

/***** File name: Trial.java ******/

public class Geeks

   public static void main(String[] args) {

        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.

/***** File name: Trial.java ******/

class Geeks

    public static void main(String[] args) {

        System.out.println("Hello world");

    }

Step 1: javac Trial.java


Step1 will create a Geeks.class (byte code) without any error message since the
class is not public.
Step 2: java Geeks
Now the output will be Hello world
The myth about the file name and class name should be same only when the class is
declared in
public.
 The above program works as follows :

 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

Do we need forward declarations in Java?


The answer is NO, Unlike C++, we don’t need forward declarations in Java. Identifiers
(class and method names) are recognized automatically from source files. Similarly, library

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:

class Test2 {      


    public static void main(String[] args) {    
         Test1 t1 = new Test1();
         t1.fun(5);         
    }
}    
class Test1 {   
    void fun(int x) {
        System.out.println("fun() called: x = " + x);
    }
}
Output:
fun() called: x = 5

Note that Test1 and fun() are not declared before their use.

Does Java support goto?


Java does not support goto, it is reserved as a keyword just in case they wanted to
add it to a later version.
 Unlike C/C++, Java does not have goto statement, but java supports label.
 The only place where a label is useful in Java is right before nested loop statements.
 We can specify label name with break to break out a specific outer loop.
 Similarly, label name can be specified with continue.
 // Java code to illustrate
 // using label  and break
 // instead of goto
   
 // file name: Main.java
 public class Main {
     public static void main(String[] args)
     {
   
     // label for outer loop
     outer:
         for (int i = 0; i < 10; i++) {
             for (int j = 0; j < 10; j++) {
                 if (j == 1)
                     break outer;
                 System.out.println(" value of j = " + j);
             }
         } // end of outer loop
     } // end of main()
 } // end of class Main
o/p: value of j = 0
// Java code to illustrate
// using label  and continue
// instead of goto
  
// file name: Main.java
public class Main {
    public static void main(String[] args)
    {
  
    // label for outer loop
    outer:
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                if (j == 1)
                     continue outer;
                System.out.println(" value of j = " + j);
            }
        } // end of outer loop
    } // end of main()
} // end of class Main
Output:
value of j = 0
value of j = 0
value of j = 0
value of j = 0
value of j = 0
value of j = 0
value of j = 0
value of j = 0
value of j = 0
value of j = 0
Explanation : Since continue statement skips to the next iteration in the loop, it
iterates for 10 times as i iterates from 0 to 9. So the outer loop executes for 10 times
and the inner for loop executes 1 time in each of the outer loops.
Java does not have a goto statement because it provides a way to branch in an
arbitrary and unstructured manner. This usually makes goto-ridden code hard to
understand and hard to maintain. It also prohibits certain compiler optimization.
There are, however, a few places where the goto is a valuable and legitimate
construct for flow control. For example, the goto can be useful when you are exiting
from a deeply nested set of loops. To handle such situations, Jave defines an
expanded form of the break statement.
The general form of the labelled break statement is:
break label;

Currying Functions in Java with Examples


Function Currying is a concept of breaking a function with many arguments into
many functions with single argument in such a way, that the output is same. In
other words, its a technique of simplifying a multi-valued argument function into
single-valued argument multi-functions.
Consider the example to clear the concept:

Adding 2 numbers using Function Currying

// Java Program to demonstrate Function Currying


  
import java.util.function.Function;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Using Java 8 Functions
        // to create lambda expressions for functions
        // and with this, applying Function Currying
  
        // Curried Function for Adding u & v
        Function<Integer, Function<Integer, Integer> >
            curryAdder = u -> v -> u + v;
  
        // Calling the curried functions
  
        // Calling Curried Function for Adding u & v
        System.out.println("Add 2, 3 :"
                           + curryAdder
                                 .apply(2)
                                 .apply(3));
  
        }
}
Output:
Add 2, 3 :5

Using underscore in Numeric Literals in Java


class Test
{
     public static void main (String[] args)
               throws java.lang.Exception
     {
         int inum = 1_00_00_000;
         System.out.println("inum:" + inum);
  
         long lnum = 1_00_00_000;
         System.out.println("lnum:" + lnum);
  
         float fnum = 2.10_001F;
         System.out.println("fnum:" + fnum);
  
         double dnum = 2.10_12_001;
         System.out.println("dnum:" + dnum);
      }
}
Output:
inum: 10000000
lnum: 10000000
fnum: 2.10001
dnum: 2.1012001

Using _ (underscore) as variable name in Java


Java 9 has made changes in features of java language and eliminating underscore
from legal name is a major change made by Oracle.
 The use of the variable name _ in any context is never encouraged.
 Latest versions of the Java reserve this name as a keyword and/or give it special
semantics. If you use the underscore character (“_”) an identifier, your source code can
no longer be compiled. You will get compile time error.
Using underscore as variable name in Java 8
Although, it is supported in Java 8, a mandatory warning is issued if you use _ as an
identifier , telling you that “use of ‘_’ as an identifier might not be supported in
releases after Java SE 8”. (See JDK-8005852 Treatment of ‘_’ as identifier)

Access specifiers for classes or interfaces in


Java

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[]) {
  
  }
}

prog.java:2: error: modifier protected not allowed here


protected class Test {}
^
1 error
Note : Nested interfaces and classes can have all access specifiers.
Non-access modifiers : In java, we have 7 non-access modifiers. They are used with
classes, methods, variables, constructors etc to provide information about their behavior to
JVM.They are
 static
 final
 abstract
 synchronized
 transient
 volatile
 native

Interesting facts about null in Java


1.null is Case sensitive:

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;

// you can assign null to Integer also


Integer itr = null;

// null can also be assigned to Double


Double dbl = null;
// null can be type cast to String
String myStr = (String) null;

// it can also be type casted to Integer


Integer myItr = (Integer) null;

// yes it's possible, no error


Double myDbl = (Double) null;
4. Autoboxing and unboxing : During auto-boxing and unboxing operations,
compiler simply throws Nullpointer exception error if a null value is assigned to
primitive boxed data type.
public class Test
{
    public static void main (String[] args) throws java.lang.Exception
    {
            //An integer can be null, so this is fine
            Integer i = null;
              
            //Unboxing null to integer throws NullpointerException
            int a = i;
    }
}
Output:
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:6)

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

instanceof operator is true if the value of the Expression is not null.

This is an important property of instanceof operation which makes it useful for type casting

checks.

public class Test


{
    public static void main (String[] args) throws java.lang.Exception
    {
        Integer i = null;
        Integer j = 10;
              
        //prints false
        System.out.println(i instanceof Integer);
          
        //Compiles successfully
        System.out.println(j instanceof Integer);
    }
}
Output:
false
true
Static vs Non static Methods: We cannot call a non-static method on a reference variable
with null value, it will throw NullPointerException, but we can call static method with
reference variables with null values. Since static methods are bonded using static binding,
they won’t throw Null pointer Exception. public class Test
{             
    public static void main(String args[])
    {
        Test obj= null;
        obj.staticMethod();
        obj.nonStaticMethod();                             
    }
      
    private static void staticMethod()
    {
        //Can be called by null reference
        System.out.println("static method, can be called by null
reference");
          
    }
          
    private void nonStaticMethod()
    {
        //Can not be called by null reference
        System.out.print(" Non-static method- ");
        System.out.println("cannot be called by null reference");
          
    }
  
}

7.== and != The comparison and not equal to operators are allowed with null in Java. 

ADVANCED JAVA IS FOR APPLICATION DEV:


1.JDBC (JAVA PRG AND DATABASE)
2.SERVLET
3.JSP

Core java is for meaningful writing programs:

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.

Threads Are Everywhere


It is not important if you write explicit multithreaded application or not,
often you work in a multithreaded environment without directly
managing thread instances.
Here are few example of multithreaded applications where the
programmer doesn't manually invoke the creation of new threads:
 Web applications because servlets are handled by a pool of threads
 Swing desktop applications where threads handle GUI events 
 Timer instances create new threads to handle future task
executions
Creating an Immutable Object
To create an immutable object you need to follow some simple rules:
 Don't add any setter method
 Declare all fields final and private
 If a field is a mutable object create defensive copies of it for getter
methods
 If a mutable object passed to the constructor must be assigned to a
field create a defensive copy of it
 Don't allow subclasses to override methods.
Now we discover point by point the reasons of the five rules explained
before.

Don't add any setter method


If you are building an immutable object its internal state will never
change. Task of a setter method is to change the internal value of a field,
so you can't add it.

Declare all fields final and private


A private field is not visible from outside the class so no manual changes
can't be applied to it. 
Declaring a field final will guarantee that if it references a primitive value
the value will never change, if it reference an object the reference can't
be changed. This is not enough to ensure that an object with only private
final fields is not mutable. Here is an example showing an object with a
private final field and an example on how to mutate its internal state:

public class DateContainer {


private final Date date;

public DateContainer() {
this.date = new Date();
}

public Date getDate() {


return 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 1 second after

If a field is a mutable object create defensive copies


of it for getter methods
We have seen before that defining a field final and private is not enough
because it is possible to change its internal state. To solve this problem
we need to create a defensive copy of that field and return that field
every time it is requested.
Here is the previous class with that modification:

public class DateContainer {


private final Date date;

public DateContainer() {
this.date = new Date();
}

public Date getDate() {


return new Date(date.getTime());
}
}

....
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

If a mutable object passed to the constructor must


be assigned to a field create a defensive copy of it
The same problem happens if you hold a reference passed to the
constructor because it is possible to change it.
Here we show a modified example of DateContainer that accept a Date
for the constructor and we will see how it is possible to change its
internal state:

public class DateContainer {


private final Date date;

public DateContainer(Date date) {


this.date = date;
}

public Date getDate() {


return new Date(date.getTime());
}
}

....

Date date = new Date();


DateContainer dateContainer = new DateContainer(date);
System.out.println(dateContainer.getDate());
date.setTime(date.getTime() + 1000);
System.out.println(dateContainer.getDate());
// Now dateContainer date is 1 second after also if the getter method
// create a defensive copy of date. We changed the reference passed to the
// constructor, not the copy.

So holding a reference to an object passed to the constructor can create


mutable objects. To solve this problem it is necessary to create a
defensive copy of the parameter if they are mutable objects:

public class DateContainer {


private final Date date;

public DateContainer(Date date) {


this.date = new Date(date.getTime());
}

public Date getDate() {


return new Date(date.getTime());
}
}

....

Date date = new Date();


DateContainer dateContainer = new DateContainer(date);
System.out.println(dateContainer.getDate());
date.setTime(date.getTime() + 1000);
System.out.println(dateContainer.getDate());
// Now dateContainer date is not changed. We create a copy on the constructor
// so a change to the external date will not affect the internal state of
// DateContainer instance

Note that if a field is a reference to an immutable object is not necessary


to create defensive copies of it in the constructor and in the getter
methods it is enough to define the field as final and private. As an
example of common immutable objects there are String, all primitive
wrappers (Integer, Long, Double, Byte....), BigDecimal, BigInteger.
Don't allow subclasses to override methods
If a subclass override a method it can return the original value of a
mutable field instead of a defensive copy of it.
To solve this problem it is possible to do one of the following:
 Declare the immutable class as final so it can't be extended
 Declare all methods of the immutable class final so they can't be
overriden
 Create a private constructor and a factory to create instances of the
immutable class because a class with private constructors can't be
extended 

Different ways to create objects in


Java
1) new Keyword
public class NewKeyword
{
String s = "studytonight";
public static void main(String as[])
{
NewKeyword a = new NewKeyword();
System.out.println(a.s);
}
}

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:

public class CloneEg implements Cloneable


{
@Override
protected Object clone() throws CloneNotSupportedException
{
return super.clone();
}
String s = "studytonight";

public static void main(String[] args)


{
CloneEg a= new CloneEg();
try
{
CloneEg b = (CloneEg) a.clone();
System.out.println(b.s);
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}
}
}
 The super keyword in Java is a reference variable which is used to refer immediate
parent class object. Whenever you create the instance of subclass, an instance of
parent class is created implicitly which is referred by super reference variable.

4.Deserialization : De-serialization is technique of reading an object from the saved state in


a file. Refer Serialization/De-Serialization in java

FileInputStream file = new FileInputStream(filename);


ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();
Note : All classes have at least one constructor. If a class does not explicitly declare any,
the Java compiler automatically provides a no-argument constructor, also called the default
constructor. This default constructor calls the class parent’s no-argument constructor (as it
contain only one statement i.e super();), or the Object class constructor if the class has no
other parent (as Object class is parent of all classes either directly or indirectly).

4) Using deserialization : Whenever we serialize and then deserialize an object,


JVM creates a separate object. In deserialization, JVM doesn’t use any constructor
to create the object.
To deserialize an object we need to implement the Serializable interface in the class.
Serializing an Object :

// Java program to illustrate Serializing

// an Object.

import java.io.*;

  

class DeserializationExample implements Serializable

    private String name;

    DeserializationExample(String name)
    {

        this.name = name;

    }

  

    public static void main(String[] args)

    {

        try

        {

            DeserializationExample d =

                    new DeserializationExample("GeeksForGeeks");

            FileOutputStream f = new FileOutputStream("file.txt");

            ObjectOutputStream oos = new ObjectOutputStream(f);

            oos.writeObject(d);

            oos.close();

            f.close();

        }

        catch (Exception e)

        {

            e.printStackTrace();

        }

    }

Object of DeserializationExample class is serialized using writeObject() method and


written to file.txt file.
Deserialization of Object :
// Java program to illustrate creation of Object

// using Deserialization.

import java.io.*;

  

public class DeserializationExample

    public static void main(String[] args)

    {

        try
        {

            DeserializationExample d;

            FileInputStream f = new FileInputStream("file.txt");

            ObjectInputStream oos = new ObjectInputStream(f);

            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

2.when attributes are not known:


Solution is to use Wrapper Class If we create a wrapper class that contains references of
Car, we can swap cars by swapping references of wrapper class.
class Car
{
    int model, no;
  
    // Constructor
    Car(int model, int no)
    {
        this.model = model;
        this.no = no;
    }
  
    // Utility method to print object details
    void print()
    {
        System.out.println("no = " + no + 
                           ", model = " + model);
    }
}
  
// A Wrapper over class that is used for swapping
class CarWrapper
{
   Car c;
  
   // Constructor
   CarWrapper(Car c)   {this.c = c;}
}
  
// A Class that use Car and swaps objects of Car
// using CarWrapper
class Main
{
    // This method swaps car objects in wrappers
    // cw1 and cw2
    public static void swap(CarWrapper cw1, 
                            CarWrapper cw2)
    {
        Car temp = cw1.c;
        cw1.c = cw2.c;
        cw2.c = temp;
    }
  
    // Driver method
    public static void main(String[] args)
    {
        Car c1 = new Car(101, 1);
        Car c2 = new Car(202, 2);
        CarWrapper cw1 = new CarWrapper(c1);
        CarWrapper cw2 = new CarWrapper(c2);
        swap(cw1, cw2);
        cw1.c.print();
        cw2.c.print();
    }
}
Output:
no = 2, model = 202
no = 1, model = 101

Java Class File


A class is a user defined blueprint or prototype from which objects are
created.  It represents the set of properties or methods that are common to all
objects of one type. In general, class declarations can include these components,
in order:
1 Modifiers : A class can be public or has default access (Refer this for details).
Top level classes:public,abstract,final,<default>,strictfp
inner classes:private,protected,static
2 Class name: The name should begin with a initial letter (capitalized by convention).
3 Superclass(if any): The name of the class’s parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.
4 Interfaces(if any): A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement more than one
interface.
5 Body: The class body surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that
provides the state of the class and its objects, and methods are used to implement
the behavior of the class and its objects.
There are various types of classes that are used in real time applications such
as nested classes, anonymous classes, lambda expressions.

A Java class file is a file containing Java bytecode and having .class


extension that can be executed by JVM. A Java class file is created by a Java
compiler from .java files as a result of successful compilation. As we know that a
single Java programming language source file (or we can say .java file) may contain
one class or more than one class. So if a .java file has more than one class then
each class will compile into a separate class files.
For Example: Save this below code as Test.java on your system.

// Compiling this Java program would

// result in multiple class files.

  

class Sample

  

  

// Class Declaration

class Student

  

// Class Declaration

class Test

       public static void main(String[] args)   

       {

           System.out.println("Class File Structure");


       }

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.

Rules for Java Class

 A class can have only public or default(no modifier) access specifier.

 It can be either abstract, final or concrete (normal class).

 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.

 It may optionally implement any number of comma-separated interfaces.

 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

any number of default visible classes.

 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();

After the above statement std is instance/object of Student class. Here the new keyword


creates an actual physical copy of the object and assign it to the std variable. It will have
physical existence and get memory in heap area. The new operator dynamically allocates
memory for an object

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.

Using predefined class name as Class or Variable


name in Java
In Java, Using predefined class name as Class or Variable name is allowed.
However, According to Java Specification Language(§3.9) the basic rule for naming
in Java is that you cannot use a keyword as name of a class, name of a variable nor
the name of a folder used for package.
Using any predefined class in Java won’t cause such compiler error as Java
predefined classes are not keywords.
Following are some invalid variable declarations in Java:
boolean break = false; // not allowed as break is keyword
int boolean = 8; // not allowed as boolean is keyword
boolean goto = false; // not allowed as goto is keyword
String final = "hi"; // not allowed as final is keyword
Using predefined class name as User defined class name

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

// Number is predefined class name in java.lang package

// Note : java.lang package is included in every java program by default

public class Number

    public static void main (String[] args)

    {

        System.out.println("It works");

    }

Output:
It works
2 Using String as User Defined Class:

// String is predefined class name in java.lang package


// Note : java.lang package is included in every java program by default

public class String

    public static void main (String[] args)

    {

        System.out.println("I got confused");

    }

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 .

// String is predefined class name in java.lang package

// Note : java.lang package is included in every java program by default

public class String

    public static void main (java.lang.String[] args)

    {

        System.out.println("I got confused");

    }

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.

// Number is predefined class name in java.lang package


// Note : java.lang package is included in every java program by default

public class Number

    // instance variable

    int Number = 20;

      

    public static void main (String[] args)

    {

        // reference variable

        Number Number = new Number();

          

        // printing reference

        System.out.println(Number);

          

        // printing instance variable

        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.

Below is an example in which new reference variable obj1 is created


which is pointing to address as obj which is same.

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.

Syntax of Inner class

1 class Java_Outer_class{  
2  //code  
3  class Java_Inner_class{  
4   //code  
5  }  
6 }  

Advantage of java inner classes


There are basically three advantages of inner classes in java. They are as follows:

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.

2) Nested classes are used to develop more readable and maintainable


code because it logically group classes and interfaces in one place only.

3) Code Optimization: It requires less code to write.

Inner class is a part of nested class. Non-static


nested classes are known as inner classes.
o Non-static nested class (inner class)
1 Member inner class
2 Anonymous inner class
3 Local inner class
o Static nested class
Type Description

Member Inner A class created within class and outside


Class method.

Anonymous A class created for implementing interface or


Inner Class extending class. Its name is decided by the
java compiler.

Local Inner A class created within method.


Class

Static Nested A static class created within class.


Class

Nested An interface created within class or


Interface interface.

Java Member inner class example


In this example, we are creating msg() method in member inner class that is accessing
the private data member of outer class.

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.

Java Anonymous inner class


A class that have no name is known as anonymous inner class in java. It should be used
if you have to override method of class or interface. Java Anonymous inner class can be
created by two ways:

1 Class (may be abstract or concrete).


2 Interface

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

Java Local inner class


A class i.e. created inside a method is called local inner class in java. If you want to
invoke the methods of local inner class, you must instantiate this class inside the
method.

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

Java static nested class


A static class i.e. created inside a class is called static nested class in java. It cannot
access non-static data members and methods. It can be accessed by outer class name.

o It can access static data members of outer class including private.


o Static nested class cannot access non-static (instance) data member or method.

Java static nested class example with instance


method
1 class TestOuter1{  
2   static int data=30;  
3   static class Inner{  
4    void msg(){System.out.println("data is "+data);}  
5   }  
6   public static void main(String args[]){  
7   TestOuter1.Inner obj=new TestOuter1.Inner();  
8   obj.msg();  
9   }  
10 }  
11 data is 30

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.

Java static nested class example with static method


If you have the static member inside static nested class, you don't need to create
instance of static nested class.

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

Java Nested Interface


An interface i.e. declared within another interface or class is known as nested interface.
The nested interfaces are used to group related interfaces so that they can be easy to
maintain. The nested interface must be referred by the outer interface or class. It can't
be accessed directly.

Points to remember for nested interfaces


There are given some points that should be remembered by the java programmer.

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.

Example of nested interface which is declared within the


interface

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:

Why Java main method is public?


main method is public so that it can be accessible everywhere and to every object
which may desire to use it for launching the application. 

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).

Why Java main method is static?


Java can have overloaded constructors, we all know. Now, which one should be used
and from where the parameters for overloaded constructors will come. These are just
more difficult questions, which helped Java designers to make up their mind and to have the
main method as static.

Why Java main method is void?


Why should it not be void? Have you called this method from your code? NO. Then
there is no use of returning any value to JVM, who actually invokes this
method. It simply doesn’t need any returning value.

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.

Why the name is main?


No rock solid reason. Lets assume because it was already in use with C and C++
language. So, most developers were already comfortable with this name. 
What happens internally when you invoke main
method?
First, JVM executes the static block, then it executes static methods, and then it creates
the object needed by the program. Finally, it executes the instance methods. JVM
executes a static block on the highest priority basis. It means JVM first goes to static
block even before it looks for the main() method in the program.

Do we always need main method to run java


program?
The answer should be Yes. You might have noticed that Java applets do not have main() but
run on browsers.

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:

 The Java Virtual Machine first loads your class


 Then it arranges and runs all static blocks
 Then finally stare across your code for main() and uses it

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:

Integral Data Types


An integral data type is a numeric data type whose values are integers. Java
offers five integral data types: byte, short, int, long, and char.

1.1. int data type

 The int data type is a 32-bit signed Java primitive data type. A variable of


the int data type takes 32 bits of memory.
 Its valid range is -2,147,483,648 to 2,147,483,647 (-231 to 231– 1).
 All whole numbers in this range are known as integer literals (or integer constants).
For example, 10, -200, 0, 30, 19, etc. are integer literals of int.

An integer literal can be assigned to an int variable, say counter, like so:


int counter = 21;

Integer Wrapper Class

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

int min = Integer.MIN_VALUE; // Assigns minimum int value to min

1.2. long data type

 The long data type is a 64-bit signed Java primitive data type.


 It is used when the result of calculations on whole numbers may exceed the range of the int data type.
 Its range is -263 to 263 – 1.
 All whole numbers in the range of long are called integer literals of long type.

An integer literal of type long always ends with ‘L’ (or lowercase ‘l’).
long num1 = 0L;

long num2 = 401L;

long mum3 = -3556L;

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.

Long Wrapper Class

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;

long min = Long.MIN_VALUE;

1.3. byte data type

 The byte data type is an 8-bit signed Java primitive integer data type.


 Its range is -128 to 127 (-27 to 27 – 1). This is the smallest integer data type available
in Java.
 Unlike int and long literals, there are no byte literals.
 However, you can assign any int literal that falls in the range of byte to a byte variable.

byte b1 = 125;
byte b2 = -11;

Byte Wrapper Class

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;

byte min = Byte.MIN_VALUE;

short data type

  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;

short min = Short.MIN_VALUE;

char data type

 The char data type is a 16-bit unsigned Java primitive data type.


 It represents a Unicode character.
 Note that char is an unsigned data type. Therefore, a char variable cannot have a
negative value.
 The range of the char data type is 0 to 65535, which is the same as the range of the
Unicode set.
 A character literal represents a value of the char data type.

char c1 = 'A';
char c2 = 'L';

char c3 = '5';

char c4 = '/';

1.5.1. Character escape sequences

A character literal can also be expressed as a character escape sequence. A


character escape sequence starts with a backslash immediately followed by a
character, and both are enclosed in single quotes.

There are eight predefined character escape sequences as listed below:

CHARACTER ESCAPE SEQUENCE DESCRIPTION

‘\n’ A linefeed

‘\r’ A carriage return


‘\f’ A form feed

‘\b’ A backspace

‘\t’ A tab

‘\\’ A backslash

‘\”‘ A double quote

‘\” A single quote

These are only eight character escape sequences in Java. You cannot define your own
character escape sequences.

1.5.2. Unicode escape sequence

A character literal can also be expressed as a Unicode escape sequence in the


form '\uxxxx', Here, \u (a backslash immediately followed by a lowercase u) denotes
the start of the Unicode escape sequence, and xxxx represents exactly four
hexadecimal digits.
char c1 = 'A';

char c2 = '\u0041';  // Same as c2 = 'A'

float data type

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;

2.2. double data type

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.

The type wrappers classes are part of java.lang package.

Each primitive type has a corresponding wrapper class.

Primtive Type Wrapper Class

double Double

float Float
long Long

int Integer

short Short

byte Byte

char Character

boolean Boolean

1.When to use wrapper classes


Java wrapper classes are used in scenarios –

 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.

2. Primitive type to wrapper class

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

Integer anotherObject = Integer.valueOf(10);

3. Wrapper class to primitive type

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)

Autoboxing is the automatic conversion of the primitive types into their


corresponding object wrapper classes. For example, converting an int to an Integer,
a char to a Character, and so on.

We can simply pass or assign a primitive type to an argument or reference accepting


wrapper class object. e.g.
Character ch = 'a';     //char to Character
 
List<Integer> integerList = new ArrayList<>();
 
for (int i = 1; i < 10; i ++)
{
    integerList.add(i);     //int to Integer
}

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)

Unboxing happens when the conversion happens from wrapper class to its


corresponding primitive type. It means we can pass or assign a wrapper object to an
argument or reference accepting primitive type. e.g.
public static int sumOfEven(List<Integer> integerList)
{
    int sum = 0;
    for (Integer i: integerList) {
        if (i % 2 == 0)
            sum += i;           //Integer to int
    }
    return sum;
}

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 literals in string pool


String blogName1 = "howtodoinjava.com";
String blogName2 = "howtodoinjava.com";
String blogName3 = "howtodoinjava.com";
String blogName4 = "howtodoinjava.com";
String blogName5 = "howtodoinjava.com";

2 In above example, we created 5 string literals with same char sequence.


Inside JVM, there will be only one instance of String inside string pool. All
rest 4 instances will share the reference of string literal created for first literal.

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.

String object example


String blogName1 = new String("howtodoinjava.com");
String blogName2 = new String("howtodoinjava.com");
String blogName3 = new String("howtodoinjava.com");

In above example, there will be 3 separate instances of String with same value in
heap memory.

How many ways can we create the string object?


1) String Literal

Java String literal is created by using double quotes. For Example:

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).

153) How many objects will be created in the following code?


1 String s1="Welcome";  
2 String s2="Welcome";  
3 String s3="Welcome";  

Only one object will be created using the above code because strings in Java are
immutable.

More details.

154) Why java uses the concept of the string literal?


To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).

More details.

155) How many objects will be created in the following code?


1 String s = new String("Welcome");  

Two objects, one in string constant pool and other in non-pool(heap).

Java String Methods


1 char charAt(int index) – Returns the character at the specified index. Specified index
value should be between '0' to 'length() -1' both inclusive. It
throws IndexOutOfBoundsException if index is invalid/ out of range.

String blogName = "howtodoinjava.com";


         

char c = blogName.charAt(5);    //'d'


2 boolean equals(Object obj) – Compares the string with the specified string and
returns true if both matches else false.

String blogName = "howtodoinjava.com";


         

blogName.equals( "howtodoinjava.com" );     //true

blogName.equals( "example.com" );           //false

3 boolean equalsIgnoreCase(String string) – Compares same as equals method but


in case insensitive way.

String blogName = "howtodoinjava.com";


         

blogName.equalsIgnoreCase( "howtodoinjava.com" );       //true

blogName.equalsIgnoreCase( "HowToDoInJava.com" );       //true

4 int compareTo(String string) – Compares the two strings lexicographically based on


the Unicode value of each character in the strings. You can consider it dictionary based
comparison.

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";

         

blogName.compareTo( "HowToDoInJava.com" );      //32

blogName.compareTo( "example.com" );            //3

5 int compareToIgnoreCase(String string) – Same as CompareTo method however it


ignores the case during comparison.

String blogName = "howtodoinjava.com";


         

blogName.compareToIgnoreCase( "HowToDoInJava.com" );        //0

blogName.compareToIgnoreCase( "example.com" );              //3

6 boolean startsWith(String prefix, int offset) – Checks whether the String is having
the specified prefix or not – starting from the specified offset index.

String blogName = "howtodoinjava.com";


 
blogName.startsWith( "d", 5 );      //true
blogName.startsWith( "e", 5 );      //false

7 boolean startsWith(String prefix) – Tests whether the string is having


specified prefix, if yes then it returns true else false. The offset index value is 0 in
this overloaded method.

String blogName = "howtodoinjava.com";


 
blogName.startsWith( "h" );     //true

blogName.startsWith( "e" );     //false

8 boolean endsWith(String suffix) – Checks whether the string ends with the specified
suffix.

String blogName = "howtodoinjava.com";


 
blogName.endsWith( "com" );         //true

blogName.endsWith( "java" );        //false

9 int hashCode() – Returns the hash code of the string.

String blogName = "howtodoinjava.com";


 
blogName.hashCode();            //1894145264

10 int indexOf(int ch) – Returns the index of first occurrence of the specified character
argument in the string.

String blogName = "howtodoinjava.com";


 
blogName.indexOf( 'o' );            //1

11 int indexOf(int ch, int fromIndex) – Overloaded version of indexOf(char


ch) method however it starts searching in the string from the specified fromIndex.

String blogName = "howtodoinjava.com";


 
blogName.indexOf( 'o', 5 );     //6

12 int indexOf(String str) – Returns the index of first occurrence of specified


substring 'str'.

String blogName = "howtodoinjava.com";


 
blogName.indexOf( "java" );         //9
13 int indexOf(String str, int fromIndex) – Overloaded version of indexOf(String
str) method however it starts searching in the string from the specified fromIndex.

String blogName = "howtodoinjava.com";


 
blogName.indexOf( "java" , 5);          //9

14 int lastIndexOf(int ch) – Returns the last occurrence of the character 'ch' in the
string.

String blogName = "howtodoinjava.com";


 
blogName.lastIndexOf( 'o' );            //15

15 int lastIndexOf(int ch, int fromIndex) – Overloaded version of lastIndexOf(int


ch) method. It starts searching backward starting at the fromIndex.

String blogName = "howtodoinjava.com";


 
blogName.lastIndexOf( 'o', 5 );         //4

16 int lastIndexOf(String str) – Returns the index of last occurrence of string 'str'. It is


similar to lastIndexOf(int ch).

String blogName = "howtodoinjava.com";


 
blogName.lastIndexOf( "java" );         //9

17 int lastIndexOf(String str, int fromIndex) – Overloaded version


of lastIndexOf(String str) method. It starts searching backward starting at
the fromIndex.

String blogName = "howtodoinjava.com";


 
blogName.lastIndexOf( "java", 6 );          //9

18 String substring(int beginIndex) – Returns the substring of the string. The substring
starts with the character at the specified index.

String blogName = "howtodoinjava.com";


 
blogName.substring( 7 );        //injava.com

19 String substring(int beginIndex, int endIndex)  – Returns the substring. The


substring starts with character at beginIndex and ends with the character at endIndex.

String blogName = "howtodoinjava.com";


 
blogName.substring( 7, 9 );     //in

20 String concat(String str) – Concatenates the specified string argument at the end of
the string.

String blogName = "howtodoinjava.com";


 
blogName.concat( " Hello Visitor !!" );     //howtodoinjava.com Hello Visitor !!

21 String replace(char oldChar, char newChar) – Returns the new updated string after
changing all the occurrences of oldChar with the newChar arguments.

String blogName = "howtodoinjava.com";


 
blogName.replace( 'o', 'O' );       //hOwtOdOinjava.cOm

22 String replace(String target, String replacement)  – Returns the new updated string
after changing all the occurrences of target with the replacement argument.

String blogName = "howtodoinjava.com";


 
blogName.replace( "com", "COM" );       //howtodoinjava.COM

23 String replaceFirst(String regex, String replacement)  – Replaces the first occurrence


of substring that matches the given regular expression argument with the specified
replacement string.

String blogName = "howtodoinjava.com";


 
blogName.replaceFirst("how", "HOW");        //HOWtodoinjava.com

24 String replaceAll(String regex, String replacement)  – Replaces all the occurrences


of substrings that matches the regular expression argument with the replacement
string.
25 String[] split(String regex, int limit) – Splits the string and returns the array of sub-
strings that matches the given regular expression. 'limit' is a maximum number of
elements in array.

String blogName = "howtodoinjava.com";


 
blogName.split("o", 3);     //[h, wt, doinjava.com]

26 String[] split(String regex) – Overload of previous method without any threshold


limit.
27 boolean contains(CharSequence s) – Checks whether the string contains the
specified sequence of char values. If yes then it returns true else false. It
throws NullPointerException if argument is null.

String blogName = "howtodoinjava.com";


 
blogName.contains( "java" );        //true

blogName.contains( "python" );      //false

28 String toUpperCase(Locale locale) – Converts the string to upper case string using
the rules defined by specified locale.

String blogName = "howtodoinjava.com";


 
blogName.toUpperCase( Locale.getDefault() );        //HOWTODOINJAVA.COM

29 String toUpperCase() – Overloaded version of previous toUpperCase() method with


default locale.
30 String toLowerCase(Locale locale) – Converts the string to lower case string using
the rules defined by given locale.
31 String toLowerCase() – Overloaded version of previous method with default locale.
32 String intern() – Searches the specified string in the memory pool and if it is found
then it returns the reference of it. Otherwise this method allocates creates string literal
in string pool and return the reference.

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.

String blogName = "howtodoinjava.com";


 
blogName.isEmpty();     //false

"".isEmpty();           //true

34 static String join() – Joins the given strings using the specified delimiter and returns
the concatenated Java String literal.

String.join("-", "how","to", "do", "in", "java")        //how-to-do-in-java

35 static String format() – Returns a formatted string.

public class FormatExample{

public static void main(String args[]){

String name="sonoo";

String sf1=String.format("name is %s",name);

String sf2=String.format("value is %f",32.33434);

String sf3=String.format("value is %32.12f",32.33434);//returns 12 char


fractional part filling with 0

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.

public class StringTrimExample{

public static void main(String args[]){

String s1=" hello string ";


System.out.println(s1+"javatpoint");//without trim()

System.out.println(s1.trim()+"javatpoint");//with trim()

}}

op

hello string javatpoint

hello stringjavatpoint

eg2:

public class StringTrimExample {

public static void main(String[] args) {

String s1 =" hello java string ";

System.out.println(s1.length());

System.out.println(s1); //Without trim()

String tr = s1.trim();

System.out.println(tr.length());

System.out.println(tr); //With trim()

22

hello java string

17

hello java string

37 char[] toCharArray() – Converts the string to a character array.


38 static String copyValueOf(char[] data) – Returns a string that contains the characters of
the specified character array.

char[] chars = new char[] {'h','o','w'};


 
String.copyValueOf(chars);      //how

39 byte[] getBytes(String charsetName) – Converts the String into sequence of bytes


using the specified charset encoding.
40 byte[] getBytes() – Overloaded version of previous method. It uses the default
charset encoding.
41 int length() – Returns the length of a String.
42 boolean matches(String regex) – Validates whether the String is matching with the
specified regular expression argument.
43 int codePointAt(int index) – It is similar to the charAt() method. It returns the
Unicode code point value of specified index rather than the character itself.
44 static String copyValueOf(char[] data, int offset, int count) – Overloaded version of
previous method with two extra arguments – initial offset of subarray and length of
subarray. It selects characters from array based on extra arguments,and then create
the string.
45 void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin) – Copies the
characters of src array to the dest array. Only the specified range is being
copied(srcBegin to srcEnd) to the dest subarray(starting fromdestBegin).
46 static String valueOf() – Returns a string representation of passed arguments such as
int, long, float, double, char and char array.
47 boolean contentEquals(StringBuffer sb) – Compares the string to the specified
string buffer.
48 boolean regionMatches(int srcoffset, String dest, int destoffset, int len) –
Compares the substring of input to the substring of specified string.
49 boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int
destoffset, int len) – Another variation of regionMatches method with the extra
boolean argument to specify whether the comparison is case sensitive or case
insensitive.

HASHCODE:
It provides memory identification number which is gn by JVM with out checking the content.

EG 1:

Class Test{

Int sid;

String str;

Public static void main(String a[]){


Test t=new Test();

System.out.print(“t ”+t);

O:p t Test@some address (class name @ some add)

E g 2:

Class Test{

Int sid;

String str;

Test(int data,String name){

This.sid=sid;

This.str=name;

//@override

Public String toString(){

Return sid+” “+str;

}//o;p 101 ram

Public static void main(String a[]){

Test t=new Test(101,”ram”);

Test t1=new Test(101,”ram”);

Test t2=new Test(102,”ram”);

System.out.print(“t ”+t); //o;p 101 ram

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

System.out.print(“t2 ”+t2.hashCode());// op: 65645234

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;

Test(int data,String name){

This.sid=sid;

This.str=name;

//@override

Public String toString(){

Return sid+” “+str;

//override (for generating correct id num)

Public int hashCode(){

Return sid+str.hashCode();

//r a m

// 2 1 0(powers)

//114*(31) 97*(31) 109*31

//112771

//override equals

Public Boolean equals(Object obj){

Test tst=(test)obj;// downcasting

If(this.sid==tst.sid && this.str.equals(tst.str)){ // this.sid is t1.sid and tst.sid is t2.sid


Return true;

Else{

Return false;

Public static void main(String a[]){

Test t=new Test(101,”ram”);

Test t1=new Test(101,”ram”);


Test t2=new Test(102,”ram”);

System.out.print(“t ”+t);

System.out.print(“t1 ”+t1.hashCode());//112771

System.out.print(“t2 ”+t2.hashCode());//112771

System.out.print(“before overridden of equals);

System.out.print(“whether the two values are same in the two objects”+t1.equals(t2));

// 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.

//In order to overcome that OVERRIDE the equals method.

System.out.print(“after overridden of equals);

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)

2.int to String: String.valueOf(int) and Integer.toString(int);

3.string to char: string.toCharAt(index) and string.toCharArray()

4.char to string: string.valueOf(char) and Character.toString(char)

5.string to date: Date new_date=new SimpleDateFormat(“dd/mm/yyyy”).parse(string)

6.date to string: string str= dateFormat.format(date)

7.string to object: Object obj=string

i)string to class object:

Class c=Class.forName("java.lang.String");

System.out.println("class name: "+c.getName()); //java.lang.String

System.out.println("super class name: "+c.getSuperclass().getName()); //java.lang.Object

8.object to string: Main m=new Main()  string.valueOf(m) and m.toString()

9.string builder and buffer to stirng: sb.toString()

10.long to string : Long.toString() and String.valueOf(long)

11.string to long: Long.parseLong(string)

12.int to long
i)long=int and Long =Long.valueof(int)

13.long to int

i)int =(int)long and int= l(var).intValue()

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:");

StringBuffer sb=new StringBuffer("java");

System.out.println(sb.hashCode());

sb.append("tpoint");

System.out.println(sb.hashCode());

Hashcode test of StringBuffer:

118352462

118352462

STRING BUILDER(NON SYNCHRONIZED):


Java StringBuilder class is used to create mutable (modifiable) string. The Java
StringBuilder class is same as StringBuffer class except that it is non-synchronized.

The StringBuilder class is introduced since JDK 1.5.

OPERATION METHODS ARE SAME

No. StringBuffer StringBuilder

1 StringBuffer is synchronized i.e. StringBuilder is non-synchronized i.e.


) thread safe. It means two threads not thread safe. It means two threads
can't call the methods of StringBuffer can call the methods of StringBuilder
simultaneously. simultaneously.

2 StringBuffer is less efficient than StringBuilder is more efficient than


) StringBuilder. StringBuffer.

STRING TOKENIZER:

The java.util.StringTokenizer class allows you to break a string into tokens. It is


simple way to break string.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc.

Constructor Description

StringTokenizer(String str) creates StringTokenizer with specified string.

StringTokenizer(String str, creates StringTokenizer with specified string and


String delim) delimeter.

StringTokenizer(String str, creates StringTokenizer with specified string,


String delim, boolean delimeter and returnValue. If return value is true,
returnValue) delimiter characters are considered to be tokens.
If it is false, delimiter characters serve to
separate tokens.

Public method Description

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

String nextToken() returns the next token from the StringTokenizer


object.

String nextToken(String returns the next token based on the delimeter.


delim)

boolean hasMoreElements() same as hasMoreTokens() method.

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


int countTokens() returns the total number of tokens.

StringTokenizer class is deprecated now. It is


recommended to use split() method of String
class or regex (Regular Expression).
Why CharArray() is preferred over String to store the
password?
String stays in the string pool until the garbage is collected. If we store the password
into a string, it stays in the memory for a longer period, and anyone having the
memory-dump can extract the password as clear text. On the other hand, Using
CharArray allows us to set it to blank whenever we are done with the password. It avoids
the security threat with the string by enabling us to control the memory.

How to create immutable class in Java:


An immutable class is one whose state can not be changed once created.

RULES:

1.Don’t provide “setter” methods(BCZ IT WILL CHANGE THE PROPERTY)

2. Make all fields final and private

3.Don’t allow subclasses to override methods

4. Special attention when having mutable instance variables

Always remember that your instance variables will be either mutable or immutable.


Identify them and return new objects with copied content for all mutable objects.
Immutable variables can be returned safely without extra effort.

A more sophisticated approach is to make the constructor private and construct


instances in factory methods.

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 }  

The above class is immutable because:

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.

These points makes this class as immutable.

Immutable classes in JDK

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

Benefits of making a class immutable


Lets first identify advantages of immutable class. In Java, immutable classes are:
1 are simple to construct, test, and use
2 are automatically thread-safe and have no synchronization issues
3 do not need a copy constructor
4 do not need an implementation of clone

Object-Oriented Programming (OOPs) Concept

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)

Eg:dynamic polymorphism(same name


RUN TIME POLYMORPHISM OR DYNAMIC
METHOD DISPATCH:
Method overriding is one of the ways in which Java supports Runtime Polymorphism.
Dynamic method dispatch is the mechanism by which a call to an overridden method
is resolved at run time, rather than compile time.
 When an overridden method is called through a superclass reference, Java
determines which version(superclass/subclasses) of that method is to be
executed based upon the type of the object being referred to at the time the call
occurs. Thus, this determination is made at run time.
 At run-time, it depends on the type of the object being referred to (not the type
of the reference variable) that determines which version of an overridden
method will be executed
 A superclass reference variable can refer to a subclass object. This is also
known as upcasting. Java uses this fact to resolve calls to overridden methods
at run time.
class A
{
    void m1()
    {
        System.out.println("Inside A's m1 method");
    }
}
  
class B extends A
{
    // overriding m1()
    void m1()
    {
        System.out.println("Inside B's m1 method");
    }
}
  
class C extends A
{
    // overriding m1()
    void m1()
    {
        System.out.println("Inside C's m1 method");
    }
}
  
// Driver class
class Dispatch
{
    public static void main(String args[])
    {
        // object of type A
        A a = new A();
  
        // object of type B
        B b = new B();
  
        // object of type C
        C c = new C();
  
        // obtain a reference of type A
        A ref;
          
        // ref refers to an A object
        ref = a;
  
        // calling A's version of m1()
        ref.m1();
  
        // now ref refers to a B object
        ref = b;
  
        // calling B's version of m1()
        ref.m1();
  
        // now ref refers to a C object
        ref = c;
  
        // calling C's version of m1()
        ref.m1();
    }
}
Output:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method

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.

In Java, there are two ways to achieve the abstraction.

o Abstract Class
o Interface

It is achieved through interface and abstract(implicit person in real life) class

Best eg is hashMap or hashset;

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

abstract class Animal {

// Abstract method (does not have a body)


public abstract void animalSound();//NOTE SEE BELOW

// Regular method

public void sleep() {

System.out.println("Zzz");

// Subclass (inherit from Animal)

class Pig extends Animal {

public void animalSound() {

// The body of animalSound() is provided here

System.out.println("The pig says: wee wee");

class MyMainClass {

public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound();//NOTE:HERE THE CHILD CLASS IS RESPONSIBLE FOR


IMPLEMENTATION OF THE animalSound(), yet WHEN WE COMMENT THE ABSTRACT
METHOD IN PARENT CLASS THE CHILD CLASS MAY OR MAY NOT PROVIDE
IMPLEMENTATION.THE MAIN ADVANTAGE OF ABSTRACTION IS WHEN THE ABSTRACT
METHOD IS DECLARED IN ABSTRACT METHOD THEN THE CHILD CLASS IS
RESPONSIBLE FOR IMPLEMENTATION OF THE ABSTRACT METHOD.

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

Can an Abstract class be final in Java?

No, an abstract class cannot be declared as final in Java. Because it will


completely negate the purpose of an abstract class. An abstract class should be
extended to create instances. If it is declared final, then it cannot be extended
and so an abstract class cannot be declared as final.
5. Inheritance(IS-A relationship)
In the concept of inheritance, one object acquires all the properties and behaviours
of another object. Using this concept code can be reused. Inheritance is used to
provide runtime polymorphism. Following are the important terminologies used:
i. Super Class
A superclass is the parent class or base class whose features can be inherited.
ii. Sub Class
A subclass is an intermediate class also known as a derived class, extended class or
child class. It can inherit the superclass using the extend keyword.

Purpose of Inheritance
1 It promotes the code reusabilty i.e the same methods and variables which are

defined in a parent/super/base class can be used in the child/sub/derived class.

2 It promotes polymorphism by allowing method overriding.

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.

Simple example of Inheritance


Before moving ahead let's take a quick example and try to understand the concept of
Inheritance better,
class Parent

public void p1()

System.out.println("Parent method");
}

public class Child extends Parent {

public void c1()

System.out.println("Child method");

public static void main(String[] args)

Child cobj = new Child();

cobj.c1(); //method of Child class

cobj.p1(); //method of Parent class

Child method

Parent method

Types of Inheritance
1 Single Inheritance

2 Multilevel Inheritance

3 Heirarchical Inheritance

NOTE: Multiple inheritance is not supported in java


Why multiple inheritance is not supported in Java?

 To remove ambiguity.

 To provide more maintainable and clear design.

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;

public class Child extends Parent {

String name;

public void details()

super.name = "Parent"; //refers to parent class member

name = "Child";

System.out.println(super.name+" and "+name);

public static void main(String[] args)

Child cobj = new Child();


cobj.details();

Parent and Child

Example of Child class refering Parent class methods


using super keyword
In this examle we will only focus on accessing the parent class methods.
class Parent

String name;

public void details()

name = "Parent";

System.out.println(name);

public class Child extends Parent {

String name;

public void details()

super.details(); //calling Parent class details() method

name = "Child";

System.out.println(name);

public static void main(String[] args)

Child cobj = new Child();

cobj.details();
}

Parent

Child

Example of Child class calling Parent


class constructor using super keyword
In this examle we will focus on accessing the parent class constructor.
class Parent

String name;

public Parent(String n)

name = n;

public class Child extends Parent {

String name;

public Child(String n1, String n2)

super(n1); //passing argument to parent class constructor

this.name = n2;

public void details()

System.out.println(super.name+" and "+name);

}
public static void main(String[] args)

Child cobj = new Child("Parent","Child");

cobj.details();

Parent and Child

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.

Super class reference pointing to Sub class object


In context to above example where Class B extends Class A.
A a = new B();

The above code is legal syntax because of IS-A relationship is there between class
A and Class B.

Q. Can you use both this() and super() in a Constructor?


NO, because both super() and this() must be first statement inside a constructor.
Hence we cannot use them together.

MULTIPLE INHERITANCE USING INTERFACE:


As we have long learned the fact that multiple inheritance  is not directly supported in Java,
well that was only till Java 7. In Java 8, we can realize the concept of multiple
inheritance through use of default methods without getting into diamond
problem(MULTIPLE INHERITANCE).

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 !!");
    }
}

If all classes implementing Moveable interface do not need change themselves (until


some class specifically wants to override moveFast() method to add custom logic).
All classes can directly call instance.moveFast() method.

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();
    }
}

Possible conflicts during mutiple inheritance


package com.howtodoinjava.examples;
 
interface Moveable
{
    default void run(){
        System.out.println("I am running, kid !!");
    }
}
  
interface Crawlable
{
    default void run(){
        System.out.println("I am running, daddy !!");
    }
}
  
public class Animal implements Moveable, Crawlable
{
    public static void main(String[] args)
    {
        Animal self = new Animal();
 
        //What will happen when below statement will execute
        //self.run();
    }
}

So solve above conflict, caller class must decide which run() method it want to


invoke and then call using interface’s reference like below.
Moveable.super.run();   //Call Moveable's run() method
 
//or
 
Crawlable.super.run();  //Call Crawlable's run() method

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;

//Getter and Setter methods


public int getEmpSSN(){
return ssn;
}

public String getEmpName(){


return empName;
}

public int getEmpAge(){


return empAge;
}

public void setEmpAge(int newValue){


empAge = newValue;
}
public void setEmpName(String newValue){
empName = newValue;
}

public void setEmpSSN(int newValue){


ssn = newValue;
}
}
public class EncapsTest{
public static void main(String args[]){
EncapsulationDemo obj = new EncapsulationDemo();
obj.setEmpName("Mario");
obj.setEmpAge(32);
obj.setEmpSSN(112233);
System.out.println("Employee Name: " + obj.getEmpName());
System.out.println("Employee SSN: " + obj.getEmpSSN());
System.out.println("Employee Age: " + obj.getEmpAge());
}
}
Output:

Employee Name: Mario


Employee SSN: 112233
Employee Age: 32

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.

An interface is a completely "abstract class" that is used to group related


methods with empty bodies:

Why And When To Use Interfaces?


1) To achieve security - hide certain details and only show the important
details of an object (interface).

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).

We can't create object of interfaces because of the reason that : Interface is


basically a complete abstract class. ... So if we don't have any implementation of a
method then that means if we create object of that interface and call that method it
compile nothing as there is no code to compile.

Can an interface have a constructor?


This is a most frequently asked java interview question. The answer is
No, interface cannot have constructors. ... In order to call any method we need an
object since there is no need to have object of interface, there is no need of
having constructor in interface (Constructor is being called during creation of
object).
When can an object reference be cast to an interface
reference?
An object reference can be cast to an interface reference when the object implements
the referenced interface.Eg:List names=new ArrayList<>();

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 {

public void animalSound(); // interface method (does not have a body)

public void run(); // interface method (does not have a body)

To access the interface methods, the interface must be "implemented" (kinda


like inherited) by another class with the implements keyword (instead
of extends). The body of the interface method is provided by the
"implement" class:

Example
// Interface

interface Animal {

public void animalSound(); // interface method (does not have a body)

public void sleep(); // interface method (does not have a body)

}
// Pig "implements" the Animal interface

class Pig implements Animal {

public void animalSound() {

// The body of animalSound() is provided here

System.out.println("The pig says: wee wee");

public void sleep() {

// The body of sleep() is provided here

System.out.println("Zzz");

class MyMainClass {

public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

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 {

public void myOtherMethod(); // interface method

class DemoClass implements FirstInterface, SecondInterface {

public void myMethod() {

System.out.println("Some text..");

public void myOtherMethod() {

System.out.println("Some other text...");

class MyMainClass {

public static void main(String[] args) {

DemoClass myObj = new DemoClass();

myObj.myMethod();

myObj.myOtherMethod();

Abstract class implementing interface:

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.

Interface is absolutely abstract and cannot be instantiated; A Java abstract class also


cannot be instantiated, but can be invoked if a main() exists.

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. 

Can an abstract class implement an interface?

In Java, an abstract class can implement an interface, and not provide


implementations of all of the interface's methods. It is the responsibility of the first
concrete class that has that abstract class as an ancestor to implement all of the
methods in the interface.

Can abstract class inherit interface?

An abstract class defines the identity of a class. An interface can


inherit multiple interfaces but cannot inherit a class. An abstract class can
inherit a class and multiple interfaces
9.Java extends vs implements keywords:

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.

Take the example of ArrayList class. It extends AbstractList class which in turn


extends AbstractCollection class.

So essentially ArrayList class has methods and behaviors of both it’s parent classes
AbstractList and AbstractCollection.

AbstractCollection provides methods like contains(Object o), toArray(),


remove(Object o) etc. While AbstractList class provides add(), indexOf(), lastIndexOf(),
clear() etc. Some of the methods are overridden by ArrayList again.

ArrayList.java
public class ArrayList<E> extends AbstractList<E>

        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

    //code

Java extends example

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 {

     

    public int dataVal = 100;

     

    public int getDataVal() {

        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

    public static void main(String[] args)

    {

        ChildClass child = new ChildClass();

         

        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.

Java implements example

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.

A class Human implement both interfaces so it MUST implement the methods defined


in both interfaces.

Movable.java
public interface Movable {

     

    public void move();

Swimmable.java
public interface Swimmable

    public void swim();

Human.java
public class Human implements Movable, Swimmable

    @Override

    public void swim() {

        System.out.println("I am swimming");

    }

 
    @Override

    public void move() {

        System.out.println("I am moving");

    }

}
Now we will test the human class and it’s enforced behavior.

Main.java
public class Main

    public static void main(String[] args)

    {

        Human obj = new Human();

         

        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.

3. Differences between extends vs implements


Based on above examples, let’s list down the differences between extends and
implements keywords 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.

Note: Java instanceof operator (also called type comparison operator) is used to test


whether the object is an instance of the specified type (class or subclass or interface).

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

THE HAS A RELATION IS COMMONLY USED THAN THE IS A RELATIONSHIP.

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.

It is represented by a line between the classes followed by an arrow that navigates


the direction, and when the arrow is on both sides, it is then called a bidirectional
association. We can specify the multiplicity of an association by adding the
adornments on the line that will denote the association.

Example:

1) A single teacher has multiple students.


2) A single student can associate with many teachers.

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.

2 call-by-reference : In this reference of an argument is pass to a method. Any

changes made inside the method will affect the agrument value.

NOTE :There is only call by value in java, not call by reference.

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

Method Overriding in Java


When a method in a sub class has same name, same number of arguments and
same type signature as a method in its super class, then the method is known as
overridden method. Method overriding is also referred to as runtime polymorphism.
The key benefit of overriding is the abitility to define method that's specific to a
particular subclass type.
private, static and final methods can not be overridden in java

Example of Method Overriding


Below we have simple code example with one parent class and one child class
wherein the child class will override the method definition provided by the parent
class.
class Animal

public void eat()

System.out.println("Generic Animal eating");

class Dog extends Animal

public void eat() //eat() method overriden by Dog class.

System.out.println("Dog eat meat");

As you can see here Dog class gives it own implementation of eat() method. For


method overriding, the method must have same name and same type signature in
both parent and child class.
NOTE: Static methods cannot be overridden because, a static method is
bounded with class where as instance method is bounded with object.

Can we change the scope of the overridden method in the


subclass?
Yes, we can change the scope of the overridden method in the subclass. However, we
must notice that we cannot decrease the accessibility of the method. The following point
must be taken care of while changing the accessibility of the method.

o The private can be changed to protected, public, or default.


o The protected can be changed to public or default.
o The default can be changed to public.
o The public will always remain public.

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.

o If the superclass method does not declare an exception, subclass overridden


method cannot declare the checked exception, but it can declare the unchecked
exception.
o If the superclass method declares an exception, subclass overridden method can
declare same, subclass exception or no exception but cannot declare parent
exception.

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.

Covariant return type


Since Java 5, it is possible to override a method by changing its return type. If
subclass override any method by changing the return type of super class method,
then the return type of overriden method must be subtype of return type declared
in original method inside the super class. This is the only way by which method can
be overriden by changing its return type.
Example :
class Animal

Animal myType()

return new Animal();

class Dog extends Animal

Dog myType() //Legal override after Java5 onward

return new Dog();


}

Covariant another example

What is covariant return type?


Now, since java5, it is possible to override any method by changing the return type if the
return type of the subclass overriding method is subclass type. It is known as covariant
return type. The covariant return type specifies that the return type may vary in the
same direction as the subclass.

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

Another example of overloading:

class Calculating {

public int AddNum(int var1, int var2){

return var1 + var2;

public double AddNum(double var1, double var2){

return var1 + var2;

}
}

Calculating calc = new 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{

public void making_sound(){

//which animal so no sound

System.out.println("*silence*");

class Dog extends Animal{

public void making_sound(){

System.out.println("Wouf!");

}}

//Outputs Wouf!

class Cat extends Animal{


public void making_sound(){

System.out.println( "Meov!");

}}

//Outputs Meov!

Dog bobby = new Dog();

Cat lemis = new Cat();

Animal prototype = new Animal();

bobby.making_sound();//outout wouf!

lemis.making_sound();//output meov!

prototype.making_sound();//silence

Difference between Overloading and Overriding


Method overloading and Method overriding seems to be similar concepts but they
are not. Let's see some differences between both of them:

Method Overloading Method Overriding

Parameter must be different and name must Both name and parameter must be same.
be same.

Compile time polymorphism. Runtime polymorphism.

Increase readability of code. Increase reusability of code.


Method Overloading Method Overriding

Access specifier can be changed. Access specifier cannot be more restrictive than original
method(can be less restrictive).

It is Compiled Time Polymorphism. It is Run Time Polymorphism.

It is performed within a class It is performed between two classes using inheritance


relation.

It is performed between two classes using It requires always inheritance.


inheritance relation.

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

It uses static binding It uses the dynamic binding.

Access modifiers and Non-access modifiers Access modifiers and Non-access modifiers can not be
can be changed. changed.

It is code refinement technique. It is a code replacement technique.


Method Overloading Method Overriding

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

No restriction is Throws Clause. Restriction in only checked exception.

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 OverloadingDemo{ class Demo2{

static int add1(int x,int y){return x+y;} void a()

static int add1(int x,int y,int z){return {System.out.println("A");}}


x+y+z;}
class b extends c
}
{void a(){System.out.println("B”);}
Q. Can we Override static method? Explain with
reasons?
No, we cannot override static method. Because static method is bound to class
whereas method overriding is associated with object i.e at runtime.

Overriding equals method


Below is an example of the overriding equals method.
Example:

class Demo{

private double a, b;

public Demo(double a, double b) {

this.a = b;

this.a = b;

}
}

public class MethodDemo11{

public static void main(String[] args)

Demo obj1 = new Demo(25, 10);

Demo obj2 = new Demo(25, 10);

if (obj1 == obj2)

System.out.println("Values are Equal");

else

System.out.println("Values are Not Equal");

}
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()

1.can be used only in constructors

2.must be in first line of constructor

3.both cannot be used simultaneously

Types of Constructor
There are two types of constructors:

 Default Constructor(compiler will initialize DC when there any constructors and

the DC and user defined constructor cannot be simultaneously present in

same class).

i)the DC contain only one line it is super() and it calls the parent class

constructor.

ii)the DC has the modifier as same in the class modifier(private,public not

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.

Why do we Overload constructors?


Constuctor overloading is done to construct object in different ways.

Example of constructor overloading


class Cricketer
{
String name;
String team;
int age;
Cricketer () //default constructor.
{
name ="";
team ="";
age = 0;
}
Cricketer(String n, String t, int a) //constructor overloaded
{
name = n;
team = t;
age = a;
}
Cricketer (Cricketer ckt) //constructor similar to copy constructor of c++
{
name = ckt.name;
team = ckt.team;
age = ckt.age;
}
public String toString()
{
return "this is " + name + " of "+team;
}
}
Class test:
{
public static void main (String[] args)
{
Cricketer c1 = new Cricketer();
Cricketer c2 = new Cricketer("sachin", "India", 32);
Cricketer c3 = new Cricketer(c2 );
System.out.println(c2);
System.out.println(c3);
c1.name = "Virat";
c1.team= "India";
c1.age = 32;
System .out. print in (c1);
}
}

this is sachin of india

this is sachin of india

this is virat of india

Q What's the difference between constructors and normal methods?


Constructors must have the same name as the class and can not return a value.
They are only called once for a single object while regular methods could be called
many times and it can return a value or can be void.
Copy Constructor
In Java, to Create a Copy constructor, one object is copied to another object.
Arguments of copy constructor must object. There can be two types of copy
constructor i.e System Define or user defines. A system provides its own copy
constructor if no copy constructor is defined.
Example:
1 //Java program to initialize the values from one object to another  
2 class Student6{  
3     int id;  
4     String name;  
5     //constructor to initialize integer and string  
6     Student6(int i,String n){  
7     id = i;  
8     name = n;  
9     }  
10     //constructor to initialize another object  
11     Student6(Student6 s){  
12     id = s.id;  
13     name =s.name;  
14     }  
15     void display(){System.out.println(id+" "+name);}  
16    
17     public static void main(String args[]){  
18     Student6 s1 = new Student6(111,"Karan");  
19     Student6 s2 = new Student6(s1);  
20     s1.display();  
21     s2.display();  
22    }  
23 }  
Test it Now

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:

final class abc


{
private abc()
{}
public static void add(int a, int b)
{
int z = a+b;
System.out.println("Addition: "+z);
}
public static void sub(int x, int y)
{
int z = x-y;
System.out.println("Subtraction: "+z);
}

}
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:

// Java program to demonstrate implementation of Singleton

// pattern using private constructors.

import java.io.*;
class MySingleton

static MySingleton instance = null;

public int x = 10;

// private constructor can't be accessed outside the class

private MySingleton() { }

// Factory method to provide the users with instances

static public MySingleton getInstance()

if (instance == null)

instance = new MySingleton();

return instance;

// Driver Class

class Main

public static void main(String args[])

MySingleton a = MySingleton.getInstance();

MySingleton b = MySingleton.getInstance();

a.x = a.x + 10;

System.out.println("Value of a.x = " + a.x);


System.out.println("Value of b.x = " + b.x);

Op:

20

20

Constructor Inheritance & Overriding:


We know that generally the we override the methods when we inherit the classes but in
constructors the two properties is not applicable. But the overloading is allowed bcz it does not
require inheritance. For eg:

Class parent{

Parent(){

Class child extends 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.

Child c=new child(10);//valid

INTERFACE CANNOT HAVE CONSTRUCTOR:


CONSTRUCTOR CAN BE IN NORMAL CLASS AND ALSO IN ABSTRACT CLASS BUT NOT IN THE
INTERFACE BCZ ALL THE VARIABLE IN THE INTERFACE ARE BY DEFAULT STATIC FINAL SO WE CANNOT
INITIALIZE VALUE TO THAT.

RECURSIVE CONSTRUCTOR INVOCATION:


CONSIDER THE EG:

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”);

}}

PARENT AND CHILD CLASS CONSTRUCTOR:


Class p{

P(int i){

//1.overcome

P(){

Class child extends 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.

//to overcome this always write the no argument constructor as (1)

Java keyword’S:
Note : this() is different from this and also super() is diff from super

1. Java this keyword


 this keyword automatically holds the reference to current instance of a class.
It is very useful in scenarios where we are inheriting a method from parent
class into child class, and want to invoke method from child class specifically.
 IF A METHOD IS DECLARED AS STATIC AND IN THAT THIS AND SUPER
KEYWORDS ARE USED THEN COMPILER POPS ERROR THAT NONSTATIC KEYWORD
THIS CANNOT BE REFERENCE TO STATIC REF BCZ WHEN THIS IS USED TO
REFER THE CURRENT CLASS OBJECT AND IF THE METHOD IS STATIC THEN
THERE IS NO MEANING OF USING THIS.
Java this keyword
 this keyword is used to refer to current object.

 this is always a reference to the object on which method was invoked.

 this can be used to invoke current class constructor.

 this can be passed as an argument to another method.

1. Using ‘this’ keyword to refer current class instance variables


//Java code for using 'this' keyword to
//refer current class instance variables
class Test
{
    int a;
    int b;
      
    // Parameterized constructor
    Test(int a, int b)
    {
        this.a = a;
        this.b = b;
    }
  
    void display()
    {
        //Displaying value of variables a and b
        System.out.println("a = " + a + "  b = " + b);
    }
  
    public static void main(String[] args)
    {
        Test object = new Test(10, 20);
        object.display();
    }
}
 Output:
 a = 10 b = 20

2. Using this() to invoke current class constructor

// Java code for using this() to 


// invoke current class constructor
class Test
{
    int a;
    int b;
  
    //Default constructor
    Test()
    {  
        this(10, 20); //test(int a,int b)
        System.out.println("Inside  default constructor \n");
    }
      
    //Parameterized constructor
    Test(int a, int b)
    {
        this.a = a;
        this.b = b;
        System.out.println("Inside parameterized constructor");
    }
  
    public static void main(String[] args)
    {
        Test object = new Test();
    }
}
 Output:
 Inside parameterized constructor
 Inside default constructor

3. Using ‘this’ keyword to return the current class instance

//Java code for using 'this' keyword 


//to return the current class instance
class Test
{
    int a;
    int b;
  
    //Default constructor
    Test()
    {
        a = 10;
        b = 20;
    }
      
    //Method that returns current class instance
    Test get()
    {
        return this;//test()
    }
      
    //Displaying value of variables a and b
    void display()
    {
        System.out.println("a = " + a + "  b = " + b);
    }
  
    public static void main(String[] args)
    {
        Test object = new Test();
        object.get().display();
    }
}
 Output:
 a = 10 b = 20

4. Using ‘this’ keyword as method parameter


// Java code for using 'this' 
// keyword as method parameter
class Test
{
    int a;
    int b;
      
    // Default constructor
    Test()
    {
        a = 10;
        b = 20;
    }
      
    // Method that receives 'this' keyword as parameter
    void display(Test obj)
    {
        System.out.println("a = " + a + "  b = " + b);
    }
   
    // Method that returns current class instance
    void get()
    {
        display(this); //test()
    }
  
    public static void main(String[] args)
    {
        Test object = new Test();
        object.get();
    }
}
 Output:
 a = 10 b = 20

5. Using ‘this’ keyword to invoke current class method

// Java code for using this to invoke current 


// class method
class Test {
  
    void display()
    {
        // calling function show()
        this.show();
     
       System.out.println("Inside display function");
    }
      
    void show() {
        System.out.println("Inside show funcion");
    }
      
  
    public static void main(String args[]) {
        Test t1 = new Test();
        t1.display();
    }
}
 Output :
 Inside show funcion
 Inside display function

6. Using ‘this’ keyword as an argument in the constructor call


// Java code for using this as an argument in constructor
// call
// Class with object of Class B as its data member
class A
{
    B obj;
      
    // Parameterized constructor with object of B 
    // as a parameter
    A(B obj)
    {
        this.obj = obj;
         
     // calling display method of class B
        obj.display();
    }
      
}
  
class B
{
    int x = 5;
      
    // Default Contructor that create a object of A 
    // with passing this as an argument in the 
   // constructor
    B()
    {
        A obj = new A(this);
    }
      
    // method to show value of x 
    void display()
    {
        System.out.println("Value of x in Class B : " + x);
    }
      
    public static void main(String[] args) {
        B obj = new B();
    }
}
 Output :
 Value of x in Class B : 5

 this refer to current instance of a class while super refer to the parent


class of that class where super keyword is used.
 2. Java super keyword
 Similar to this keyword, super also is a reserved keyword in Java. It always
hold the reference to parent class of any given class.
 Used only in constructor.
 Using super keyword, we can access the fields and methods of parent class in
any child class.

3. Java this and super keyword example


 In this example, we have two
classes ParentClass and ChildClass where ChildClass extends ParentClass. I
have created a method showMyName() in parent class and override it child
class.
 Now when we try to invoke showMyName() method inside child class using this
and super keywords, it invokes the methods from current class and parent
class, respectively.

ParentClass.java
public class ParentClass

{  

    public void showMyName()

    {

        System.out.println("In ParentClass");

    }

ChildClass.java
public class ChildClass extends ParentClass

    public void showMyName()

    {

        System.out.println("In ChildClass");

    }

     

    public void test()


    {

        this.showMyName();

         

        super.showMyName();

    }

Main.java
public class Main

    public static void main(String[] args)

    {

        ChildClass childObj = new ChildClass();

         

        childObj.test();

    }

 Program output.

Console
In ChildClass

DIFFERENCE BETWEEN THIS(),SUPER() AND THIS,SUPER:


THIS(),SUPER() THIS,SUPER
These are constructor These are keywords
calls to call current refer parent class
class and super class context and current
class context
These can be used in These can be used in
constructor only any where except static
area
We can use any one of Both and multiple times
them only once

4. Java OTHER KEYWORDS:


 abstract: Java abstract keyword is used to declare abstract class. Abstract class can
provide the implementation of interface. It can have abstract and non-abstract
methods.
 boolean: Java boolean keyword is used to declare a variable as a boolean type. It
can hold True and False values only.
 break: Java break keyword is used to break loop or switch statement. It breaks the
current flow of the program at specified condition.
 byte: Java byte keyword is used to declare a variable that can hold an 8-bit data
values.
 case: Java case keyword is used to with the switch statements to mark blocks of
text.
 catch: Java catch keyword is used to catch the exceptions generated by try
statements. It must be used after the try block only.
 char: Java char keyword is used to declare a variable that can hold unsigned 16-bit
Unicode characters
 class: Java class keyword is used to declare a class.
 continue: Java continue keyword is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified condition.
 default: Java default keyword is used to specify the default block of code in a switch
statement.
 do: Java do keyword is used in control statement to declare a loop. It can iterate a
part of the program several times.
 double: Java double keyword is used to declare a variable that can hold a 64-bit
floating-point numbers.
 else: Java else keyword is used to indicate the alternative branches in an if
statement.
 enum: Java enum keyword is used to define a fixed set of constants. Enum
constructors are always private or default.
 extends: Java extends keyword is used to indicate that a class is derived from
another class or interface.
 final: Java final keyword is used to indicate that a variable holds a constant value. It
is applied with a variable. It is used to restrict the user.

The final variable which is not assigned to any value can only be assigned through the class
constructor.

 What is the final blank variable?


A final variable, not initialized at the time of declaration, is known as the final blank variable.
We can't initialize the final blank variable directly. Instead, we have to initialize it by using
the class constructor. It is useful in the case when the user has some data which must not be
changed by others, for example, PAN Number. Consider the following example:
class Student{  
int id;  
String name;  
final String PAN_CARD_NUMBER;  
...  
}  
Can you declare the main method as final?
Yes, We can declare the main method as public static final void main(String[] args){}.

Can we declare a constructor as final?


The constructor can never be declared as final because it is never inherited. Constructors are
not ordinary methods; therefore, there is no sense to declare constructors as final. However,
if you try to do so, The compiler will throw an error.

99) Can we declare an interface as final?


No, we cannot declare an interface as final because the interface must be implemented by
some class to provide its definition. Therefore, there is no sense to make an interface final.
However, if you try to do so, the compiler will show an error.

100) What is the difference between the final method and


abstract method?
The main difference between the final method and abstract method is that the abstract
method cannot be final as we need to override them in the subclass to give its definition.

 finally: Java finally keyword indicates a block of code in a try-catch structure. This


block is always executed whether exception is handled or not.
 float: Java float keyword is used to declare a variable that can hold a 32-bit floating-
point number.
 for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some conditions become true. If the number of
iteration is fixed, it is recommended to use for loop.
 if: Java if keyword tests the condition. It executes the if block if condition is true.
 implements: Java implements keyword is used to implement an interface.
 import: Java import keyword makes classes and interfaces available and accessible
to the current source code.
 instanceof: Java instanceof keyword is used to test whether the object is an
instance of the specified class or implements an interface.
 int: Java int keyword is used to declare a variable that can hold a 32-bit signed
integer.
 interface: Java interface keyword is used to declare an interface. It can have only
abstract methods.
 long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
 native: Java native keyword is used to specify that a method is implemented in native
code using JNI (Java Native Interface).
 new: Java new keyword is used to create new objects.
 null: Java null keyword is used to indicate that a reference does not refer to anything.
It removes the garbage value.
 package: Java package keyword is used to declare a Java package that includes the
classes.
 private: Java private keyword is an access modifier. It is used to indicate that a
method or variable may be accessed only in the class in which it is declared.
 protected: Java protected keyword is an access modifier. It can be accessible within
package and outside the package but through inheritance only. It can't be applied on
the class.
 public: Java public keyword is an access modifier. It is used to indicate that an item
is accessible anywhere. It has the widest scope among all other modifiers.
 return: Java return keyword is used to return from a method when its execution is
complete.
 short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
 static: Java static keyword is used to indicate that a variable or method is a class
method. The static keyword in Java is used for memory management mainly.
 strictfp: Java strictfp is used to restrict the floating-point calculations to ensure
portability.
 super: Java super keyword is a reference variable that is used to refer parent class
object. It can be used to invoke immediate parent class method.
 switch: The Java switch keyword contains a switch statement that executes code
based on test value. The switch statement tests the equality of a variable against
multiple values.
 synchronized: Java synchronized keyword is used to specify the critical sections or
methods in multithreaded code.
 this: Java this keyword can be used to refer the current object in a method or
constructor.
 throw: The Java throw keyword is used to explicitly throw an exception. The throw
keyword is mainly used to throw custom exception. It is followed by an instance.
 throws: The Java throws keyword is used to declare an exception. Checked
exception can be propagated with throws.
 transient: Java transient keyword is used in serialization. If you define any data
member as transient, it will not be serialized.
 try: Java try keyword is used to start a block of code that will be tested for
exceptions. The try block must be followed by either catch or finally block.
 void: Java void keyword is used to specify that a method does not have a return
value.
 volatile: Java volatile keyword is used to indicate that a variable may change
asynchronously.
 while: Java while keyword is used to start a while loop. This loop iterates a part of
the program several times. If the number of iteration is not fixed, it is recommended
to use while loop.

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:

 static variable are also known as class variable.

 static means to remain constant.


 In Java, it means that it will be constant for all the instances created for that class.

 static variable need not be called from object.

 It is called by classname.static variable name

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);
}
}

public class StudyTonight {


public static void main(String[] args) {

Student o1 = new Student();


Student o2 = new Student();

o1.change();

Student.id = 1;
o2.change();
}
}
Output:

35
1

Static variable vs Instance variable


Here are some differences between Static/class variable and Instance variable.

Static variable Instance Variable

Represent common property Represent unique property

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

Let's take an example and understand the difference:


public class Test

static int x = 100;

int y = 100;

public void increment()

x++; y++;

public static void main( String[] args )

Test t1 = new Test();

Test t2 = new Test();

t1.increment();

t2.increment();

System.out.println(t2.y);

System.out.println(Test.x); //accessed without any instance of class.


}

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.

The naming of an address is known as variable. Variable is the name of memory


location.
Java Programming language defines mainly three kind of variables.

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

public static void square(int x)

System.out.println(x*x);

public static void main (String[] arg)

square(8) //static method square () is called without any instance of class.

64

Few things to remember.

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>>.*;

Static import example


For example, You remember printing messages in the standard output using
the System.out.println() method. System is a class in java.lang package that has a
static variable named out. When you use System.out, you are referring to that static
variable out of the System class. You can use a static import declaration to import
the out static variable from the System class as follows:
import static java.lang.System.out;

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 {

        public static void main(String[] args) {

                out.println("Hello static import!");

        }

4.Static block in Java


Static block is used to initialize static data member. Static block executes
before main() method.
Time for an Example:
class ST_Employee

int eid;

String name;

static String company_name;

static {

company_name ="StudyTonight"; //static block invoked before main() method

public void show()

System.out.println(eid+" "+name+" "+company_name);

public static void main( String[] args )

ST_Employee se1 = new ST_Employee();

se1.eid = 104;

se1.name = "Abhijit";

se1.show();

104 Abhijit StudyTonight

 Why a non-static variable cannot be referenced from a static context?


When you try to access a non-static variable from a static context like main method,
java compiler throws a message like "a non-static variable cannot be referenced
from a static context". This is because non-static variables are related with instance
of class(object) and they get created when instance of a class is created by
using new operator. So if you try to access a non-static variable without any instance
compiler will complain because those variables are not yet created and they don't
have any existence until an instance is created and associated with it.
Let's take an example of accessing non-static variable from a static context,
class Test

int x;

public static void main(String[] args)

x = 10;

compiler error: non-static variable count cannot be referenced from a static context

Now below we have the same example using instance of class,


class Test

int x;

public static void main(String[] args)

Test tt = new Test();

tt.x = 10; //works fine with instance of class

Q. Why main() method is static in java?


Because static methods can be called without any instance of a class and main() is
called before any instance of a class is created.
5.Static Class
In Java, you can have a static class as inner class. Just like other static members,
nested classed belong with class scope so the inner static class can be accessed
without having an object of outer class.
public class JavaStaticExample

    public static void main(String[] args)

    {

        //Static inner class example

        System.out.println( DataObject.StaticInnerClas.innerStaticVar );

    }

class DataObject

    public Integer nonStaticVar;

    public static Integer staticVar;    //static variable

     

    static class StaticInnerClas {

        Integer innerNonStaticVar = 60;

        static Integer innerStaticVar = 70;     //static variable inside inner class

    }

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

    public static void main(String[] args)

    {

        //Static inner class example

        DataObject.StaticInnerClas.accessOuterClass();

    }

}
class DataObject

    public Integer nonStaticVar;

    public static Integer staticVar;    //static variable

         

    static {

        staticVar = 40;

        //nonStaticVar = 20;    //Not possible to access non-static members

    }

 
    public static Integer getStaticVar(){

        return staticVar;

    }

     

    static class StaticInnerClas

    {  

        public static void accessOuterClass()

        {

            System.out.println(DataObject.staticVar);       //static variable of outer c

            System.out.println(DataObject.getStaticVar());  //static method of outer cla

        }

    }

 
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;
    }
}

Enumerations serve the purpose of representing a group of named constants in a


programming language. For example the 4 suits in a deck of playing cards may be 4
enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated
type named Suit. Other examples include natural enumerated types (like the planets,
days of the week, colors, directions, etc.).
Enums are used when we know all possible values at compile time, such as
choices on a menu, rounding modes, command line flags, etc. It is not necessary
that the set of constants in an enum type stay fixed for all time.
In Java (from 1.5), enums are represented using enum data type. Java enums are
more powerful than C/C++ enums . In Java, we can also add variables, methods and
constructors to it. The main objective of enum is to define our own data
types(Enumerated Data Types).
Declaration of enum in java :
 Enum declaration can be done outside a Class or inside a Class but not inside a
Method.

// A simple enum example where enum is declared

// outside any class (Note enum keyword instead of

// class keyword)

enum Color

    RED, GREEN, BLUE;

  

public class Test

    // Driver method

    public static void main(String[] args)

    {

        Color c1 = Color.RED;

        System.out.println(c1);

    }

Output :
RED

Enum with Customized Value in Java


Prerequisite : enum in Java
By default enums have their own string values, we can also assign some custom
values to enums. Consider below example for that.
Examples:
enum Fruits
{
APPLE(“RED”), BANANA(“YELLOW”), GRAPES(“GREEN”);
}
In above example we can see that the Fruits enum have three members i.e APPLE,
BANANA and GRAPES with have their own different custom values RED, YELLOW
and GREEN respectively.
Now to use this enum in code, there are some points we have to follow:-
1 We have to create parameterized constructor for this enum class. Why? Because as
we know that enum class’s object can’t be create explicitly so for initializing we use
parameterized constructor. And the constructor cannot be the public or protected it
must have private or default modifiers. Why? if we create public or protected, it will
allow initializing more than one objects. This is totally against enum concept.
2 We have to create one getter method to get the value of enums.

// Java program to demonstrate how values can

// be assigned to enums.

enum TrafficSignal

    // This will call enum constructor with one

    // String argument

    RED("STOP"), GREEN("GO"), ORANGE("SLOW DOWN");

  

    // declaring private variable for getting values

    private String action;

  

    // getter method

    public String getAction()

    {

        return this.action;

    }

  

    // enum constructor - cannot be public or protected

    private TrafficSignal(String action)

    {
        this.action = action;

    }

  

// Driver code

public class EnumConstructorExample

    public static void main(String args[])

    {

        // let's print name of each enum and there action

        // - Enum values() examples

        TrafficSignal[] signals = TrafficSignal.values();

  

        for (TrafficSignal signal : signals)

        {

            // use getter method to get the value

            System.out.println("name : " + signal.name() +

                        " action: " + signal.getAction() );

        }

    }

Output:
name : RED action: STOP
name : GREEN action: GO
name : ORANGE action: SLOW DOWN

Local variables in Java


Local variables are declared in method, constructor or block. Local variables are
initialized when method, constructor or block start and will be destroyed once its end.
Local variable reside in stack. Access modifiers are not used for local variable.
foreach or enhanced for loop
J2SE 5 introduces special type of for loop called foreach loop to access elements of
array. Using foreach loop you can access complete array sequentially without using
index of array. Let us see an example of foreach loop.
class Test
{
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40};
for(int x : arr)
{
System.out.println(x);
}
}
}

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

Java operators can be divided into following categories:

 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

Labelled For Loop


In Java, Labelled For Loop is used to give label before any for loop. It is very useful
for nesting for loop.
Syntax:

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:

public class LabelDemo1{


public static void main(String[] args)
{
a:
for (inti = 0; i< 10; i++) {
for (int j = 0; j < 10; j++) {
if (j == 5)
break a;
System.out.println("j = " + j);
}
}
}
}

JAVA EXCEPTIONAL HANDLING(API):


The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

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 java.lang.Throwable class is the root class of Java Exception hierarchy


which is inherited by two subclasses: Exception and Error. A hierarchy of Java
Exception classes are given below:
Difference between Checked and Unchecked
Exceptions
1) Checked Exception

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

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Keyword Description

try The "try" keyword is used to specify a block where


we should place exception code. The try block must
be followed by either catch or finally. It means, we
can't use try block alone.

catch The "catch" block is used to handle the exception. It


must be preceded by try block which means we can't
use catch block alone. It can be followed by finally
block later.

Finally(finally block is always executed) The "finally" block is used to execute the important


code of the program. It is executed whether an
exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions.


It doesn't throw an exception. It specifies that there
may occur an exception in the method. It is always
used with method signature.
Try and catch:

A try block can be followed by one or more catch blocks.

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.

In case we generate NullPointerException, but didn't provide the corresponding


exception type. In such case, the catch block containing the parent exception
class Exception will invoked as catch(Exception e)  .

If THE CORRESPONDING EXCEPTION TRY BLOCK HAS IRRESPECTIVE HANDLING IN THE


CATCH MAY PRODUCE COMPILE TIME ERROR.

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");}

for example consider below code for better


understanding:

import java.lang.*;

class Main{

public static void main(String args[]){

try{

try{

System.out.println("going to divide");

int b =39/0;

}catch(ArithmeticException e){System.out.println(e);}

try{

int a[]=new int[5];

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..

AND WHEN THE BOLDED PIECE IS UNCOMMENTED THEN THE OUTPUT IS

going to divide
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 5

handeled
normal flow..

THIS IS BECAUSE THE TRY BLOCK IS CONSIDERED AS SUCCESSFUL WHEN THE


EXCEPTION OCCURS SO WHEN WE EXECUTE THE 1ST CODE THERE IS NO
EXCEPTION IN THE OUTER TRY BLOCK BUT IN THE 2ND CODE THERE IS
EXCEPTION (INT A=10/0) SO THE RESPECTIVE HANDLED IS DISPLAYED.

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 in thread main java.lang.ArithmeticException:not valid

Java throws keyword


The Java throws keyword is used to declare an exception. It gives an information to
the programmer that there may occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can be maintained.

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.

Syntax of java throws


1 return_type method_name() throws exception_class_name{  
2 //method code  
3 }  
Advantage of Java throws keyword
Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.

There are two cases:


1 Case1:You caught the exception i.e. handle the exception using try/catch.
2 Case2:You declare the exception i.e. specifying throws with the method.

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.

A)Program if exception does not occur


1 import java.io.*;  
2 class M{  
3  void method()throws IOException{  
4   System.out.println("device operation performed");  
5  }  
6 }  
7 class Testthrows3{  
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:device operation performed
normal flow...

B)Program if exception occurs

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

Java Exception propagation


An exception is first thrown from the top of the stack and if it is not caught, it drops down the
call stack to the previous method,If not caught there, the exception again drops down to the
previous method, and so on until they are caught or until they reach the very bottom of the
call stack.This is called exception propagation.

Rule: By default Unchecked Exceptions are forwarded in calling chain


(propagated). THIS MEANS EXCEPTION PROPAGATION IS APPLICABLE
ONLY FOR UNCHECKED EXCEPTIONS.

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...

FOR CHECKED EXCEPTIONS:

Rule: By default, Checked Exceptions are not forwarded in calling chain


(propagated).

Program which describes that checked exceptions are not propagated

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 }  

Output:Compile Time Error


Difference between final, finally and
finalize
There are many differences between final, finally and finalize. A list of differences
between final, finally and finalize are given below:

No. final finally finalize

1) Final is used to apply restrictions on Finally is used to place Finalize is used to


class, method and variable. Final important code, it will perform clean up
class can't be inherited, final be executed whether processing just before
method can't be overridden and exception is handled or object is garbage
final variable value can't be not. collected.
changed.

2) Final is a keyword. Finally is a block. Finalize is a method.

Java final example


1 class FinalExample{  
2 public static void main(String[] args){  
3 final int x=100;  
4 x=200;//Compile Time Error  
5 }}  

Java finally example


1 class FinallyExample{  
2 public static void main(String[] args){  
3 try{  
4 int x=300;  
5 }catch(Exception e){System.out.println(e);}  
6 finally{System.out.println("finally block is executed");}  
7 }}  

Java finalize example


1 class FinalizeExample{  
2 public void finalize(){System.out.println("finalize called");}  
3 public static void main(String[] args){  
4 FinalizeExample f1=new FinalizeExample();  
5 FinalizeExample f2=new FinalizeExample();  
6 f1=null;  
7 f2=null;  
8 System.gc();  
9 }}  
EXCEPTIONAL HANDLING IN METHOD
OVERLOADING:
ExceptionHandling with MethodOverriding in Java
There are many rules if we talk about methodoverriding with exception handling. The Rules are as
follows:

o If the superclass method does not declare an exception


o If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but it can declare unchecked exception.
o If the superclass method declares an exception
o If the superclass method declares an exception, subclass overridden method can
declare same, subclass exception or no exception but cannot declare parent exception.

If the superclass method does not declare an exception

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

Output:Compile Time Error

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

If the superclass method declares an exception

1) Rule: If the superclass method declares an exception, subclass overridden method can declare same, subcla
no exception but cannot declare parent exception.

Example in case subclass overridden method declares parent exception


1 import java.io.*;  
2 class Parent{  
3   void msg()throws ArithmeticException{System.out.println("parent");}  
4 }  
5   
6 class TestExceptionChild2 extends Parent{  
7   void msg()throws Exception{System.out.println("child");}  
8   
9   public static void main(String args[]){  
10    Parent p=new TestExceptionChild2();  
11    try{  
12    p.msg();  
13    }catch(Exception e){}  
14   }  
15 }  
Test it Now
Output:Compile Time Error

Example in case subclass overridden method declares same exception


1 import java.io.*;  
2 class Parent{  
3   void msg()throws Exception{System.out.println("parent");}  
4 }  
5   
6 class TestExceptionChild3 extends Parent{  
7   void msg()throws Exception{System.out.println("child");}  
8   
9   public static void main(String args[]){  
10    Parent p=new TestExceptionChild3();  
11    try{  
12    p.msg();  
13    }catch(Exception e){}  
14   }  
15 }  
Test it Now

Output:child

Example in case subclass overridden method declares subclass exception


1 import java.io.*;  
2 class Parent{  
3   void msg()throws Exception{System.out.println("parent");}  
4 }  
5   
6 class TestExceptionChild4 extends Parent{  
7   void msg()throws ArithmeticException{System.out.println("child");}  
8   
9   public static void main(String args[]){  
10    Parent p=new TestExceptionChild4();  
11    try{  
12    p.msg();  
13    }catch(Exception e){}  
14   }  
15 }  
Test it Now

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 }  

Java Custom Exception


If you are creating your own Exception that is known as custom exception or user-
defined exception. Java custom exceptions are used to customize the exception
according to user need.

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.

Java Regex API provides 1 interface and 3 classes in java.util.regex package.

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.

Example of Java Regular Expressions


There are three ways to write the regex example in Java.

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

true true true


The . (dot) represents a single character.

Regex Character classes


No. Character Class Description

1 [abc] a, b, or c (simple class)

2 [^abc] Any character except a, b, or c (negation)

3 [a-zA-Z] a through z or A through Z, inclusive (range)

4 [a-d[m-p]] a through d, or m through p: [a-dm-p] (union)

5 [a-z&&[def]] d, e, or f (intersection)

6 [a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction)

7 [a-z&&[^m-p]] a through z, and not m through p: [a-lq-z](subtraction)

Java Regex Finder Example


1 import java.util.regex.Pattern;  
2 import java.util.Scanner;  
3 import java.util.regex.Matcher;    
4 public class RegexExample8{    
5     public static void main(String[] args){    
6         Scanner sc=new Scanner(System.in);  
7         while (true) {    
8             System.out.println("Enter regex pattern:");  
9             Pattern pattern = Pattern.compile(sc.nextLine());    
10             System.out.println("Enter text:");  
11             Matcher matcher = pattern.matcher(sc.nextLine());    
12             boolean found = false;    
13             while (matcher.find()) {    
14                 System.out.println("I found the text "+matcher.group()+" starting at index 
"+    
15                  matcher.start()+" and ending at index "+matcher.end());    
16                 found = true;    
17             }    
18             if(!found){    
19                 System.out.println("No match found.");    
20             }    
21         }    
22     }    
23 }    

Output:

Enter regex pattern: java


Enter text: this is java, do you know java
I found the text java starting at index 8 and ending at index 12
I found the text java starting at index 26 and ending at index 30

Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing


and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared


memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in


a single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking
to utilize the CPU. Multitasking can be achieved in two ways:

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process has an address in memory. In other words, each process allocates a
separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.

For various methods in multithreading visit:


https://www.javatpoint.com/multithreading-in-java

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:

1 By extending Thread class


2 By implementing Runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thre
class and implements Runnable interface.

Commonly used Constructors of Thread class:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be 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:

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

1 Java Thread Example by extending Thread class


Import java.lang.Thread;

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...

2 Java Thread Example by implementing Runnable


interface
Import java.lang.Runnable;

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

Thread Scheduler in Java


Thread scheduler in java is the part of the JVM that decides which thread should
run.

There is no guarantee that which runnable thread will be chosen to run by the thread
scheduler.

Only one thread at a time can run in a single process.

The thread scheduler mainly uses preemptive or time slicing scheduling to schedule
the threads.

Difference between preemptive scheduling and


time slicing
Under preemptive scheduling, the highest priority task executes until it enters the
waiting or dead states or a higher priority task comes into existence. Under time slicing,
a task executes for a predefined slice of time and then reenters the pool of ready tasks.
The scheduler then determines which task should execute next, based on priority and
other factors.

Can we start a thread twice


No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once but for
second time, it will throw exception.

Let's understand it by the example given below:

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.*;

public class ThreadDemo implements Runnable {

Thread t;

public void run() {


for (int i = 10; i < 13; i++) {

System.out.println(Thread.currentThread().getName() + "
" + i);
try {
// thread to sleep for 1000 milliseconds
Thread.sleep(1000);
} catch (Exception e) {
System.out.println(e);
}
}
}

public static void main(String[] args) throws Exception {


Thread t = new Thread(new ThreadDemo());
// this will call run() function
t.start();

Thread t2 = new Thread(new ThreadDemo());


// this will call run() function
t2.start();
}
}

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

What if we call run() method directly instead start


o Each thread starts in a separate call stack.
o Invoking the run() method from main thread, the run() method goes onto the current call
beginning of a new call stack.

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...

 Problem if you direct call run() method

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.

Java Concurrency – yield(), sleep() and join() methods


We can prevent the execution of a thread by using one of the following methods of Thread class
1 yield(): Suppose there are three threads t1, t2, and t3. Thread t1 gets the processor and starts its e
t3 are in Ready/Runnable state. Completion time for thread t1 is 5 hour and completion time for t2 i
complete its execution after 5 hours, t2 has to wait for 5 hours to just finish 5 minutes job. In such s
taking too much time to complete its execution, we need a way to prevent execution of a thread in b
important is pending. yeild() helps us in doing so.
yield() basically means that the thread is not doing anything particularly important and if any other t
be run, they should run. Otherwise, the current thread will continue to run.

Use of yield method:


 Whenever a thread calls java.lang.Thread.yield method, it gives hint to the thread scheduler th
execution. Thread scheduler is free to ignore this hint.
 If any thread executes yield method , thread scheduler checks if there is any thread with same
thread. If processor finds any thread with higher or same priority then it will move the current t
state and give processor to other thread and if not – current thread will keep executing.
Syntax:
public static native void yield()

filter_none
edit
play_arrow
brightness_4
// Java program to illustrate yield() method

// in Java

import java.lang.*;

  

// MyThread extending Thread

class MyThread extends Thread

    public void run()

    {

        for (int i=0; i<5 ; i++)

            System.out.println(Thread.currentThread().getName()

                                + " in control");

    }

  

// Driver Class

public class yieldDemo

    public static void main(String[]args)

    {

        MyThread t = new MyThread();

        t.start();

  

        for (int i=0; i<5; i++)

        {

            // Control passes to child thread

            Thread.yield();
  

            // After execution of child Thread

            // main thread takes over

            System.out.println(Thread.currentThread().getName()

                                + " in control");

        }

    }

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

// sleep() method in Java

import java.lang.*;

  

public class SleepDemo implements Runnable

    Thread t;

    public void run()

    {

        for (int i = 0; i < 4; i++)

        {

            System.out.println(Thread.currentThread().getName()

                                                   + "  " + i);

            try

            {

                // thread to sleep for 1000 milliseconds

                Thread.sleep(1000);

            }

  

            catch (Exception e)

            {

                System.out.println(e);

            }

        }

    }

  

    public static void main(String[] args) throws Exception

    {

        Thread t = new Thread(new SleepDemo());

  
        // call run() function

        t.start();

  

        Thread t2 = new Thread(new SleepDemo());

  

        // call run() function

        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.*;

  

public class JoinDemo implements Runnable

    public void run()

    {

        Thread t = Thread.currentThread();

        System.out.println("Current thread: "

                               + t.getName());

  

        // checks if current thread is alive

        System.out.println("Is Alive? "

                               + t.isAlive());

    }

  

    public static void main(String args[]) throws Exception

    {

        Thread t = new Thread(new JoinDemo());

        t.start();

  

        // Waits for 1000ms this thread to die.

        t.join(1000);
  

        System.out.println("\nJoining after 1000"+

                             " mili seconds: \n");

        System.out.println("Current thread: " +

                                    t.getName());

  

  

        // Checks if this thread is alive

        System.out.println("Is alive? " + t.isAlive());

    }

Output:
Current thread: Thread-0
Is Alive? true

Joining after 1000 mili seconds:

Current thread: Thread-0


Is alive? false
Note:
 If any executing thread t1 calls join() on t2 i.e; t2.join() immediately t1 will enter into waiting sta
execution.
 Giving a timeout within join(), will make the join() effect to be nullified after the specific timeout
Priority of a Thread (Thread Priority):
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases
schedules the threads according to their priority (known as preemptive scheduling). But it is not guar
depends on JVM specification that which scheduling it chooses.

3 constants defined in Thread class:


1 public static int MIN_PRIORITY
2 public static int NORM_PRIORITY
3 public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of

Example of priority of a Thread:


1 class TestMultiPriority1 extends Thread{  
2  public void run(){  
3    System.out.println("running thread name is:"+Thread.currentThread().getName());  
4    System.out.println("running thread priority is:"+Thread.currentThread().getPriority()); 
 
5   
6   }  
7  public static void main(String args[]){  
8   TestMultiPriority1 m1=new TestMultiPriority1();  
9   TestMultiPriority1 m2=new TestMultiPriority1();  
10   m1.setPriority(Thread.MIN_PRIORITY);  
11   m2.setPriority(Thread.MAX_PRIORITY);  
12   m1.start();  
13   m2.start();  
14    
15  }  
16 }     
Test it Now
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

Daemon Thread in Java


Daemon thread in java is a service provider thread that provides services to the user
thread. Its life depend on the mercy of user threads i.e. when all the user threads dies,
JVM terminates this thread automatically.

There are many java daemon threads running automatically e.g. gc, finalizer etc.

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.

Points to remember for Daemon Thread in Java


o It provides services to user threads for background supporting tasks. It has no
role in life than to serve user threads.
o Its life depends on user threads.
o It is a low priority thread.

Why JVM terminates the daemon thread if there is no user


thread?
The sole purpose of the daemon thread is that it provides services to user thread for
background supporting task. If there is no user thread, why should JVM keep running
this thread. That is why JVM terminates the daemon thread if there is no user thread.

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

JVM Shutdown Hook in Java


Shutdown Hooks are a special construct that allows developers to plug in a
piece of code to be executed when the JVM is shutting down.
This comes in handy in cases where we need to do special clean up operations in
case the VM is shutting down.
Handling this using the general constructs such as making sure that we call a special
procedure before the application exits (calling System.exit(0) ) will not work for
situations where the VM is shutting down due to an external reason (ex. kill request
from O/S), or due to a resource problem (out of memory). As we will see soon,
shutdown hooks solve this problem easily, by allowing us to provide an arbitrary
code block, which will be called by the JVM when it is shutting down.
From the surface, using a shutdown hook is downright straight forward. All we have
to do is simply write a class which extends the java.lang.Thread class, and
provide the logic that we want to perform when the VM is shutting down,
inside the public void run() method.
Then we register an instance of this class as a shutdown hook to the VM by calling
Runtime.getRuntime().addShutdownHook(Thread) method. If you need to
remove a previously registered shutdown hook, the Runtime class provides the
removeShutdownHook(Thread) method as well.
THREAD POOL:

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.

Advantage of Java Thread Pool

Better performance It saves time because there is no need to create new thread.

Real time usage

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:

pool-1-thread-1 (Start) message = 0


pool-1-thread-2 (Start) message = 1
pool-1-thread-3 (Start) message = 2
pool-1-thread-5 (Start) message = 4
pool-1-thread-4 (Start) message = 3
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = 5
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = 6
pool-1-thread-3 (End)
pool-1-thread-3 (Start) message = 7
pool-1-thread-4 (End)
pool-1-thread-4 (Start) message = 8
pool-1-thread-5 (End)
pool-1-thread-5 (Start) message = 9
pool-1-thread-2 (End)
pool-1-thread-1 (End)
pool-1-thread-4 (End)
pool-1-thread-3 (End)
pool-1-thread-5 (End)
Finished all threads
THREAD GROUP
A ThreadGroup represents a set of threads. A thread group can also include the other
thread group. The thread group creates a tree in which every thread group except the
initial thread group has a parent.

Constructo Description
r

1) ThreadGroup(String name) creates a thread group with giv

2) ThreadGroup(ThreadGroup parent, String creates a thread group with giv


name) name.

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 :

public class ShutDownHook

  public static void main(String[] args)

  {

  

    Runtime.getRuntime().addShutdownHook(new Thread()

    {

      public void run()

      {

        System.out.println("Shutdown Hook is running !");

      }

    } );

    System.out.println("Application Terminating ...");

  }

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:

Program of performing single task by multiple threads

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

Note: Each thread run in a separate callstack.

How to perform multiple tasks by multiple threads (multitasking


in multithreading)?

If you have to perform multiple tasks by multiple threads,have multiple run() methods.For example:

Program of performing two tasks by two threads

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

Same example as above by annonymous class that extends


Thread class:
Program of performing two tasks by two threads

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

Same example as above by annonymous class that


implements Runnable interface:
Program of performing two tasks by two threads
1 class TestMultitasking5{  
2  public static void main(String args[]){  
3   Runnable r1=new Runnable(){  
4     public void run(){  
5       System.out.println("task one");  
6     }  
7   };  
8   
9   Runnable r2=new Runnable(){  
10     public void run(){  
11       System.out.println("task two");  
12     }  
13   };  
14       
15   Thread t1=new Thread(r1);  
16   Thread t2=new Thread(r2);  
17   
18   t1.start();  
19   t2.start();  
20  }  
21 }  
Test it Now
Output:task one
task two

Garbage Collection in Java


In Java destruction of object from memory is done automatically by the JVM. When
there is no reference to an object, then that object is assumed to be no longer
needed and the memory occupied by the object are released. This technique is
called Garbage Collection. This is accomplished by the JVM.
Unlike C++ there is no explicit need to destroy object.
How can an object be unreferenced?
There are many ways:

o By nulling the reference


o By assigning a reference to another
o By anonymous object etc.

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();  

Java Runtime class


Java Runtime class is used to interact with java runtime environment. Java Runtime
class provides methods to execute a process, invoke GC, get total and free memory etc.
There is only one instance of java.lang.Runtime class is available for one java
application.

The Runtime.getRuntime() method returns the singleton instance of Runtime class.


Important methods of Java Runtime class
No. Method Description

1) public static Runtime getRuntime() returns the instance of Run

2) public void exit(int status) terminates the current virt

3) public void addShutdownHook(Thread hook) registers new hook thread.

4) public Process exec(String command)throws IOException executes given command i

5) public int availableProcessors() returns no. of available pro

6) public long freeMemory() returns amount of free me

7) public long totalMemory() returns amount of total me

Can the Garbage Collection be forced explicitly ?


No, the Garbage Collection can not be forced explicitly. We may request JVM
for garbage collection by calling System.gc() method. But This does not guarantee
that JVM will perform the garbage collection.

Advantages of Garbage Collection

1 Programmer doesn't need to worry about dereferencing an object.

2 It is done automatically by JVM.

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

Some Important Points to Remember

1 finalize() method is defined in java.lang.Object class, therefore it is available to

all the classes.

2 finalize() method is declare as proctected inside Object class.

3 finalize() method gets called only once by a Daemon thread named GC (Garbage

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

public static void main(String[] args)

{
Test t = new Test();

t=null;

System.gc();

public void finalize()

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.

Why use Synchronization


The synchronization is mainly used to

1 To prevent thread interference.


2 To prevent consistency problem.

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

Concept of Lock in Java


Synchronization is built around an internal entity known as the lock or monitor. Every
object has an lock associated with it. By convention, a thread that needs consistent
access to an object's fields has to acquire the object's lock before accessing them, and
then release the lock when it's done with them.

From Java 5 the package java.util.concurrent.locks contains several lock


implementations.

Java synchronized method


If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

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

Example of synchronized method by using


annonymous class
In this program, we have created the two threads by annonymous class, so less coding
is required.

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.

Same example of static synchronization by annonymous class


In this example, we are using annonymous class to create the threads.

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

Synchronized block on a class lock:


The block synchronizes on the lock of the object denoted by the reference .class name
.class. A static synchronized method printTable(int n) in class Table is equivalent to the
following declaration:

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.

Example of Deadlock in java


1 public class TestDeadlockExample1 {  
2   public static void main(String[] args) {  
3     final String resource1 = "ratan jaiswal";  
4     final String resource2 = "vimal jaiswal";  
5     // t1 tries to lock resource1 then resource2  
6     Thread t1 = new Thread() {  
7       public void run() {  
8           synchronized (resource1) {  
9            System.out.println("Thread 1: locked resource 1");  
10   
11            try { Thread.sleep(100);} catch (Exception e) {}  
12   
13            synchronized (resource2) {  
14             System.out.println("Thread 1: locked resource 2");  
15            }  
16          }  
17       }  
18     };  
19   
20     // t2 tries to lock resource2 then resource1  
21     Thread t2 = new Thread() {  
22       public void run() {  
23         synchronized (resource2) {  
24           System.out.println("Thread 2: locked resource 2");  
25   
26           try { Thread.sleep(100);} catch (Exception e) {}  
27   
28           synchronized (resource1) {  
29             System.out.println("Thread 2: locked resource 1");  
30           }  
31         }  
32       }  
33     };  
34   
35       
36     t1.start();  
37     t2.start();  
38   }  
39 }  
40           
Output: Thread 1: locked resource 1
Thread 2: locked resource 2
next →← prev
Inter-thread communication in Java
Inter-thread communication or Co-operation is all about allowing synchronized
threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is


paused running in its critical section and another thread is allowed to enter (or lock)
in the same critical section to be executed.It is implemented by following methods
of Object class:

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.

The 3 methods provided by the Thread class for


interrupting a thread
o public void interrupt()
o public static boolean interrupted()
o public boolean isInterrupted()

Reentrant Monitor in Java


According to Sun Microsystems, Java monitors are reentrant means java thread can
reuse the same monitor for different synchronized methods if method is called from the
method.

Advantage of Reentrant Monitor

It eliminates the possibility of single thread deadlocking

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/

 2)  java.io: Contains classed for supporting input / output operations.


 https://www.geeksforgeeks.org/java-io-packag/

 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 AND FILES:


For files operation vist: https://www.codejava.net/java-se/file-io/how-to-read-and-write-text-file-in-
java

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.

We can perform file handling in Java by Java I/O API.

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: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and an error message to the console.

1 System.out.println("simple message");  
2 System.err.println("error message");  

Let's see the code to get input from console.

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 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 classes required for input and output operations.

We can perform file handling in Java by Java I/O API.

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: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and an error message to the console.

1 System.out.println("simple message");  
2 System.err.println("error message");  

Let's see the code to get input from console.

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.

We can perform file handling in Java by Java I/O API.

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: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and an error message to the console.

1 System.out.println("simple message");  
2 System.err.println("error message");  

Let's see the code to get input from console.

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.

Useful methods of OutputStream


Method Description

1) public void write(int)throws IOException is used to write a byte to the current out

2) public void write(byte[])throws IOException is used to write an array of byte to the c

3) public void flush()throws IOException flushes the current output stream.


4) public void close()throws IOException is used to close the current output stream

OutputStream Hierarchy

InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input stream

Useful methods of InputStream


Method Description

1) public abstract int read()throws reads the next byte of data from the input stream
IOException of the file.

2) public int available()throws returns an estimate of the number of bytes that c


IOException current input stream.

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

Javatpoint provides tutorials of all technology.

The content of a text file testout.txt is set with the data Like Java, Spring,
Hibernate, Android, PHP etc.

Serialization and Deserialization in Java

4)deserializabilty

Serialization is a mechanism of converting the state of an object into a byte stream.


Deserialization is the reverse process where the byte stream is used to recreate the
actual Java object in memory. This mechanism is used to persist the object.
The byte stream created is platform independent. So, the object serialized on one
platform can be deserialized on a different platform. For serializing the object, we call
the writeObject() method ObjectOutputStream, and for deserialization we call
the readObject() method of ObjectInputStream class.

next →← prev

Serialization and Deserialization in Java


1 Serialization
2 Serializable Interface
3 Example of Serialization
4 Example of Deserialization
5 Serialization with Inheritance
6 Externalizable interface
7 Serialization and static data member

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.

The reverse operation of serialization is called deserialization where byte-stream is converted into an


and deserialization process is platform-independent, it means you can serialize an object in a platform
different platform.

For serializing the object, we call the writeObject() method ObjectOutputStream, and for deserializ


the readObject() method of ObjectInputStream class.

We must have to implement the Serializable interface for serializing the object.

Advantages of Java Serialization

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.

It must be implemented by the class whose object you want to persist.

The String class and all the wrapper classes implement the java.io.Serializable interface by default.

Let's see the example given below:

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.

2) public void flush() throws IOException {} flushes the current output

3) public void close() throws IOException {} closes the current output s

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{}

2) public void close() throws closes ObjectInputStream.


IOException {}

Example of Java Serialization


In this example, we are going to serialize the object of Student class. The writeObject() method of O
provides the functionality to serialize the object. We are saving the state of the object in the file nam

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

Example of Java Deserialization


Deserialization is the process of reconstructing the object from the serialized state. It is
the reverse operation of serialization. Let's see an example where we are reading the
data from a deserialized object.

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

Java Serialization with the static data member


If there is any static data member in a class, it will not be serialized because static is the
part of class not object.

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.

The java.util package contains all the classes and interfaces for the Collection


framework.

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.

Java Collections and Generics


By purpose, generics provide type safety. It detects the incompatible types (in
method arguments) and prevent ClassCastException in runtime. In Java collections
as well, we can define a collection class to store only a certain type of objects. All
other types should be disallowed. This is done via generics.

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(1, "A");    //allowed

map.put(2, "B");    //allowed

 
map.put("3", "C");  //NOT allowed - Key is string

equals() and hashCode() Methods


Many collection classes provide specific functionalities such as sorted elements, no
duplicate elements etc. To implement this behavior, the added elements (objects)
must implement the equals() and hashCode() methods correctly.

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);

Benefits of Java Collections


 Consistent and reusable APIs – This is any framework does. It provides a consistent
set of classes methods which can be used to solve a similar set of problems over and
over, without getting unpredictable results. Java collections framework also helps in
solving common problems related to a group of objects – in consistent manner.

All collection classes have consistent implementation and provide some


common methods like add, get, put, remove etc. No matter what kind of data
structure you are dealing with, these methods work according to underlying
implementation and perform actions transparently.

 Less development time – A common and predictable framework always decreases


the development time and helps in writing application program in speedy manner.
Java collection also helps in performing some most repeated common tasks with
objects and collections and thus improve time factor.
 Performance – The Java collection APIs are written by some most brilliant minds of
industry and their performance is top notch in most of the scenarios. Ongoing
development work by Oracle and very enthusiastic Java developer community helps in
making it better.
 Clean code – These APIs have been written with all good coding practices and
documented very well. They follow a certain standard across whole Java collection
framework. It makes the programmer code look good and clean.

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.

To instantiate the List interface, we must use :

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

List<String> names = new ArrayList<>();

 
//Arraylist initialized with another collection

List<Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5));

Use add(), set() and remove() methods to add or update the elements in the


list.

Add/remove elements in the arraylist


//Create arraylist
List<String> names = new ArrayList<>();
 
names.add("lokesh");    //[lokesh]
names.add("alex");      //[lokesh, alex]
 
names.set(1, "brian");  //[lokesh, brian]
 
names.remove(1);        //[lokesh]

 Iterate

Use iterator() or listIterator() to get the reference of iterator instance. This


iterator can be used to iterate the elements in the arraylist.

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.

Consider the following example.

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.

Consider the following example.

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.

Consider the following example.

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.

Queue interface can be instantiated as:

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.

Consider the following example.

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.

Deque can be instantiated as:

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.

Set can be instantiated as:

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.

Consider the following example.

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.

Consider the following example.

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.

The SortedSet can be instantiated as:

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.

Consider the following example:

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

You might also like