0% found this document useful (0 votes)
1 views163 pages

Java Unit-1

AKTU unit 1 of 4th semester

Uploaded by

k060hushiyadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views163 pages

Java Unit-1

AKTU unit 1 of 4th semester

Uploaded by

k060hushiyadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 163

What is Java?

Java is a programming language and a platform.

Platform Any hardware or software environment in which a program runs, known as a


`platform. Since Java has its own Runtime Environment (JRE) and API, it is called
platform.

Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is
currently used. Some of them are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus etc.


2. Web Applications such as irctc.co.in etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.

Types of Java Applications


There are mainly 4 type of applications that can be created using java:

1) Standalone Application

It is also known as desktop application or window-based application. An application that


we need to install on every machine such as media player, antivirus etc. AWT and Swing
are used in java for creating standalone applications.

2) Web Application

An application that runs on the server side and creates dynamic page, is called web
application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web
applications in java.

3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for
creating enterprise applicatios.

4) Mobile Application

An application that is created for mobile devices. Currently Android and Java ME are
used for creating mobile applications.

History of Java
Java history is interesting to know. Java team members (also known as Green Team),
initiated a revolutionary task to develop a language for digital devices such as set-top
boxes, televisions etc.

At that time, it was a advanced concept for the green team. But, it was good for internet
programming. Later, Netscape Navigator incorporated Java technology.

James Gosling

Currently, Java is used in internet programming, mobile devices, games, e-business


solutions etc. Let's see the major points that describes the history of java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.

2) Originally designed for small, embedded systems in electronic appliances like set-top
boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.

4) After that, it was called Oak and was developed as a part of the Green project.

5) Why Oak? Oak is a symbol of strength and choosen as a national tree of many
countries like U.S.A., France, Germany, Romania etc.

6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.

7) Why they choosed java name for java language? The team gathered to choose a
new name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA"
etc. They wanted something that reflected the essence of the technology: revolutionary,
dynamic, lively, cool, unique, and easy to spell and fun to say.

According to James Gosling "Java was one of the top choices along with Silk". Since java
was so unique, most of the team members preferred java.

8) Java is an island of Indonesia where first coffee was produced (called java coffee).

9) Notice that Java is just a name not an acronym.

10) Originally developed by James Gosling at Sun Microsystems (which is now a


subsidiary of Oracle Corporation) and released in 1995.

11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.

12) JDK 1.0 released in(January 23, 1996).


Java Version History
There are many java versions that has been released.

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java se8 (18th mar 2014)
11. Java SE 9 (September 2017 but March 2018 for OpenJDK)
12. Java SE 10 (March 2018 but September 2018 for OpenJDK)
13. Java SE 11(September 2018 but At least September 2022 for Adopt OpenJDK )
14. Java SE 12(March 2019 but September 2019 for OpenJDK)

Features of Java
There is given many features of java. They are also called java buzzwords.

1.Simple

2.Object-oriented

3.Platform independent

4.Secured

5.Robust

6.Architecture neutral

7.Portable

8.Dynamic

9.Interpreted

10.High Performance

11.Multithreaded
12.Distributed

Simple
Java is simple in the sense that:

syntax is based on C++ (so easier for programmers to learn it after C++).

removed many confusing and/or rarely-used features e.g., explicit pointers,


operator overloading etc.

No need to remove unreferenced objects because there is Automatic Garbage


Collection in java.

Object-oriented
Object-oriented means we organize our software as a combination of different types
of objects that incorporates both data and behaviour.

Object-oriented programming(OOPs) is a methodology that simplify software


development and maintenace by providing some rulues.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independent
A platform is the hardware or software environment in which a program runs. There
are two types of platforms software-based and hardware-based. Java provides
software-based platform. The Java platform differs from most other platforms in the
sense that it's a software-based platform that runs on top of other hardware-based
platforms.It has two components:

1. Runtime Environment
2. API(Application Programming Interface)
Java code can
be run on
multiple
platforms
e.g.Windows,Li
nux,Sun
Solaris,Mac/OS
etc. Java code
is compiled by
the compiler
and converted
into
bytecode.This
bytecode is a
platform
independent
code because it
can be run on
multiple
platforms i.e.
Write Once and
Run
Anywhere(WORA).

Secured
Java is secured because:

 No explicit pointer
 Programs run inside virtual machine sandbox.

 Classloader- adds security by separating the package for the classes of the
local file system from those that are imported from network sources.
 Bytecode Verifier- checks the code fragments for illegal code that can violate
accesss right to objects.
 Security Manager- determines what resources a class can access such as
reading and writing to the local disk.

These security are provided by java language. Some sucurity can also be provided by
application developer through SSL,JAAS,cryptography etc.

Robust
Robust simply means strong. Java uses strong memory management. There are lack
of pointers that avoids security problem. There is automatic garbage collection in
java. There is exception handling and type checking mechanism in java. All these
points makes java robust.

Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is set.

Portable
We may carry the java bytecode to any platform.

High-performance
Java is faster than traditional interpretation since byte code is "close" to native code
still somewhat slower than a compiled language (e.g., C++)

Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any
machine on the internet.

Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it shares the same memory. Threads are
important for multi-media, Web applications etc.

Difference between JDK,JRE and JVM


Understanding the difference between JDK, JRE and JVM is important in Java. We will
have brief overview of JVM here. If you want to gain the detailed knowledge of JVM,
move to the next page. Firstly, let's see the basic differences between the JDK, JRE
and JVM.

JVM
JVM (Java Virtual Machine) is an abstract machine.It is a specification that provides
runtime environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e.JVM is plateform
dependent).

The JVM performs four main tasks:

 Loads code
 Verifies code
 Executes code
 Provides runtime environment

JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime
environment.It is the implementation of JVM.It physically exists.It contains set of
libraries + other files that JVM uses at runtime.

Implementation of JVMs are also actively released by other companies besides Sun
Micro Systems.
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.
JVM (Java Virtual Machine)
JVM (Java Virtual Machine) is an abstract machine.It is a specification that provides
runtime environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e.JVM is plateform
dependent).

The JVM performs four main tasks:

 Loads code
 Verifies code
 Executes code
 Provides runtime environment

JVM provides definitions for the:

 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.

Internal Architecture of JVM


Let's understand the internal architecture of JVM. It contains classloader, memory
area, execution engine etc.

1) Classloader:
Classloader is a subsystem of JVM that is used to load class files.

2) Class(Method) Area:
Class(Method) Area stores per-class structures such as the runtime constant pool, field
and method data, the code for methods.
3) Heap:
It is the runtime data area in which objects are allocated.

4) Stack:
Java Stack stores frames.It holds local variables and partial results, and plays a part
in method invocation and return.

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its
method invocation completes.

5) Program Counter Regiser:


PC (program counter) register. It contains the address of the Java virtual machine
instruction currently being executed.

6) Native Method Stack:


It contains all the native methods used in the application.

7) Execution Engine:
It contains:

1) A virtual processor

2) Interpreter:Read bytecode stream then execute the instructions.

3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles


parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation.Here the term ?compiler? refers
to a translator from the instruction set of a Java virtual machine (JVM) to the
instruction set of a specific CPU.

Variable and Datatype in Java


In this page, we will learn about the variable and java data types. Variable is a name
of memory location. There are three types of variables: local, instance and static.
There are two types of datatypes in java, primitive and non-primitive.

Variable
Variable is name of reserved area allocated in memory.
int data=50;//Here data is variable

Types of Variable
There are three types of variables in java

 local variable
 instance variable
 static variable

Local Variable

A variable that is declared inside the method is called local variable.

Instance Variable

A variable that is declared inside the class but outside the method is called instance
variable . It is not declared as static.

Static variable
A variable that is declared as static is called static variable. It cannot be local.

We will have detailed learning of these variables in next chapters.

Example to understand the types of variables

class A
{

int data=50;//instance variable

static int m=100;//static variable

void method(){
int n=90;//local variable
}

}//end of class

Data Types in Java


In java, there are two types of data types

 primitive data types


 non-primitive data types
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

Int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte


Why char uses 2 byte in java and what is \u0000 ?
because java uses unicode system rather than ASCII code system. \u0000 is the
lowest range of unicode system.

Unicode System
Unicode is a universal international standard character encoding that is capable of
representing most of the world's written languages.

Why java uses Unicode System?


Before Unicode, there were many language standards:

 ASCII (American Standard Code for Information Interchange) for the United
States.
 ISO 8859-1 for Western European Language.
 KOI-8 for Russian.
 GB18030 and BIG-5 for chinese, and so on.

This caused two problems:

1. A particular code value corresponds to different letters in the various language


standards.
2. The encodings for languages with large character sets have variable
length.Some common characters are encoded as single bytes, other require
two or more byte.

To solve these problems, a new language standard was developed i.e. Unicode
System.

In unicode, character holds 2 byte, so java also uses 2 byte for characters.

lowest value:\u0000

highest value:\uffff

Operators in java
Operator is a special symbol that is used to perform operations. There are many types
of operators in java such as unary operator, arithmetic operator, relational operator,
shift operator, bitwise operator, ternary operator and assignment operator.

Precedence of Operators
Operators Precedence

postfix expr++ expr--

unary ++expr --expr +expr -expr ~ !

multiplicative * / %

additive + -

shift << >> >>>

relational < > <= >= instanceof

equality == !=

bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&

logical OR ||

ternary ? :

assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Useful Programs:
There is given some useful programs such as factorial number, prime number,
fibonacci series etc.

It is better for the freshers to skip this topic and come to it after OOPs
concepts.
1) Program of factorial number.
class Operation{

static int fact(int number){


int f=1;
for(int i=1;i<=number;i++){
f=f*i;
}
return f;
}

public static void main(String args[]){


int result=fact(5);
System.out.println("Factorial of 5="+result);
}
}

2) Program of fibonacci series.


class Fabnoci{

public static void main(String...args)


{
int n=10,i,f0=1,f1=1,f2=0;
for(i=1;i<=n;i++)
{
f2=f0+f1;
f0=f1;
f1=f2;
f2=f0;
System.out.println(f2);
}

}
}
3) Program of armstrong number.
class ArmStrong{
public static void main(String...args)
{
int n=153,c=0,a,d;
d=n;
while(n>0)
{
a=n%10;
n=n/10;
c=c+(a*a*a);
}
if(d==c)
System.out.println("armstrong number");
else
System.out.println("it is not an armstrong number");

}
}

4) Program of checking palindrome number.


class Palindrome
{
public static void main( String...args)
{
int a=242;
int n=a,b=a,rev=0;
while(n>0)
{
a=n%10;
rev=rev*10+a;
n=n/10;
}
if(rev==b)
System.out.println("it is Palindrome");
else
System.out.println("it is not palinedrome");
}
}

5) Program of swapping two numbers without using third


variable.
class SwapTwoNumbers{
public static void main(String args[]){
int a=40,b=5;
a=a*b;
b=a/b;
a=a/b;

System.out.println("a= "+a);
System.out.println("b= "+b);

}
}

6) Program of factorial number by recursion


class FactRecursion{

static int fact(int n){


if(n==1)
return 1;

return n*=fact(n-1);
}

public static void main(String args[]){

int f=fact(5);
System.out.println(f);
}
}
Java OOPs Concepts
Object-Oriented Programming is a paradigm that provides many concepts, such
as inheritance, data binding, polymorphism, etc.

Simula is considered the first object-oriented programming language. The


programming paradigm where everything is represented as an object is known as a
truly object-oriented programming language.

Smalltalk is considered the first truly object-oriented programming language.

The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.Sec

Java Try Catch

The main aim of object-oriented programming is to implement real-world entities,


for example, object, classes, abstraction, inheritance, polymorphism, etc.

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies software development and
maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object

Any entity that has state and behavior is known as an object. For example, a chair,
pen, table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and
takes up some space in memory. Objects can communicate without knowing the
details of each other's data or code. The only necessary thing is the type of message
accepted and the type of response returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well
as behaviors like wagging the tail, barking, eating, etc.

Class
Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.

Inheritance
When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.

Polymorphism

If one task is performed in different ways, it is known as polymorphism. For example:


to convince the customer differently, to draw something, for example, shape,
triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve


polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog
barks woof, etc.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For example
phone call, we don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

Coupling
Coupling refers to the knowledge or information or dependency of another class. It
arises when classes are aware of each other. If a class has the details information of
another class, there is strong coupling. In Java, we use private, protected, and public
modifiers to display the visibility level of a class, method, and field. You can use
interfaces for the weaker coupling because there is no concrete implementation.

Cohesion
Cohesion refers to the level of a component which performs a single well-defined
task. A single well-defined task is done by a highly cohesive method. The weakly
cohesive method will split the task into separate parts. The java.io package is a highly
cohesive package because it has I/O related classes and interface. However, the
java.util package is a weakly cohesive package because it has unrelated classes and
interfaces.

Association
Association represents the relationship between the objects. Here, one object can be
associated with one object or many objects. There can be four types of association
between the objects:

o One to One
o One to Many
o Many to One, and
o Many to Many

Let's understand the relationship with real-time examples. For example, One country
can have one prime minister (one to one), and a prime minister can have many
ministers (one to many). Also, many MP's can have one prime minister (many to one),
and many ministers can have many departments (many to many).

Association can be undirectional or bidirectional.

Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship
where one object contains other objects as a part of its state. It represents the weak
relationship between objects. It is also termed as a has-a relationship in Java. Like,
inheritance represents the is-a relationship. It is another way to reuse objects.

Composition
The composition is also a way to achieve Association. The composition represents
the relationship where one object contains other objects as a part of its state. There
is a strong relationship between the containing object and the dependent object. It is
the state where containing objects do not have an independent existence. If you
delete the parent object, all the child objects will be deleted automatically.

Advantage of OOPs over Procedure-oriented


programming language
1) OOPs makes development and maintenance easier, whereas, in a procedure-
oriented programming language, it is not easy to manage if code grows as project
size increases.

2) OOPs provides data hiding, whereas, in a procedure-oriented programming


language, global data can be accessed from anywhere.
Figure: Data Representation in Procedure-Oriented Programming

Figure: Data Representation in Object-Oriented Programming

3) OOPs provides the ability to simulate real-world event much more effectively. We
can provide the solution of real word problem if we are using the Object-Oriented
Programming language.

What is the difference between an object-oriented programming


language and object-based programming language?
Object-based programming language follows all the features of OOPs except
Inheritance. JavaScript and VBScript are examples of object-based programming
languages.

Java Naming convention


A naming convention is a rule to follow as you decide what to name your identifiers
(e.g. class, package, variable, method, etc.), but it is not mandatory to follow that is
why it is known as convention not rule.

Advantage of java naming convension

By using standard Java naming conventions they make their code easier to read for
themselves and for other programmers. Readability of Java code is important because
it means less time is spent trying to figure out what the code does.

Name Convension

class name should begin with uppercase letter and be a noun e.g.String,System,Thread etc.

Interface should begin with uppercase letter and be an adjective (whereever possible). e.g.
name Runnable,ActionListener etc.

method should begin with lowercase letter and be a verb. e.g.


name main(),print(),println(),actionPerformed() etc.

variable should begin with lowercase letter e.g. firstName,orderNumber etc.


name

package should be in lowercase letter. e.g. java,lang,sql,util etc.


name

constants should be in uppercase letter. e.g. RED,YELLOW,MAX_PRIORITY etc.


name

Object and Class in Java


In this page, we will learn about the objects and classes. In object-oriented
programming, we design a program using objects and classes. Object is the physical
entity whereas class is the logical entity. A class works as a template from which we
create the objects.
Object

A runtime entity that has state and behaviour is known as an object. For example: chair,
table, pen etc. It can be tengible or intengible (physical or logical).

An object has three characterstics:

 state:represents the data of an object.


 behaviour:represents the behaviour of an object.
 identity:Object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user, but is used internally by the JVM to
identify each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behaviour.

Object is an instance of a class.Class is a template or blueprint from which objects


are created.So object is the instance(result) of a class.

Class
A class is a group of objects that have common property. It is a template or blueprint
from which objects are created.

A class in java can contain:

 data member
 method
 constructor
 block

Syntax to declare a class:

class <class_name>{
data member;
method;
}

Simple Example of Object and Class


In this example, we have created a Student class that have two data members id and
name. We are creating the object of the Student class by new keyword and printing
the objects value.

class Student{
int id;//data member (also instance variable)
String name;//data member(also instance variable)

public static void main(String args[]){


Student s1=new Student();//creating an object of Student
System.out.println(s1.id+" "+s1.name);

}
}
Output:0 null

Instance variable
A variable that is created inside the class but outside the method, is known as
instance variable.Instance variable doesn't get memory at compile time.It gets
memory at runtime when object(instance) is created.That is why, it is known as
instance variable.

Method
In java, a method is like function i.e. used to expose behaviour of an object.

Advantage of Method

 Code Reusability
 Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.

Example of Object and class that maintains the records of


students
In this example, we are creating the two objects of Student class and initializing the
value to these objects by invoking the insertRecord method on it. Here, we are
displaying the state (data) of the objects by invoking the displayInformation method.

class Student{
int rollno;
String name;

void insertRecord(int r, String n){ //method


rollno=r;
name=n;
}

void displayInformation(){System.out.println(rollno+" "+name);}//method

public static void main(String args[]){


Student s1=new Student();
Student s2=new Student();

s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");

s1.displayInformation();
s2.displayInformation();

}
}
Output:111 Karan
222 Aryan
As you see in the above figure, object gets the memory in Heap area and reference
variable refers to the object allocated in the Heap memory area. Here, s1 and s2 both
are reference variables that refer to the objects allocated in memory.

Another Example of Object and Class


There is given another example that maintains the records of Rectangle class. Its
exaplanation is same as in the above Student class example.

class Rectangle{
int length;
int width;

void insert(int l,int w){


length=l;
width=w;
}

void calculateArea(){System.out.println(length*width);}

public static void main(String args[]){


Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();

r1.insert(11,5);
r2.insert(3,15);

r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45

What are the different ways to create an object in Java?


There are many ways to create an object in java. They are:

 By new keyword
 By newInstance() method
 By clone() method
 By factory method etc.

We will learn, these ways to create the object later.

Annonymous object
Annonymous simply means nameless.An object that have no reference is known as
annonymous object.

If you have to use an object only once, annonymous object is a good approach.

class Calculation{

void fact(int n){


int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}

public static void main(String args[]){


new Calculation().fact(5);//calling method with annonymous object
}
}
Output:Factorial is 120

Creating multiple objects by one type only


We can create multiple objects by one type only as we do in case of primitives.

Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects

Let's see the example:

class Rectangle{
int length;
int width;

void insert(int l,int w){


length=l;
width=w;
}

void calculateArea(){System.out.println(length*width);}

public static void main(String args[]){


Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects

r1.insert(11,5);
r2.insert(3,15);

r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45

Method in Java
In general, a method is a way to perform some task. Similarly, the method in Java is
a collection of instructions that performs a specific task. It provides the reusability of
code. We can also easily modify code using methods. In this section, we will
learn what is a method in Java, types of methods, method declaration, and how
to call a method in Java.

What is a method in Java?


A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation. It is used to achieve
the reusability of code. We write a method once and use it many times. We do not
require to write code again and again. It also provides the easy
modification and readability of code, just by adding or removing a chunk of code.
The method is executed only when we call or invoke it.

The most important method in Java is the main() method.

Method Declaration
The method declaration provides information about method attributes, such as
visibility, return-type, name, and arguments. It has six components that are known
as method header, as we have shown in the following figure.Method
Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access specifier:

o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a
primitive data type, object, collection, void, etc. If the method does not return
anything, we use void keyword.

Method Name: It is a unique name that is used to define the name of a method. It
must be corresponding to the functionality of the method. Suppose, if we are
creating a method for subtraction of two numbers, the method name must
be subtraction(). A method is invoked by its name.

Parameter List: It is the list of parameters separated by a comma and enclosed in


the pair of parentheses. It contains the data type and variable name. If the method
has no parameter, left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.

Naming a Method
While defining a method, remember that the method name must be a verb and start
with a lowercase letter. If the method name has more than two words, the first name
must be a verb followed by adjective or noun. In the multi-word method name, the
first letter of each word must be in uppercase except the first word. For example:

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()

It is also possible that a method has the same name as another method name in the
same class, it is known as method overloading.

Types of Method
There are two types of methods in Java:

o Predefined Method
o User-defined Method

Predefined Method
In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods. It is also known as the standard library
method or built-in method. We can directly use these methods just by calling them
in the program at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc. When we call any of the predefined methods in our
program, a series of codes related to the corresponding method runs in the
background that is already stored in the library.

Each and every predefined method is defined inside a class. Such as print() method
is defined in the java.io.PrintStream class. It prints the statement that we write
inside the method. For example, print("Java"), it prints Java on the console.

Let's see an example of the predefined method.

Demo.java

1. public class Demo


2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max(9,7));
7. }
8. }

Output:

The maximum number is: 9

In the above example, we have used three predefined methods main(),


print(), and max(). We have used these methods directly without declaration
because they are predefined. The print() method is a method of PrintStream class
that prints the result on the console. The max() method is a method of
the Math class that returns the greater of two numbers.

We can also see the method signature of any predefined method by using the
link https://docs.oracle.com/. When we go through the link and see the max()
method signature, we find the following:

In the above method signature, we see that the method signature has access
specifier public, non-access modifier static, return type int, method
name max(), parameter list (int a, int b). In the above example, instead of defining
the method, we have just invoked the method. This is the advantage of a predefined
method. It makes programming less complicated.
Similarly, we can also see the method signature of the print() method.

User-defined Method
The method written by the user or programmer is known as a user-defined method.
These methods are modified according to the requirement.

How to Create a User-defined Method

Let's create a user defined method that checks the number is even or odd. First, we
will define the method.

1. //user defined method


2. public static void findEvenOdd(int num)
3. {
4. //method body
5. if(num%2==0)
6. System.out.println(num+" is even");
7. else
8. System.out.println(num+" is odd");
9. }

We have defined the above method named findevenodd(). It has a


parameter num of type int. The method does not return any value that's why we
have used void. The method body contains the steps to check the number is even or
odd. If the number is even, it prints the number is even, else prints the number is
odd.

How to Call or Invoke a User-defined Method

Once we have defined a method, it should be called. The calling of a method in a


program is simple. When we call or invoke a user-defined method, the program
control transfer to the called method.

1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from the user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }

In the above code snippet, as soon as the compiler reaches at


line findEvenOdd(num), the control transfer to the method and gives the output
accordingly.

Let's combine both snippets of codes in a single program and execute it.

EvenOdd.java

1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }
14. //user defined method
15. public static void findEvenOdd(int num)
16. {
17. //method body
18. if(num%2==0)
19. System.out.println(num+" is even");
20. else
21. System.out.println(num+" is odd");
22. }
23. }
Output 1:

Enter the number: 12


12 is even

Output 2:

Enter the number: 99


99 is odd

Let's see another program that return a value to the calling method.

In the following program, we have defined a method named add() that sum up the
two numbers. It has two parameters n1 and n2 of integer type. The values of n1 and
n2 correspond to the value of a and b, respectively. Therefore, the method adds the
value of a and b and store it in the variable s and returns the sum.

Addition.java

1. public class Addition


2. {
3. public static void main(String[] args)
4. {
5. int a = 19;
6. int b = 5;
7. //method calling
8. int c = add(a, b); //a and b are actual parameters
9. System.out.println("The sum of a and b is= " + c);
10. }
11. //user defined method
12. public static int add(int n1, int n2) //n1 and n2 are formal parameters
13. {
14. int s;
15. s=n1+n2;
16. return s; //returning the sum
17. }
18. }

Output:

The sum of a and b is= 24


Static Method
A method that has static keyword is known as static method. In other words, a
method that belongs to a class rather than an instance of a class is known as a static
method. We can also create a static method by using the keyword static before the
method name.

The main advantage of a static method is that we can call it without creating an
object. It can access static data members and also change the value of it. It is used to
create an instance method. It is invoked by using the class name. The best example
of a static method is the main() method.

Example of static method

Display.java

1. public class Display


2. {
3. public static void main(String[] args)
4. {
5. show();
6. }
7. static void show()
8. {
9. System.out.println("It is an example of static method.");
10. }
11. }

Output:

It is an example of a static method.

Instance Method
The method of the class is known as an instance method. It is a non-static method
defined in the class. Before calling or invoking the instance method, it is necessary to
create an object of its class. Let's see an example of an instance method.

InstanceMethodExample.java

1. public class InstanceMethodExample


2. {
3. public static void main(String [] args)
4. {
5. //Creating an object of the class
6. InstanceMethodExample obj = new InstanceMethodExample();
7. //invoking instance method
8. System.out.println("The sum is: "+obj.add(12, 13));
9. }
10. int s;
11. //user-defined method because we have not used static keyword
12. public int add(int a, int b)
13. {
14. s = a+b;
15. //returning the sum
16. return s;
17. }
18. }

Output:

The sum is: 25

There are two types of instance method:

o Accessor Method
o Mutator Method

Accessor Method: The method(s) that reads the instance variable(s) is known as the
accessor method. We can easily identify it because the method is prefixed with the
word get. It is also known as getters. It returns the value of the private field. It is
used to get the value of the private field.

Example

1. public int getId()


2. {
3. return Id;
4. }

Mutator Method: The method(s) read the instance variable(s) and also modify the
values. We can easily identify it because the method is prefixed with the word set. It
is also known as setters or modifiers. It does not return anything. It accepts a
parameter of the same data type that depends on the field. It is used to set the value
of the private field.

Example

1. public void setRoll(int roll)


2. {
3. this.roll = roll;
4. }

Example of accessor and mutator method

Student.java

1. public class Student


2. {
3. private int roll;
4. private String name;
5. public int getRoll() //accessor method
6. {
7. return roll;
8. }
9. public void setRoll(int roll) //mutator method
10. {
11. this.roll = roll;
12. }
13. public String getName()
14. {
15. return name;
16. }
17. public void setName(String name)
18. {
19. this.name = name;
20. }
21. public void display()
22. {
23. System.out.println("Roll no.: "+roll);
24. System.out.println("Student name: "+name);
25. }
26. }

Abstract Method
The method that does not has method body is known as abstract method. In other
words, without an implementation is known as abstract method. It always declares in
the abstract class. It means the class itself must be abstract if it has abstract method.
To create an abstract method, we use the keyword abstract.

Syntax

1. abstract void method_name();

Example of abstract method

Demo.java

1. abstract class Demo //abstract class


2. {
3. //abstract method declaration
4. abstract void display();
5. }
6. public class MyClass extends Demo
7. {
8. //method impelmentation
9. void display()
10. {
11. System.out.println("Abstract method?");
12. }
13. public static void main(String args[])
14. {
15. //creating object of abstract class
16. Demo obj = new MyClass();
17. //invoking abstract method
18. obj.display();
19. }
20. }

Output:
Abstract method..

Constructor in Java
Constructor is a special type of method that is used to initialize the object.

Constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.

Rules for creating constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of constructors

There are two types of constructors:

1. default constructor (no-arg constructor)


2. parameterized constructor
1) Default Constructor
A constructor that have no parameter is known as default constructor.

Syntax of default constructor:

<class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.

class Bike{

Bike(){System.out.println("Bike is created");}

public static void main(String args[]){


Bike b=new Bike();
}
}
Output:Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a


default constructor.

Que)What is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending
on the type.
Example of default constructor that displays the default
values

class Student{
int id;
String name;

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1=new Student();
Student s2=new Student();
s1.display();
s2.display();
}
}
Output:0 null
0 null

Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor.Here 0 and null values are provided by default
constructor.

Parameterized constructor
A constructor that have parameters is known as parameterized constructor.

Why use parameterized constructor?


Parameterized constructor is used to provide different values to the distinct objects.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.

class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
Output:111 Karan
222 Aryan

Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number
of constructors that differ in parameter lists.The compiler differentiates these
constructors by taking into account the number of parameters in the list and their
type.

Example of Constructor Overloading

class Student{
int id;
String name;
int age;
Student(int i,String n){
id = i;
name = n;
}
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:111 Karan 0
222 Aryan 25

What is the difference between constructor and method ?


There are many differences between constructors and methods. They are given
below.

Constructor Method

Constructor is used to initialize the state of an object. Method is used to expose behaviour o
an object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if you Method is not provided by compiler in
don't have any constructor. any case.

Constructor name must be same as the class name. Method name may or may not be
same as class name.

Copying the values of one object to another like copy


constructor in C++
There are many ways to copy the values of one object into another. They are:

 By constructor
 By assigning the values of one object into another
 By clone() method of Object class

In this example, we are going to copy the values of one object into another using
constructor.

class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}

Student(Student s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1 = new Student(111,"Karan");
Student s2 = new Student(s1);
s1.display();
s2.display();
}
}
Output:111 Karan
111 Karan

Copying the values of one object to another without constructor


We can copy the values of one object into another by assigning the objects values to
another object. In this case, there is no need to create the constructor.

class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
Student(){}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1 = new Student(111,"Karan");
Student s2 = new Student();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
Output:111 Karan
111 Karan

Que)Does constructor return any value?


Ans:yes,that is current class instance (You cannot use return type yet it returns a
value).

Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling method etc. You can perform any
operation in the constructor as you perform in the method.

Method Overloading in Java


If a class have multiple methods by same name but different parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases
the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behaviour of the method because its name differs. So,
we perform method overloading to figure out the program quickly.
Advantage of method overloading?

Method overloading increases the readability of the program.

Different ways to overload the method


There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In java, Methood Overloading is not possible by changing the return type of the
method.

1)Example of Method Overloading by changing the no. of


arguments
In this example, we have created two overloaded methods, first sum method
performs addition of two numbers and second sum method performs addition of three
numbers.

class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){


Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);

}
}
Output:30
40

2)Example of Method Overloading by changing data type of


argument
In this example, we have created two overloaded methods that differs in data type.
The first sum method receives two integer arguments and second sum method
receives two double arguments.

class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}

public static void main(String args[]){


Calculation obj=new Calculation();
obj.sum(10.5,10.5);
obj.sum(20,20);

}
}
Output:21.0
40

Que) Why Method Overloaing is not possible by changing the return


type of method?
In java, method overloading is not possible by changing the return type of the
method because there may occur ambiguity. Let's see how ambiguity may occur:

because there was problem:

class Calculation{
int sum(int a,int b){System.out.println(a+b);}
double sum(int a,int b){System.out.println(a+b);}
public static void main(String args[]){
Calculation obj=new Calculation();
int result=obj.sum(20,20); //Compile Time Error

}
}

int result=obj.sum(20,20); //Here how can java determine which sum() method should
be called

Can we overload main() method?

Yes, by method overloading. You can have any number of main methods in a class by
method overloading. Let's see the simple example:

class Simple{
public static void main(int a){
System.out.println(a);
}

public static void main(String args[]){


System.out.println("main() method invoked");
main(10);
}
}
Output:main() method invoked
10

Method Overloading and TypePromotion


One type is promoted to another implicitly if no matching datatype is found. Let's
understand the concept by the figure given below:
As displayed in the above diagram, byte can be promoted to short, int, long, float or
double. The short datatype can be promoted to int,long,float or double. The char
datatype can be promoted to int,long,float or double and so on.

Example of Method Overloading with TypePromotion

class Calculation{
void sum(int a,long b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){


Calculation obj=new Calculation();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);

}
}
Output:40
60

Example of Method Overloading with TypePromotion if


matching found
If there are matching type arguments in the method, type promotion is not
performed.

class Calculation{
void sum(int a,int b){System.out.println("int arg method invoked");}
void sum(long a,long b){System.out.println("long arg method invoked");}

public static void main(String args[]){


Calculation obj=new Calculation();
obj.sum(20,20);//now int arg sum() method gets invoked
}
}
Output:int arg method invoked

Example of Method Overloading with TypePromotion in case


ambiguity
If there are no matching type arguments in the method, and each method promotes
similar number of arguments, there will be ambiguity.

class Calculation{
void sum(int a,long b){System.out.println("a method invoked");}
void sum(long a,int b){System.out.println("b method invoked");}

public static void main(String args[]){


Calculation obj=new Calculation();
obj.sum(20,20);//now ambiguity
}
}
Output:Compile Time Error

One type is not depromoted implicitely for example double cannot be


depromoted to any type implicitely.

static keyword
The static keyword is used in java mainly for memory management. We may apply
static keyword with variables, methods, blocks and nested class. The static keyword
belongs to the class than instance of the class.

The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
3. block

1) static variable
If you declare any variable as static, it is known static variable.

 The static variable can be used to refer the common property of all objects (that
is not unique for each object) e.g. company name of employees,college name of
students etc.
 The static variable gets memory only once in class area at the time of class
loading.

Advantage of static variable


It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable

class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get
memory each time when object is created.All student have its unique rollno and name so
instance data member is good.Here, college refers to the common property of all
objects.If we make it static,this field will get memory only once.

static property is shared to all objects.

Example of static variable


//Program of static variable

class Student{
int rollno;
String name;
static String college ="ITS";

Student(int r,String n){


rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student s1 = new Student (111,"Karan");
Student s2 = new Student (222,"Aryan");

s1.display();
s2.display();
}
}
Output:111 Karan ITS
222 Aryan ITS
Program of counter without static variable
In this example, we have created an instance variable named count which is
incremented in the constructor. Since instance variable gets the memory at the time
of object creation, each object will have the copy of the instance variable, if it is
incremented, it won't reflect to other objects. So each objects will have the value 1 in
the count variable.

class Counter{
int count=0;//will get memory when instance is created

Counter(){
count++;
System.out.println(count);
}

public static void main(String args[]){

Counter c1=new Counter();


Counter c2=new Counter();
Counter c3=new Counter();

}}

Output:1
1
1

Program of counter by static variable


As we have mentioned above, static variable will get the memory only once, if any
object changes the value of the static variable, it will retain its value.

class Counter{
static int count=0;//will get memory only once and retain its value

Counter(){
count++;
System.out.println(count);
}

public static void main(String args[]){

Counter c1=new Counter();


Counter c2=new Counter();
Counter c3=new Counter();

}}

Output:1
2
3

2) static method
If you apply static keyword with any method, it is known as static method.

 A static method belongs to the class rather than object of a class.


 A static method can be invoked without the need for creating an instance of a
class.
 static method can access static data member and can change the value of it.

Example of static method


//Program of changing the common property of all objects(static field).

class Student{
int rollno;
String name;
static String college = "ITS";

static void change(){


college = "BBDIT";
}

Student(int r, String n){


rollno = r;
name = n;
}

void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student.change();

Student s1 = new Student (111,"Karan");


Student s2 = new Student (222,"Aryan");
Student s3 = new Student (333,"Sonoo");

s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Another example of static method that performs normal
calculation
//Program to get cube of a given number by static method

Class Calculate{

static int cube(int x){


return x*x*x;
}

public static void main(String args[]){


int result=Calculate.cube(5);
System.out.println(result);
}
}
Output:125

Restrictions for static method


There are two main restrictions for the static method. They are:

1. The static method can not use non static data member or call non-static
method directly.
2. this and super cannot be used in static context.

class A{
int a=40;//non static

public static void main(String args[]){


System.out.println(a);
}
}
Output:Compile Time Error

Que)why main method is static?


Ans) because object is not required to call static method if it were non-static method,
jvm creats object first then call main() method that will lead the problem of extra
memory allocation.
3)static block
 Is used to initialize the static data member.
 It is excuted before main method at the time of classloading.

Example of static block


class A{

static{System.out.println("static block is invoked");}

public static void main(String args[]){


System.out.println("Hello main");
}
}
Output:static block is invoked
Hello main

Que)Can we execute a program without main() method?


Ans)Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.

class A{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
Output:static block is invoked (if not JDK7)

this keyword
There can be a lot of usage of this keyword. In java, this is a reference variable that
refers to the current object.

Usage of this keyword


Here is given the 6 usage of this keyword.

1. this keyword can be used to refer current class instance variable.


2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance.

Suggestion:If you are beginner to java, lookup only two usage of this keyword.

1) The this keyword can be used to refer current class instance


variable.
If there is ambiguity between the instance variable and parameter, this keyword
resolves the problem of ambiguity.

Understanding the problem without this keyword

Let's understand the problem if we don't use this keyword by the example given
below:

class student{
int id;
String name;

student(int id,String name){


id = id;
name = name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


student s1 = new student(111,"Karan");
student s2 = new student(321,"Aryan");
s1.display();
s2.display();
}
}
Output:0 null
0 null

In the above example, parameter (formal arguments) and instance variables are
same that is why we are using this keyword to distinguish between local variable and
instance variable.

Solution of the above problem by this keyword

//example of this keyword

class Student{
int id;
String name;

student(int id,String name){


this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
Output:111 Karan
222 Aryan
If local variables(formal arguments) and instance variables are different, there is no
need to use this keyword like in the following program:

Program where this keyword is not required

class Student{
int id;
String name;

student(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student e1 = new Student(111,"karan");
Student e2 = new Student(222,"Aryan");
e1.display();
e2.display();
}
}
Output:111 Karan
222 Aryan

2) this() can be used to invoked current class constructor.


The this() constructor call can be used to invoke the current class constructor
(constructor chaining). This approach is better if you have many constructors in the class
and want to reuse that constructor.

//Program of this() constructor call (constructor chaining)

class Student{
int id;
String name;
Student (){System.out.println("default constructor is invoked");}

Student(int id,String name){


this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student e1 = new Student(111,"karan");
Student e2 = new Student(222,"Aryan");
e1.display();
e2.display();
}
}
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan

Where to use this() constructor call?


The this() constructor call should be used to reuse the constructor in the constructor.
It maintains the chain between the constructors i.e. it is used for constructor
chaining. Let's see the example given below that displays the actual use of this
keyword.

class Student{
int id;
String name;
String city;

Student(int id,String name){


this.id = id;
this.name = name;
}
Student(int id,String name,String city){
this(id,name);//now no need to initialize id and name
this.city=city;
}
void display(){System.out.println(id+" "+name+" "+city);}

public static void main(String args[]){


Student e1 = new Student(111,"karan");
Student e2 = new Student(222,"Aryan","delhi");
e1.display();
e2.display();
}
}
Output:111 Karan null
222 Aryan delhi

Rule: Call to this() must be the first statement in constructor.

class Student{
int id;
String name;
Student (){System.out.println("default constructor is invoked");}

Student(int id,String name){


id = id;
name = name;
this ();//must be the first statement
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student e1 = new Student(111,"karan");
Student e2 = new Student(222,"Aryan");
e1.display();
e2.display();
}
}
Output:Compile Time Error

3)The this keyword can be used to invoke current class method


(implicitly).
You may invoke the method of the current class by using the this keyword. If you
don't use the this keyword, compiler automatically adds this keyword while invoking
the method. Let's see the example

class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}
Output:method is invoked

4) this keyword can be passed as an argument in the method.


The this keyword can also be passed as an argument in the method. It is mainly used
in the event handling. Let's see the example:

class S{
void m(S obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}

public static void main(String args[]){


S s1 = new S();
s1.p();
}
}
Output:method is invoked

Application of this that can be passed as an argument:


In event handling (or) in a situation where we have to provide reference of a class to
another one.

5) The this keyword can be passed as argument in the


constructor call.
We can pass the this keyword in the constructor also. It is useful if we have to use
one object in multiple classes. Let's see the example:

class B{
A obj;
B(A obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A class
}
}

class A{
int data=10;
A(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A a=new A();
}
}

Output:10

6) The this keyword can be used to return current class


instance.
We can return the this keyword as an statement from the method. In such case,
return type of the method must be the class type (non-primitive). Let's see the
example:

Syntax of this that can be returned as a statement


return_type method_name(){
return this;
}

Example of this keyword that you return as a statement from


the method

class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}

class Test{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:Hello java

Proving this keyword


Let's prove that this keyword refers to the current class instance variable. In this
program, we are printing the reference variable and this, output of both variables are
same.

class A{
void m(){
System.out.println(this);//prints same reference ID
}

public static void main(String args[]){


A obj=new A();
System.out.println(obj);//prints the reference ID

obj.m();
}
}
Output:A@13d9c02
A@13d9c02

NAGGETA NAGGETA ネcト


A

Inheritance in Java
Inheritance is a mechanism in which one object acquires all the properties and behaviours of parent
object.Inheritance represents the IS-A relationship.
Why use Inheritance?

1. For Method Overriding (So Runtime Polymorphism).


2. For Code Reusability.

Syntax of Inheritance

class Subclass-name extends Superclass-name

//methods and fields

The keyword extends indicates that you are making a new class that derives from an existing class. In
the terminology of Java, a class that is inherited is called a superclass. The new class is called a
subclass.

Understanding the simple example of inheritance

inheritance in java

Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a
type of Employee.

class Employee

float salary=40000;

}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output: Programmer salary is:40000.0
Bonus of programmer is:10000

Types of Inheritance
On the basis of class, there can be three types of inheritance: single, multilevel and
hierarchical.Multiple and Hybrid is supported through interface only. We will learn about interfaces
later.

types of inheritance in java

Note:Multiple inheritance is not supported in java in case of class.

When a class extends multiple classes i.e. known as multiple inheritance. For Example:
multiple inheritance in java

Que) Why multiple inheritance is not supported in java?

Ans.To reduce the complexity and simplify the language, multiple inheritance is not supported in
java. For example:

class A
{
void msg(){System.out.println("Hello");}
}

class B
{
void msg()
{System.out.println("Welcome");}
}
class C extends A,B
{//suppose if it were

Public Static void main(String args[])


{
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
NAGGETA N A G G E T A
dŠ

A
NAGGETA NAGGETA ネcト
A

Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents
HAS-A relationship.
Consider a situation, Employee object contains many informations such as id, name,
emailId etc. It contains one more object named address, which contains its own
informations such as city, state, country, zipcode etc. as given below.

class Employee{
int id;
String name;
Address address;//Address is a class
...
}

In such case, Employee has an entity reference address, so relationship is Employee


HAS-A address.

Why use Aggregation?


 For Code Reusability.

Simple Example of Aggregation

In this example, we have created the reference of Operation class in the Circle class.

class Operation{
int square(int n){
return n*n;
}
}

class Circle{
Operation op;//aggregation
double pi=3.14;

double area(int radius){


op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the
method call).
return pi*rsquare;
}

public static void main(String args[]){


Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}
}
Output:78.5

When use Aggregation?


 Code reuse is also best achieved by aggregation when there is no is-a
relationship.
 Inheritance should be used only if the relationship is-a is maintained throughout
the lifetime of the objects involved; otherwise, aggregation is the best choice.

Understanding meaningful example of Aggregation


In this example, Employee has an object of Address, address object contains its own
informations such as city, state, country etc. In such case relationship is Employee HAS-
A address.

Address.java

public class Address {


String city,state,country;

public Address(String city, String state, String country) {


this.city = city;
this.state = state;
this.country = country;
}

Emp.java

public class Emp {


int id;
String name;
Address address;

public Emp(int id, String name,Address address) {


this.id = id;
this.name = name;
this.address=address;
}

void display(){
System.out.println(id+" "+name);
System.out.println(address.city+" "+address.state+" "+address.country);
}

public static void main(String[] args) {


Address address1=new Address("gzb","UP","india");
Address address2=new Address("gno","UP","india");

Emp e=new Emp(111,"varun",address1);


Emp e2=new Emp(112,"arun",address2);

e.display();
e2.display();

}
}
NAGGETA NAGGETA ネcト
A
NAGEETA NAGEETA 3鷁 皡! 磖繽
0OM H ! 瑷胈1Gzw€ kZ H ! ` ! 洙胈

Method Overriding in Java


Having the same method in the subclass as declared in the parent class is known
as method overriding.

In other words, If subclass provides the specific implementation of the method i.e.
already provided by its parent class, it is known as Method Overriding.

Advantage of Method Overriding


 Method Overriding is used to provide specific implementation of a method that is
already provided by its super class.
 Method Overriding is used for Runtime Polymorphism

Rules for Method Overriding:

1. method must have same name as in the parent class


2. method must have same parameter as in the parent class.
3. must be inheritance (IS-A) relationship.

Understanding the problem without mehtod overriding

Let's understand the problem that we may face in the program if we don't use method
overriding.

class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{

public static void main(String args[]){


Bike obj = new Bike();
obj.run();
}
}
Output:Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass
that is why we use method overriding.

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation. The name and parameter of the
method is same and there is IS-A relationship between the classes, so there is method
overriding.

class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike obj = new Bike();
obj.run();
}
}
Output:Bike is running safely

Can we override static method?


No, static method cannot be overridden. It can be proved by runtime polymorphism
so we will learn it later.

Why we cannot override static method?


because static method is bound with class whereas instance method is bound with
object. Static belongs to class area and instance belongs to heap area.

What is the difference between method Overloading and Method Overriding?

There are three basic differences between the method overloading and method
overriding. They are as follows:
Method Overriding

1) Method overloading is used to Method overriding is used to provide the specific


increase the readability of the implementation of the method that is already provided by
program. its super class.

2) method overlaoding is performed Method overriding occurs in two classes that have IS-A
within a class. relationship.

3) In case of method overloading In case of method overriding parameter must be same.


parameter must be different.

NAGGETA NAGGETA ネcト


A
NAGGETA N A G G E T A
dŠ

super keyword
The super is a reference variable that is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitely i.e. referred by super reference variable.

Usage of super Keyword

1. super is used to refer immediate parent class instance variable.


2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.

1) super is used to refer immediate parent class instance


variable.
Problem without super keyword

class Vehicle{
int speed=50;
}

class Bike extends Vehicle{


int speed=100;
void display(){
System.out.println(speed);//will print speed of Bike
}
public static void main(String args[]){
Bike b=new Bike();
b.display();

}
}
Output:100
In the above example Vehicle and Bike both class have a common property speed.
Instance variable of current class is refered by instance bydefault, but I have to refer
parent class instance variable that is why we use super keyword to distinguish
between parent class instance variable and current class instance variable.

Solution by super keyword

//example of super keyword

class Vehicle{
int speed=50;
}

class Bike extends Vehicle{


int speed=100;

void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike b=new Bike();
b.display();

}
}
Output:50

2) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor as given
below:

class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}

class Bike extends Vehicle{


Bike(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike b=new Bike();

}
}
Output:Vehicle is created
Bike is created

super() is added in each class construtor automatically by compiler.


As we know well that default constructor is provided by compiler automatically but it
also adds super() for the first statement.If you are creating your own constructor and
you don't have either this() or super() as the first statement, compiler will provide
super() as the first statement of the consructor.

Another example of super keyword where super() is provided by the


compiler implicitely.

class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}

class Bike extends Vehicle{


int speed;
Bike(int speed){
this.speed=speed;
System.out.println(speed);
}
public static void main(String args[]){
Bike b=new Bike(10);
}
}
Output:Vehicle is created
10

3) super can be used to invoke parent class method.


The super keyword can also be used to invoke parent class method. It should be used
in case subclass contains the same method as parent class as in the example given
below:

class Person{
void message(){System.out.println("welcome");}
}

class Student extends Person{


void message(){System.out.println("welcome to java");}

void dislay(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}

public static void main(String args[]){


Student s=new Student();
s.display();
}
}

Output:welcome to java
welcome
In the above example Student and Person both classes have message() method if we
call message() method from Student class, it will call the message() method of
Student class not of Person class because priority is given to local.

In case there is no method in subclass as parent, there is no need to use super. In


the example given below message() method is invoked from Student class but
Student class does not have message() method, so you can directly call message()
method.

Program in case super is not required

class Person{
void message(){System.out.println("welcome");}
}

class Student extends Person{

void dislay(){
message();//will invoke parent class message() method
}

public static void main(String args[]){


Student s=new Student();
s.display();
}
}

Output:welcome
NAGGETA NAGGETA ネcト
A
NAGGETA N A G G E T A
dŠ

Instance initializer block:


Instance Initializer block is used to initialize the instance data member. It run each
time when object of the class is created.

The initialization of the instance variable can be directly but there can be performed
extra operations while initilizing the instance variable in the instance initializer block.

Que) What is the use of instance initializer block while we can directly
assign a value in instance data member? For example:

class Bike{
int speed=100;
}

Why use instance initializer block?


Suppose I have to perform some operations while assigning value to instance data
member e.g. a for loop to fill a complex array or error handling etc.

Example of Instance initializer block


Let's see the simple example of intance initializer block the performs initialization.

//Program of instance initializer block that initializes values to the


instance variable

class Bike{
int speed;

Bike(){System.out.println("speed is "+speed);}

{speed=100;}

public static void main(String args[]){


Bike b1=new Bike();
Bike b2=new Bike();
}
}
Output:speed is 100
speed is 100

There are three places in java where you can perform operations:

1. method
2. constructor
3. block

What is invoked firstly instance initializer block or


constructor?
//Program of instance initializer block

class Bike{
int speed;

Bike(){System.out.println("constructor is invoked");}

{System.out.println("instance initializer block invoked");}

public static void main(String args[]){


Bike b1=new Bike();
Bike b2=new Bike();
}
}
Output:instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked

In the above example, it seems that instance initializer block is firstly invoked but NO.
Instance intializer block is invoked at the time of object creation. The java compiler
copies the instance initializer block in the costructor after the first statement super().
So firstly, constructor is invoked. Let's understand it by the figure given below:
Note: The java compiler copies the code of instance initializer block in
every constructor.

Rules for instance initializer block :


There are mainly three rules for the instance initializer block. They are as follows:

1. The instance initializer block is created when instance of the class is created.
2. The instance initializer block is invoked after the parent class constructor is
invoked (i.e. after super() constructor call).
3. The instance initializer block comes in the order in which they appear.

Program of instance initializer block that is invoked after


super()
//Program of instance initializer block that is invoked after super()

class A{
A(){
System.out.println("parent class constructor invoked");
}

class B extends A{

B(){
super();
System.out.println("child class constructor invoked");
}

{System.out.println("instance initializer block is invoked");}

public static void main(String args[]){


B b=new B();
}
}

Output:parent class constructor invoked


instance initializer block is invoked
child class constructor invoked

//Another example of instance initializer block that is invoked after


super()

class A{

A(){
System.out.println("parent class constructor invoked");
}

class B extends A{
B(){
super();

System.out.println("child class constructor invoked");


}

B(int a){
super();

System.out.println("child class constructor invoked "+a);


}

{System.out.println("instance initializer block is invoked");}

public static void main(String args[]){


B b1=new B();
B b2=new B(10);
}
}

Output:parent class constructor invoked


instance initializer block is invoked
child class constructor invoked
parent class constructor invoked
instance initializer block is invoked
child class constructor invoked 10

NAGGETA NAGGETA ネcト


A
NAGGETA NAGGETA ネcI
A

Final Keyword in Java


The final keyword in java is used to restrict the user. The final keyword can be used in
many context. Final can be:

1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of
final keyword.

1) final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but
It can't be changed because final variable once assigned a value can never be changed.

class Bike{
final int speedlimit=90;//final variable

void run(){
speedlimit=400;
}

public static void main(String args[]){


Bike obj=new Bike();
obj.run();
}
}
Output:Compile Time Error

2) final method
If you make any method as final, you cannot override it.
Example of final method
class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error

3) final class
If you make any class as final, you cannot extend it.

Example of final class


final class Bike{}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}

Output:Compile Time Error

Q) Is final method inherited?


Ans)Yes, final method is inherited but you cannot override it. For Example:

class Bike{
final void run(){System.out.println("running...");}
}
class Honda extends Bike{

public static void main(String args[]){


new Honda().run();
}
}
Output:running...

Q) What is blank final variable?


A final variable that is not initalized at the time of declaration is known as blank final
variable. If you want to create a variable that is initialized at the time of creating
object and once initialized may not be changed, it is useful. For example PAN CARD
number of an employee. It can be initialized only in constuctor.

Example of blank final variable


class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}

Que) Can we intialize blank final variable?


Yes, but only in constructor. For example:

class Bike{
final int speedlimit;//blank final variable

Bike(){
speedlimit=70;
System.out.println(speedlimit);
}

public Static void main(String args[]){


new Bike();
}
}
Output:70

static blank final variable


A static final variable that is not initalized at the time of declaration is known as static
blank final variable. It can be initialized only in static block.

Example of static blank final variable


class A{
static final int data;//static blank final variable

static{ data=50;}

public Static void main(String args[]){


System.out.println(A.data);
}
}

Q) What is final parameter?


If you declare any parameter as final, you cannot change the value of it.

class Bike{
int cube(final int n){
n=n+2;//can't be changed as n is final
n*n*n;
}

public Static void main(String args[]){


Bike b=new Bike();
b.cube(5);
}
}
Output:Compile Time Error

Q) Can we declare a constructor final?


No, because constructor is never inherited.
NAGGETA NAGGETA ネcト
A
NAGGETA NAGGETA ネcI
A

Abstract class in Java


Before abstract class, let's understand the abstraction first.

Abstraction
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.

Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the
internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstaction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class

A class that is declared as abstract is known as abstract class. It needs to be extended


and its method implemented. It cannot be instantiated.

Syntax to declare the abstract class

abstract class <class_name>{}

abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.

Syntax to define the abstract method

abstract return_type <method_name>();//no braces{}


Example of abstract class that have abstract method

In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.

abstract class Bike{


abstract void run();
}

class Honda extends Bike{


void run(){System.out.println("running safely..");}

public static void main(String args[]){


Bike obj = new Honda();
obj.run();
}
}
Output:running safely..

Understanding the real scenario of abstract class

In this example, Shape is the abstract class, its implementation is provided by the
Rectangle and Circle classes. Mostly, we don't know about the implementation class (i.e.
hidden to the end user) and object of the implementation class is provided by
the factory method.

A factory method is the method that returns the instance of the class. We will learn
about the factory method later.

In this example, if you create the instance of Rectangle class, draw method of Rectangle
class will be invoked.

abstract class Shape{


abstract void draw();
}

class Rectangle extends Shape{


void draw(){System.out.println("drawing rectangle");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle");}
}

class Test{
public static void main(String args[]){
Shape s=new Circle();
//In real scenario, Object is provided through factory method
s.draw();
}
}
Output:drawing circle

Abstract class having constructor, data member, methods etc.

Note: An abstract class can have data member, abstract method, method body,
constructor and even main() method.

//example of abstract class that have method body

abstract class Bike{


abstract void run();
void changeGear(){System.out.println("gear changed");}
}

class Honda extends Bike{


void run(){System.out.println("running safely..");}

public static void main(String args[]){


Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Output:running safely..
gear changed
//example of abstract class having constructor, field and method
abstract class Bike
{
int limit=30;
Bike(){System.out.println("constructor is invoked");}
void getDetails(){System.out.println("it has two wheels");}
abstract void run();
}

class Honda extends Bike{


void run(){System.out.println("running safely..");}

public static void main(String args[]){


Bike obj = new Honda();
obj.run();
obj.getDetails();
System.out.println(obj.limit);
}
}
Output:constructor is invoked
running safely..
it has two wheels
30

Rule: If there is any abstract method in a class, that class must be abstract.

class Bike{
abstract void run();
}
Output:compile time error

Rule: If you are extending any abstact class that have abstract method, you must
either provide the implementation of the method or make this class abstract.

Another real scenario of abstract class

The abstract class can also be used to provide some implementation of the interface. In
such case, the end user may not be forced to override all the methods of the interface.

Note: If you are beginner to java, learn interface first and skip this example.

interface A{
void a();
void b();
void c();
void d();
}

abstract class B implements A{


public void c(){System.out.println("I am C");}
}

class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}

class Test{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Output:I am a
I am b
I am c
I am d

NAGEETA NAGEETAlTA+司temSizeミ hT A,・0 X゚ ! tT A-・ ノ ・ノ タ ノ

Interface
An interface is a blueprint of a class. It has static constants and abstract methods.

The interface is a mechanism to achieve fully abstraction in java. There can be only
abstract methods in the interface. It is used to achieve fully abstraction and multiple
inheritance in Java.

Interface also represents IS-A relationship.


It cannot be instantiated just like abstract class.

Why use Interface?


There are mainly three reasons to use interface. They are given below.

 It is used to achieve fully abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.

The java compiler adds public and abstract keywords before the interface
method and public, static and final keywords before data members.

In other words, Interface fields are public, static and final bydefault, and methods are
public and abstract.

Understanding relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.

Simple example of Interface


In this exmple, Printable interface have only one method, its implemenation is
provided in the A class.

interface printable{
void print();
}

class A implements printable{


public void print(){System.out.println("Hello");}

public static void main(String args[]){


A obj = new A();
obj.print();
}
}
Output:Hello

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.
known as multiple inheritance.
interface Printable{
void print();
}

interface Showable{
void show();
}

class A implements Printable,Showable{

public void print(){System.out.println("Hello");}


public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A obj = new A();
obj.print();
obj.show();
}
}
Output:Hello
Welcome

Q) Multiple inheritance is not supported in case of class but it is


supported in case of interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported
in case of class. But it is supported in case of interface because there is no ambiguity
as implmentation is provided by the implementation class. For example:

interface Printable{
void print();
}

interface Showable{
void print();
}

class A implements Printable,Showable{

public void print(){System.out.println("Hello");}

public static void main(String args[]){


A obj = new A();
obj.print();
}
}
Output:Hello
As you can see in the above example, Printable and Showable interface have same
methods but its implementation is provided by class A, so there is no ambiguity.

Note: A class implements interface but One interface extends another interface .

interface Printable{
void print();
}

interface Showable extends Printable{


void show();
}

class A implements Showable{


public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A obj = new A();
obj.print();
obj.show();
}
}
Output:Hello
Welcome

Que) What is marker or tagged interface ?

An interface that have no member is known as marker or tagged interface. For


example: Serializable, Cloneable, Remote etc. They are used to provide some
essential information to the JVM so that JVM may perform some useful operation.

//How Serializable interface is written?

public interface Serializable


{
}

Nested Interface

Note: An interface can have another interface i.e. known as nested interface. We will
learn it in detail in the nested classes chapter. For example:

interface printable{
void print();
interface MessagePrintable{
void msg();
}
}
gaurav singh
g a u r a v
s i n g h û• .( ï:Ú6S’
R7ú§û• {

Runtime Polymorphism
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to
an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a


superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:

class A{}
class B extends A{}
A a=new B();//upcasting

Example of Runtime Polymorphism


In this example, we are creating two classes Bike and Splendar. Splendar class extends
Bike class and overrides its run() method. We are calling the run method by the
reference variable of Parent class. Since it refers to the subclass object and subclass
method overrides the Parent class method, subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.

class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splender();//upcasting
b.run();
}
}
Output: running safely with 60km.

Runtime Polymorphism with data member


Method is overriden not the datamembers, so runtime polymorphism can't be
achieved by data members.

In the example given below, both the classes have a datamember speedlimit, we are
accessing the datamember by the reference variable of Parent class which refers to
the subclass object. Since we are accessing the datamember which is not overridden,
hence it will access the datamember of Parent class always.

Rule: Runtime polymorphism can't be achieved by data members.

class Bike{
int speedlimit=90;
}
class Honda extends Bike{
int speedlimit=150;

public static void main(String args[]){


Bike obj=new Honda();
System.out.println(obj.speedlimit);//90
}
}
Output: 90
Runtime Polymorphism with Multilevel Inheritance
Let's see the simple example of Runtime Polymorphism with multilevel inheritance.

class Animal{
void eat(){System.out.println("eating");}
}

class Dog extends Animal{


void eat(){System.out.println("eating fruits");}
}

class BabyDog extends Dog{


void eat(){System.out.println("drinking milk");}

public static void main(String args[]){


Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();

a1.eat();
a2.eat();
a3.eat();
}
}
Output: eating
eating fruits
drinking Milk

Try for Output


class Animal{
void eat(){System.out.println("animal is eating...");}
}

class Dog extends Animal{


void eat(){System.out.println("dog is eating...");}
}
class BabyDog extends Dog{
public static void main(String args[]){
Animal a=new BabyDog();
a.eat();
}}
Output: Dog is eating

Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is
invoked.

Static Binding and Dynamic Binding

Connecting a method call to the method body is known as binding.

There are two types of binding

1. static binding (also known as early binding).


2. dynamic binding (also known as late binding).

Understanding Type
Let's understand the type of instance.

1) variables have a type

Each variable has a type, it may be primitive and non-primitive.

int data=30;

Here data variable is a type of int.

2) References have a type

class Dog{
public static void main(String args[]){
Dog d1;//Here d1 is a type of Dog
}
}

3) Objects have a type

An object is an instance of particular java class,but it is also an instance of its


superclass.

class Animal{}

class Dog extends Animal{


public static void main(String args[]){
Dog d1=new Dog();
}
}
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding

When type of the object is determined at compiled time(by the compiler), it is known as
static binding.

If there is any private, final or static method in a class, there is static binding.

Example of static binding


class Dog{
private void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Dog d1=new Dog();
d1.eat();
}
}

Dynamic binding

When type of the object is determined at run-time, it is known as dynamic binding.


Example of dynamic binding:
class Animal{
void eat(){System.out.println("animal is eating...");}
}

class Dog extends Animal{


void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Animal a=new Dog();
a.eat();
}
}
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the
instance of Dog is also an instance of Animal.So compiler doesn't know its type, only
its base type.

NAGGETA NAGGETA 澆D
Arial
NAGGETA NAGGETA ネcト
A
NAGGETA NAGGETA ネcト
A
NAGGETA NAGGETA 澆D
Arial

instanceof operator
The instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).

The instanceof operator is also known as type comparison operator because it compares
the instance with type. It returns either true or false. If we apply the instanceof operator
with any variable that have null value, it returns false.

Simple example of instanceof operator


Let's see the simple example of instance operator where it tests the current class.
class Simple{
public static void main(String args[]){
Simple s=new Simple();
System.out.println(s instanceof Simple);//true
}
}
Output:true

An object of subclass type is also a type of parent class. For example, if Dog extends
Animal then object of Dog can be reffered by either Dog or Animal class.

Another example of instanceof operator

class Animal{}

class Dog extends Animal{//Dog inherits Animal

public static void main(String args[]){


Dog d=new Dog();
System.out.println(d instanceof Animal);//true
}
}
Output:true

instanceof operator with a variable that have null value


If we apply instanceof operator with a variable that have null value, it ruturns false.
Let's see the example given below where we apply instanceof operator with the
variable that have null value.

class Dog{
public static void main(String args[]){
Dog d=null;
System.out.println(d instanceof Dog);//false
}
}
Output:false

Downcasting with instanceof operator


When Subclass type refers to the object of Parent class, it is known as downcasting. If
we perform it directly, compiler gives Compilation error. If you perform it by
typecasting, ClassCastException is thrown at runtime. But if we use instanceof
operator, downcasting is possible.

Dog d=new Animal();//Compilation error

If we perform downcasting by typecasting, ClassCastException is thrown at runtime.

Dog d=(Dog)new Animal();


//Compiles successfully but ClassCastException is thrown at runtime

Possibility of downcasting with instanceof operator


Let's see the example, where downcasting is possible by instanceof operator.

class Animal { }

class Dog extends Animal {


static void method(Animal a) {
if(a instanceof Dog){
Dog d=(Dog)a;//downcasting
System.out.println("ok downcasting performed");
}
}

public static void main (String [] args) {


Animal a=new Dog();
Dog.method(a);
}

}
Output:ok downcasting performed
Downcasting without the use of instanceof operator
Downcasting can also be performed without the use of instanceof operator as
displayed in the following example:

class Animal { }

class Dog extends Animal {


static void method(Animal a) {
Dog d=(Dog)a;//downcasting
System.out.println("ok downcasting performed");
}

public static void main (String [] args) {


Animal a=new Dog();
Dog.method(a);
}

}
Output:ok downcasting performed
Let's take closer look at this, actual object that is referred by a, is an object of Dog
class. So if we downcast it, it is fine. But what will happen if we write:

Animal a=new Animal();


Dog.method(a);

//Now ClassCastException but not in case of instanceof operator

Understanding Real use of instanceof operator


Let's see the real use of instanceof operator by the example given below.

interface Printable{}

class A implements Printable{


public void a(){System.out.println("my a method");}
}
class B implements Printable{
public void b(){System.out.println("my a method");}
}

class Call{
void invoke(Printable p){//upcasting

if(p instanceof A){


A a=(A)p;//Downcasting
a.a();
}
if(p instanceof B){
B b=(B)p;//Downcasting
b.b();
}

}
}//end of Call class

class Test{
public static void main(String args[]){
Printable p=new B();
Call c=new Call();
c.invoke(p);
}
}

NAGGETA NAGGETA ネc\


A
NAGGETA NAGGETA ネcト
A

Package
A package is a group of similar types of classes, interfaces and sub-packages.

Package can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.
Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Package

 Package is used to categorize the classes and interfaces so that they can be
easily maintained.
 Package provides access protection.
 Package removes naming collision.

Simple example of package


The package keyword is used to create a package.

//save as Simple.java

package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile the Package (if not using IDE)

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

For example

javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use
any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you
want to keep the package within the same directory, you can use . (dot).

How to run the Package (if not using IDE)

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.

How to access package from another package?


There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

Using packagename.*

If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.

The import keyword is used to make the classes and interface of another package
accessible to the current package.

Example of package that import the packagename.*


//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

Using packagename.classname

If you import package.classname then only declared class of this package will be
accessible.

Example of package by import package.classname


//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time
when you are accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.

Example of package by import fully qualified name


//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.

Note: Sequence of the program must be package then import then class.

Subpackage
Package inside the package is called the subpackage. It should be created to
categorize the package further.

Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc. These classes
represent a particular group e.g. Reader and Writer classes are for Input/Output
operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun
has subcategorized the java package into subpackages such as lang, net, io etc. and put
the Input/Output related classes in io package, Server and ServerSocket classes in net
packages and so on.

The standard of defining package is domain.company.package e.g.


com.javatpoint.bean or org.sssit.dao.

Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple

Output:Hello subpackage

How to send the class file to another directory or drive?


There is a scenario, I want to put the class file of A.java source file in classes folder of
c: drive. For example:

//save as Simple.java

package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile:
e:\sources> javac –d c:\classes Simple.java

To Run:
To run this program from e:\source directory, you need to set classpath of the
directory where the class file resides.

e:\sources> set classpath=c:\classes;.;

e:\sources> java mypack.Simple

Another way to run this program by -classpath switch of java:


The -classpath switch can be used with javac and java tool.

To run this program from e:\source directory, you can use -classpath switch of java
that tells where to look for class file. For example:

e:\sources> java -classpath c:\classes mypack.Simple

Output:Welcome to package

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.

 Temporary
o By setting the classpath in the command prompt
o By -classpath switch
 Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar
file in the jre/lib/ext folder.

Rule: There can be only one public class in a java source file and it must be
saved by the public class name.

//save as C.java otherwise Compilte Time Error

class A{}
class B{}
public class C{}
How to put two public classes in a package?
If you want to put two public classes in a package, have two java source files
containing one public class, but keep the package name same. For example:

//save as A.java

package javatpoint;
public class A{}

//save as B.java

package javatpoint;
public class B{}

NAGGETA NAGGETA ネcト


A

Access Modifiers
There are two types of modifiers in java: access modifier and non-access modifier.
The access modifiers specifies accessibility (scope) of a datamember, method,
constructor or class.

There are 4 types of access modifiers:

1. private
2. default
3. protected
4. public

There are many non-access modifiers such as static, abstract, synchronized, native,
volatile, transient etc. Here, we will learn access modifiers.

1) private
The private access modifier is accessible only within class.

Simple example of private access modifer


In this example, we have created two classes A and Simple. A class contains private
data member and private method. We are accessing these private members from
outside the class, so there is compile time error.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

Role of Private Constructor:


If you make any class constructor private, you cannot create the instance of that
class from outside the class. For example:

class A{
private A(){}//private constructor

void msg(){System.out.println("Hello java");}


}

public class Simple{


public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}

Note: A class cannot be private or protected except nested class.

2) default
If you don't use any modifier, it is treated as default bydefault. The default modifier
is accessible only within package.

Example of default access modifier


In this example, we have created two packages pack and mypack. We are accessing
the A class from outside its package, since A class is not public, so it cannot be
accessed from outside the package.

//save by A.java

package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it
cannot be accessed from outside the package.

3) protected
The protected access modifier is accessible within package .

The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg
method of this package is declared as protected, so it can be accessed from outside
the class only through inheritance.

//save by A.java

package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello

4) public
The public access modifier is accessible everywhere. It has the widest scope
among all other modiers.

Example of public access modifier


//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

Understanding all java access modifiers


Let's understand the access modfiers by a simple table.

Access Modifier within class within package outside package by subclass only outside package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Applying access modifier with method overriding

If you are overriding any method, overriden method (i.e. declared in subclass)
must not be more restrictive.

class A{
protected void msg(){System.out.println("Hello java");}
}

public class Simple extends A{


void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}

NAGEETA N A G E E T A
3§c ÐT- ´rmd  ì¨pdˆ[Wu`_ 0
è¨pd1Gdv€ _
NAGGETA NAGGETA ネcト
A

Encapsulation in Java
Encapsulation is a process of wrapping code and data together into a single unit e.g.
capsule i.e mixed of several medicines.

We can create a fully encapsulated class by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.

Java Bean is the example of fully encapsulated class.

Advantage of Encapsulation

By providing only setter or getter method, you can make the class read-only or write-
only.

It provides you the control over the data. Suppose you want to set the value of id i.e.
greater than 100 only, you can write the logic inside the setter method.

Simple example of encapsulation in java


Let's see the simple example of encapsulation that has only one field with its setter and
getter methods.

//save as Student.java
package com.myjava;
public class student{
private string name;

public String getName(){


return name;
}
public void setName(String name){
this.name=name
}
}
//save as Test.java
package com.javatpoint;
class Test
public static void main(){
Student s=new Student();
s.setname("vijay");
System.out.println(s.getName());
}
}
Compile By:javac -d . Test.java
Run By:java com.myjava.Test
Output:vijay

NAGGETA NAGGETA ネcト


A

Object Cloning in Java

The object cloning is a way to create exact copy of an object. For this purpose, clone()
method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object
clone we want to create. If we don't implement Cloneable interface, clone() method
generatesCloneNotSupportedException.

The clone() method is defined in the Object class. Syntax of the clone() method is as
follows:

protected Object clone() throws CloneNotSupportedException

Why use clone() method ?

The clone() method saves the extra processing task for creating the exact copy of an
object. If we perform it by using the new keyword, it will take a lot of processing to be
performed that is why we use object cloning.

Advantage of Object cloning

Less processing task.

Example of clone() method (Object cloning)

Let's see the simple example of object cloning

class Student implements Cloneable{


int rollno;
String name;

Student(int rollno,String name){


this.rollno=rollno;
this.name=name;
}

public Object clone()throws CloneNotSupportedException


{
return super.clone();
}

public static void main(String args[]){


try{
Student s1=new Student(101,"amit");

Student s2=(Student)s1.clone();

System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);

}
catch(CloneNotSupportedException c){}

}
}
Output:101 amit
101 amit

NAGGETA N A G G E T A
S t a r t i n g . . .

A
NAGGETA NAGGETA ネcト
A

Array in Java
Normally, array is a collection of similar type of elements that have contigious memory
location.

In java, array is an object the contains elements of similar data type. It is a data
structure where we store similar elements. We can store only fixed elements in an array.

Array is index based, first element of the array is stored at 0 index.

Advantage of Array
 Code Optimization: It makes the code optimized, we can retrive or sort the
data easily.
 Random access: We can get any data located at any index position.
Disadvantage of Array
 Size Limit: We can store only fixed size of elements in the array. It doesn't grow
its size at runtime. To solve this problem, collection framework is used in java.

Types of Array

There are two types of array.

 Single Dimensional Array


 Multidimensional Array

Single Dimensional Array


Syntax to Declare an Array in java
dataType[] arrayRefVar; (or)
dataType []arrayRefVar; (or)
dataType arrayRefVar[];

Instantiation of an Array in java


arrayRefVar=new datatype[size];

Example of single dimensional java array


Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.

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

int a[]=new int[5];//declaration and instantiation


a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;

//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization

Let's see the simple example to print this array.

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

int a[]={33,3,4,5};//declaration, instantiation and initialization

//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);

}}
Output:33
3
4
5

Passing Java Array in the method


We can pass the array in the method so that we can reuse the same logic on any array.

Let's see the simple example to get minimum number of an array using method.
class B{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];

System.out.println(min);
}

public static void main(String args[]){

int a[]={33,3,4,5};
min(a);//passing array in the method

}}
Output:3

Multidimensional array
In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in java


dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to initantiate Multidimensional Array in java


int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in java


arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example of Multidimensional java array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.

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

//declaring and initializing 2D array


int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}

}}
Output:1 2 3
2 4 5
4 4 5

What is class name of java array?


In java, array is an object. For array object, an proxy class is created whose name can
be obtained by getClass().getName() method on the object.

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

int arr[]={4,4,5};

Class c=arr.getClass();
String name=c.getName();
System.out.println(name);
}

}}
Output:[I

Copying an array
We can copy an array to another by the arraycopy method of System class.

Syntax of arraycopy method


public static void arraycopy( Object src, int srcPos,Object dest, int destPos, int length )

Example of arraycopy method

class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];

System.arraycopy(copyFrom, 2, copyTo, 0, 7);


System.out.println(new String(copyTo));
}
}
Output:caffein

Addition 2 matrices
Let's see a simple example that adds two matrices.

class AE{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}

}}
Output:2 6 8
6 8 10

NAGEETA NAGEETA ー- タ7・Tawタ7・ .D 3l・(dw・q 4dwず-

String Handling
String Handling provides a lot of concepts that can be performed on a string such as
concatenating string, comparing string, substring etc.

We will discuss about immutable string later. Let's first understand what is string and
how we can create the string object.

String
Generally string is a sequence of characters. But in java, string is an object. String
class is used to create string object.

How to create String object?


There are two ways to create String object:

1. By string literal
2. By new keyword

1) String literal:
String literal is created by double quote.For Example:
String s="Hello";
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 returns. If the
string does not exist in the pool, a new String object instantiates, then is placed in
the pool.For example:

String s1="Welcome";
String s2="Welcome";//no new object will be created

In the above example only one object will be created.First time JVM will find no string
object with the name "Welcome" in string constant pool,so it will create a new
object.Second time it will find the string with the name "Welcome" in string constant
pool,so it will not create new object whether will return the reference to the same
instance.

Note: String objects are stored in a special memory area known as string
constant pool inside the Heap memory.

Why java uses concept of string literal?


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

2) By new keyword:
String s1=new String("Welcome”);

String s2=new String("Welcome");//creates two objects for same data


In such case, JVM will create a new String object in normal(nonpool) Heap memory
and the literal "Welcome" will be placed in the string constant pool.The variable s will
refer to the object in Heap(nonpool).

Immutable String:
In java, strings are immutable (unmodifiable) objects.For example
class Simple{
public static void main(String args[]){

String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are
immutable objects
}
}

Output:Sachin
As you can see in the above figure that two objects will be created but no reference
variable refers to "Sachin Tendulkar".But if we explicitely assign it to the reference
variable, it will refer to "Sachin Tendulkar" object.For example:
class Simple{
public static void main(String args[]){

String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}

Output:Sachin Tendulkar

String comparison in Java


We can compare two given on the basis of content and reference. It is used in
authentication (equals() method), sorting (compareTo() method) etc.

There are three ways to compare String objects:

1. By equals() method
2. By = = operator
3. By compareTo() method

1) By equals() method:
equals() method compares the original content of the string.It compares values of
string for equality.String class provides two methods:

 public boolean equals(Object another){} compares this string to the


specified object.
 public boolean equalsIgnoreCase(String another){} compares this String to
another String, ignoring case.

//Example of equals(Object) method

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

String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";

System.out.println(s1.equals(s2));//
System.out.println(s1.equals(s3));//
System.out.println(s1.equals(s4));//
}
}

Output:true
true
false
//Example of equalsIgnoreCase(String) method

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

String s1="Sachin";
String s2="SACHIN";

System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s3));//true
}
}

Output:false
true

2) By == operator:
The = = operator compares references not values.

//Example of == operator

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

String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");

System.out.println(s1==s2);//true (because both refer to same


instance)
System.out.println(s1==s3);//false(because s3 refers to instance
created in nonpool)
}
}

Output:true
false

3) By compareTo() method:
compareTo() method compares values and returns an int which tells if the values
compare less than, equal, or greater than.

Suppose s1 and s2 are two string variables.If:

 s1 == s2 :0
 s1 > s2 :positive value
 s1 < s2 :negative value

//Example of compareTo() method:

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

String s1="Sachin";
String s2="Sachin";
String s3="Ratan";

System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}

Output:0
1
-1

String Concatenation in Java


Concating strings form a new string i.e. the combination of multiple strings.

There are two ways to concat string objects:

1. By + (string concatenation) operator


2. By concat() method

1) By + (string concatenation) operator


String concatenation operator is used to add strings.For Example:

//Example of string concatenation operator

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

String s="Sachin"+" Tendulkar";


System.out.println(s);//Sachin Tendulkar
}
}

Output:Sachin Tendulkar

The compiler transforms this to:

String s=new StringBuilder().append("Sachin").append("


Tendulkar).toString();
String concatenation is implemented through the StringBuilder(or StringBuffer) class
and its append method.String concatenation operator produces a new string by
appending the second operand onto the end of the first operand.The string
concatenation operator can concat not only string but primitive values also.For
Example:

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

String s=50+30+"Sachin"+40+40;
System.out.println(s);//80Sachin4040
}
}

Output:80Sachin4040

Note:If either operand is a string, the resulting operation will be string concatenation.
If both operands are numbers, the operator will perform an addition.
2) By concat() method
concat() method concatenates the specified string to the end of current string.

Syntax:public String concat(String another){}

//Example of concat(String) method

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

String s1="Sachin ";


String s2="Tendulkar";

String s3=s1.concat(s2);

System.out.println(s3);//Sachin Tendulkar
}
}

Output:Sachin Tendulkar

Substring in Java

A part of string is called substring. In other words, substring is a subset of another


string.

In case of substring startIndex starts from 0 and endIndex starts from 1 or startIndex is
inclusive and endIndex is exclusive.

You can get substring from the given String object by one of the two methods:

1. public String substring(int startIndex): This method returns new String


object containing the substring of the given string from specified startIndex
(inclusive).
2. public String substring(int startIndex,int endIndex): This method returns
new String object containing the substring of the given string from specified
startIndex to endIndex.
In case of string:

 startIndex:starts from index 0(inclusive).


 endIndex:starts from index 1(exclusive).

Example of java substring


//Example of substring() method

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

String s="Sachin Tendulkar";


System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
}
}

Output:Tendulkar
Sachin

Methods of String class


java.lang.String class provides a lot of methods to work on string. Let's see the
commonly used methods of String class.

Method Description

1)public boolean equals(Object anObject) Compares this string to the specified object.

2)public boolean equalsIgnoreCase(String Compares this String to another String, ignoring


another) case.

3)public String concat(String str) Concatenates the specified string to the end of this
string.

4)public int compareTo(String str) Compares two strings and returns int

5)public int compareToIgnoreCase(String Compares two strings, ignoring case differences.


str)
6)public String substring(int beginIndex) Returns a new string that is a substring of this
string.

7)public String substring(int beginIndex,int Returns a new string that is a substring of this
endIndex) string.

8)public String toUpperCase() Converts all of the characters in this String to


upper case

9)public String toLowerCase() Converts all of the characters in this String to lowe
case.

10)public String trim() Returns a copy of the string, with leading and
trailing whitespace omitted.

11)public boolean startsWith(String prefix) Tests if this string starts with the specified prefix.

12)public boolean endsWith(String suffix) Tests if this string ends with the specified suffix.

13)public char charAt(int index) Returns the char value at the specified index.

14)public int length() Returns the length of this string.

15)public String intern() Returns a canonical representation for the string


object.

First seven methods have already been discussed.Now Let's take the example of other
methods:

toUpperCase() and toLowerCase() method


//Example of toUpperCase() and toLowerCase() method

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

String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
}
}

Output:SACHIN
sachin
Sachin

trim() method
//Example of trim() method

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

String s=" Sachin ";


System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin
}
}

Output: Sachin
Sachin

startsWith() and endsWith() method


//Example of startsWith() and endsWith() method

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

String s="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.startsWith("n"));//true
}
}

Output:true
true

charAt() method
//Example of charAt() method

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

String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
}
}

Output:S
h

length() method
//Example of length() method

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

String s="Sachin";
System.out.println(s.length());//6
}
}

Output:6

intern() method
A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this
String object as determined by the equals(Object) method, then the string from the
pool is returned. Otherwise, this String object is added to the pool and a reference to
this String object is returned.
//Example of length() method

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

String s=new String("Sachin");


String s2=s.intern();
System.out.println(s2);//Sachin
}
}

Output:Sachin

StringBuffer class:
The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer
class is same as String except it is mutable i.e. it can be changed.

Note: StringBuffer class is thread-safe i.e. multiple threads cannot


access it simultaneously .So it is safe and will result in an order.

Commonly used Constructors of StringBuffer class:


1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified
capacity as length.

Commonly used methods of StringBuffer class:


1. public synchronized StringBuffer append(String s): is used to append the
specified string with this string. The append() method is overloaded like
append(char), append(boolean), append(int), append(float), append(double)
etc.
2. public synchronized StringBuffer insert(int offset, String s): is used to
insert the specified string with this string at the specified position. The insert()
method is overloaded like insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
3. public synchronized StringBuffer replace(int startIndex, int endIndex,
String str): is used to replace the string from specified startIndex and
endIndex.
4. public synchronized StringBuffer delete(int startIndex, int
endIndex): is used to delete the string from specified startIndex and
endIndex.
5. public synchronized StringBuffer reverse(): is used to reverse the string.
6. public int capacity(): is used to return the current capacity.
7. public void ensureCapacity(int minimumCapacity): is used to ensure the
capacity at least equal to the given minimum.
8. public char charAt(int index): is used to return the character at the
specified position.
9. public int length(): is used to return the length of the string i.e. total
number of characters.
10. public String substring(int beginIndex): is used to return the substring
from the specified beginIndex.
11. public String substring(int beginIndex, int endIndex): is used to return
the substring from the specified beginIndex and endIndex.

What is mutable string?


A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.

simple example of StringBuffer class by append() method


The append() method concatenates the given argument with this string.

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

StringBuffer sb=new StringBuffer("Hello ");


sb.append("Java");//now original string is changed

System.out.println(sb);//prints Hello Java


}
}

Example of insert() method of StringBuffer class


The insert() method inserts the given string with this string at the given position.

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

StringBuffer sb=new StringBuffer("Hello ");


sb.insert(1,"Java");//now original string is changed

System.out.println(sb);//prints HJavaello
}
}

Example of replace() method of StringBuffer class


The replace() method replaces the given string from the specified beginIndex and
endIndex.

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

StringBuffer sb=new StringBuffer("Hello");


sb.replace(1,3,"Java");

System.out.println(sb);//prints HJavalo
}
}

Example of delete() method of StringBuffer class


The delete() method of StringBuffer class deletes the string from the specified
beginIndex to endIndex.

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

StringBuffer sb=new StringBuffer("Hello");


sb.delete(1,3);

System.out.println(sb);//prints Hlo
}
}

Example of reverse() method of StringBuffer class


The reverse() method of StringBuilder class reverses the current string.

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

StringBuffer sb=new StringBuffer("Hello");


sb.reverse();

System.out.println(sb);//prints olleH
}
}

Example of capacity() method of StringBuffer class


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.

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

StringBuffer sb=new StringBuffer();


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

Example of ensureCapacity() method of StringBuffer class


The ensureCapacity() method of StringBuffer class ensures that the given capacity is
the minimum to the current capacity. If it is greater than the 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.

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

StringBuffer sb=new StringBuffer();


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

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

}
}

StringBuilder class:
The StringBuilder class is used to create mutable (modifiable) string. The
StringBuilder class is same as StringBuffer class except that it is non-synchronized. It
is available since JDK1.5.
Commonly used Constructors of StringBuilder class:
1. StringBuilder(): creates an empty string Builder with the initial capacity of
16.
2. StringBuilder(String str): creates a string Builder with the specified string.
3. StringBuilder(int length): creates an empty string Builder with the specified
capacity as length.

Commonly used methods of StringBuilder class:


1. public StringBuilder append(String s): is used to append the specified
string with this string. The append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double) etc.
2. public StringBuilder insert(int offset, String s): is used to insert the
specified string with this string at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
3. public StringBuilder replace(int startIndex, int endIndex, String
str): is used to replace the string from specified startIndex and endIndex.
4. public StringBuilder delete(int startIndex, int endIndex): is used to
delete the string from specified startIndex and endIndex.
5. public StringBuilder reverse(): is used to reverse the string.
6. public int capacity(): is used to return the current capacity.
7. public void ensureCapacity(int minimumCapacity): is used to ensure the
capacity at least equal to the given minimum.
8. public char charAt(int index): is used to return the character at the
specified position.
9. public int length(): is used to return the length of the string i.e. total
number of characters.
10. public String substring(int beginIndex): is used to return the substring
from the specified beginIndex.
11. public String substring(int beginIndex, int endIndex): is used to return
the substring from the specified beginIndex and endIndex.

simple program of StringBuilder class by append() method


The append() method concatenates the given argument with this string.

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

StringBuilder sb=new StringBuilder("Hello ");


sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}

Example of insert() method of StringBuilder class


The insert() method inserts the given string with this string at the given position.

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

StringBuilder sb=new StringBuilder("Hello ");


sb.insert(1,"Java");//now original string is changed

System.out.println(sb);//prints HJavaello
}
}

Example of replace() method of StringBuilder class


The replace() method replaces the given string from the specified beginIndex and
endIndex.

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

StringBuilder sb=new StringBuilder("Hello");


sb.replace(1,3,"Java");

System.out.println(sb);//prints HJavalo
}
}
Example of delete() method of StringBuilder class
The delete() method of StringBuilder class deletes the string from the specified
beginIndex to endIndex.

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

StringBuilder sb=new StringBuilder("Hello");


sb.delete(1,3);

System.out.println(sb);//prints Hlo
}
}

Example of reverse() method of StringBuilder class


The reverse() method of StringBuilder class reverses the current string.

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

StringBuilder sb=new StringBuilder("Hello");


sb.reverse();

System.out.println(sb);//prints olleH
}
}

Example of capacity() method of StringBuilder class


The capacity() method of StringBuilder class returns the current capacity of the
Builder. The default capacity of the Builder 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.

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

StringBuilder sb=new StringBuilder();


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

Example of ensureCapacity() method of StringBuilder class


The ensureCapacity() method of StringBuilder class ensures that the given capacity is
the minimum to the current capacity. If it is greater than the 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.

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

StringBuilder sb=new StringBuilder();


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

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

How to create Immutable class?


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. We
can also create immutable class by creating final class that have final data members
as the example given below:

Example to create Immutable class


In this example, we have created a final class named Employee. It have one final
datamember, a parameterized constructor and getter method.

public final class Employee{


final String pancardNumber;

public Employee(String pancardNumber){


this.pancardNumber=pancardNumber;
}

public String getPancardNumber(){


return pancardNumber;
}

The above class is immutable because:

 The instance variable of the class is final i.e. we cannot change the value of it
after creating an object.
 The class is final so we cannot create the subclass.
 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.


Understanding toString() method
If you want to represent any object as a string, toString() method comes into
existence.

The toString() method returns the string representation of the object.

If you print any object, java compiler internally invokes the toString() method on the
object. So overriding the toString() method, returns the desired output, it can be the
state of an object etc. depends on your implementation.

Advantage of the toString() method

By overriding the toString() method of the Object class, we can return values of the
object, so we don't need to write much code.

Understanding problem without toString() method

Let's see the simple code that prints reference.

class Student{
int rollno;
String name;
String city;

Student(int rollno, String name, String city){


this.rollno=rollno;
this.name=name;
this.city=city;
}

public static void main(String args[]){


Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");

System.out.println(s1);//compiler writes here s1.toString()


System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:Student@1fee6fc
Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values
of the objects but I want to print the values of these objects. Since java compiler
internally calls toString() method, overriding this method will return the specified
values. Let's understand it with the example given below:

Example of toString() method

Now let's see the real example of toString() method.

class Student{
int rollno;
String name;
String city;

Student(int rollno, String name, String city){


this.rollno=rollno;
this.name=name;
this.city=city;
}

public String toString(){//overriding the toString() method


return rollno+" "+name+" "+city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");

System.out.println(s1);//compiler writes here s1.toString()


System.out.println(s2);//compiler writes here s2.toString()
}
}

Output:101 Raj lucknow


102 Vijay ghaziabad
StringTokenizer in Java
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. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

Constructors of StringTokenizer class

There are 3 constructors defined in the StringTokenizer class.

Constructor Description

StringTokenizer(String str) creates StringTokenizer with specified string.

StringTokenizer(String str, creates StringTokenizer with specified string and delimeter.


String delim)

StringTokenizer(String str, creates StringTokenizer with specified string, delimeter and


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

Methods of StringTokenizer class

The 6 useful methods of StringTokenizer class are as follows:

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 delim) returns the next token based on the delimeter.

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.

Simple example of StringTokenizer class

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

import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Output:my
name
is
khan

Example of nextToken(String delim) method of


StringTokenizer class
import java.util.*;

public class Test {


public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("my,name,is,khan");

// printing next token


System.out.println("Next token is : " + st.nextToken(","));
}
}
Output:Next token is : my
StringTokenizer class is deprecated now. It is recommended to use split()
method of String class or regex (Regular Expression).

You might also like