KEMBAR78
Module 1 | PDF | Java Virtual Machine | Object Oriented Programming
0% found this document useful (0 votes)
7 views122 pages

Module 1

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

Module 1

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

MODULE - 1

OOPS CONCEPTS AND JAVA PROGRAMMING

Java
Java technology is widely used currently. Let's start learning of java from basic
questions like what is java, where it is used, what type of applications are created in
java and why use java?

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, google.com 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 types of applications that can be created using java:

1) Standalone Application

Page 1
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 applications.

4) Mobile Application

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

What will we learn in Basics of Java?


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.

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

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

Page 4
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)

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

Page 5
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 maintenance by providing some rules.

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)

Page 6
Java code can be run on multiple platforms e.g.Windows,Linux,Sun Solaris,Mac/OS
etc. Java code is compiled by the compiler and converted into bytecode.This
bytecode is a platform independent code because it can be run on multiple
platforms i.e. Write Once and Run Anywhere(WORA).

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 access 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 security can also be
provided by application developer through SSL,JAAS,cryptography etc.

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

Simple Program of Java

Page 8
In this page, we will learn how to write the hello java program. Creating hello java
example is too easy. Here, we have created a class named Simple that contains
only main method and prints a message hello java. It is the simple program of
java.

Requirement for Hello Java Example


For executing any java program, you need to

 create the java program.


 install the JDK if you don't have installed it, download the JDK and install
it.
 set path of the bin directory under jdk.
 compile and execute the program.

Creating hello java example


Let's create the hello java program:

1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }

save this file as Simple.java

To compile: javac Simple.java

To execute: java Simple

Output:Hello Java

Understanding first java program


Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().

 class is used to declare a class in java.


 public is an access modifier which represents visibility, it means it is visible
to all.

Page 9
 static is a keyword, if we declare any method as static, it is known as static
method. The core advantage of static method is that there is no need to
create object to invoke the static method. The main method is executed by
the JVM, so it doesn't require to create object to invoke the main method. So
it saves memory.
 void is the return type of the method, it means it doesn't return any value.
 main represents startup of the program.
 String[] args is used for command line argument. We will learn it later.
 System.out.println() is used print statement.

To write the simple program, open notepad and write simple program as
displayed below:

Page
10
As displayed in the above diagram, write the simple program of java in notepad
and saved it as Simple.java. To compile and run this program, you need to open
command prompt by start -> All Programs -> Accessories -> command prompt.

Page
11
To compile and run the above program, go to your current directory first; my
current directory is c:\new . Write here:

To compile: javac Simple.java

To execute: java Simple

Resolving an exception "javac is not recognized as an internal or


external command" ?
If there occurs a problem like displayed in the below figure, you need to set path.
Since DOS doesn't know javac or java, we need to set path. Path is not required in
such a case if you save your program inside the jdk/bin folder. But its good

Page
12
approach to set path.

Internal Details of Hello Java Program


In the previous page, we have learned about the first program, how to compile and
how to run the first java program. Here, we are going to learn, what happens while
compiling and running the java program. Moreover, we will see some question
based on the first program.

Page
13
What happens at compile time?
At compile time, java file is compiled by Java Compiler (It does not interact with
OS) and converts the java code into bytecode.

What happens at runtime?


At runtime, following steps are performed:

Page
14
Classloader: is the subsystem of JVM that is used to load class files.

Bytecode Verifier: checks the code fragments for illegal code that can violate
access right to objects.

Interpreter: read bytecode stream then execute the instructions.

Q)Can you save a java source file by other name than the
class name?
Yes, like the figure given below illustrates:

Page
15
To compile: javac Hard.java

To execute: java Simple

Q)Can you have multiple classes in a java source file?


Yes, like the figure given below illustrates:

Page
16
How to set path of JDK in Windows:
Path is required for using tools such as javac, java etc. If you are saving the java
file in jdk/bin folder, path is not required.But If you are having your java file
outside the jdk/bin folder, it is necessary to set path of JDK. There are two ways to
set path of JDK:

1. temporary
2. permanent

1)Setting temporary Path of JDK in Windows:


For setting the temporary path of JDK, you need to follow these steps:

 Open command prompt


 copy the path of bin folder

Page
17
 write in command prompt: set path=copiedpath

For Example:

set path=C:\Program Files\Java\jdk1.6.0_23\bin

Let's see it in the figure given below:

Page
18
2)Setting Permanent Path of JDK in Windows:
For setting the permanent path of JDK, you need to follow these steps:

 Go to MyComputer properties -> advanced tab -> environment variables ->


new tab of user variable -> write path in variable name -> write path of bin
folder in variable value -> ok -> ok -> ok

For Example:
1)Go to MyComputer properties

2)click on advanced tab

Page
19
3)click on environment variables

Page
20
4)click on new tab of user variables

Page
21
5)write path in variable name

Page
22
6)Copy the path of bin folder

Page
23
7)paste path of bin folder in variable value

Page
24
8)click on ok button

Page
25
9)click on ok button

Page
26
Now your permanent path is set.You can now execute any program of java from any
drive.

Setting Path in Linux OS


Setting the path in Linux OS is same as setting the path in the Windows OS. But
here we use export tool rather than set. Let's see how to set path in Linux OS:

export PATH=$PATH:/home/jdk1.6.01/bin/

Here, we have installed the JDK in the home directory under Root (/home).

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

Page
28
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.

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

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

Page
31
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) registers. 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.

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

Page
33
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

Page
34
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

Page
35
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. To get detail about Unicode see below.

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

Page
36
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 ? :

Page
37
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;

Page
38
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

Page
39
{
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);

}
}

Page
40
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


In this page, we will learn about basics of OOPs. Object Oriented Programming is a
paradigm that provides many concepts such as inheritance, data
binding,polymorphism etc.

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


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

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

OOPs (Object Oriented Programming System)

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

 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Object

Any entity that has state and behavior is known as an object. For example: chair,
pen, table, keyboard, bike etc. It can be physical and logical.

Class

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

Inheritance

Page
42
When one object acquires all the properties and behaviours of parent
object i.e. known as inheritance. It provides code reusability. It is used to achieve
runtime polymorphism.

Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For
example: to convense the customer differently, to draw something e.g. shape or
rectangle etc.

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


polymorphism.

Another example can be to speak something e.g. cat speaks meaw, 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.

Page
43
Encapsulation

Binding (or wrapping) code and data together into a single unit is known
as encapsulation. For example: 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.

Advantage of OOPs over Procedure-oriented


programming language
1) OOPs makes development and maintenance easier where as in Procedure-
oriented programming language it is not easy to manage if code grows as project
size grows.

2) OOPs provide data hiding whereas in Procedure-oriented prgramming language


a global data can be accessed from anywhere.

3) OOPs provide ability to simulate real-world event much more effectively. We


can provide the solution of real world problem if we are using the Object-Oriented
Programming language.

Page
44
What is difference between 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.

What we will learn in OOPs Concepts?

 Advantage of OOPs
 Naming Convention
 Object and class
 Method overloading
 Constructor
 static keyword
 this keyword with 6 usage
 Inheritance
 Aggregation
 Method Overriding
 Covariant Return Type
 super keyword
 Instance Initializer block
 final keyword
 Abstract class
 Interface
 Runtime Polymorphism
 Static and Dynamic Binding
 Downcasting with instanceof operator
 Package
 Access Modifiers
 Encapsulation
 Object Cloning

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 convention

Page
45
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 Convention

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


name possible). e.g. 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
Next Topic

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.

Page
46
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 :

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

Page
47
A class in java can contain:

 data member
 method
 constructor
 block

Syntax to declare a class:


1. class <class_name>{
2. data member;
3. method;
4. }

Simple Example of Object and Class


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

1. class Student{
2. int id;//data member (also instance variable)
3. String name;//data member(also instance variable)
4.
5. public static void main(String args[]){
6. Student s1=new Student();//creating an object of Student
7. System.out.println(s1.id+" "+s1.name);
8.
9. }
10.}
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

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

1. class Student{
2. int rollno;
3. String name;
4.
5. void insertRecord(int r, String n){ //method
6. rollno=r;
7. name=n;
8. }
9.
10. void displayInformation(){System.out.println(rollno+" "+name);}//method
11. public static void main(String args[]){
12. Student s1=new Student();
13. Student s2=new Student();
14.
15. s1.insertRecord(111,"Karan");
16. s2.insertRecord(222,"Aryan");
17.
18. s1.displayInformation();
19. s2.displayInformation();
20.
21. }
22.}
Output:111 Karan
222 Aryan

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

1. class Rectangle{
2. int length;
3. int width;
4.
5. void insert(int l,int w){
6. length=l;
7. width=w;
8. }
9.
10. void calculateArea(){System.out.println(length*width);}
11.
12. public static void main(String args[]){
13. Rectangle r1=new Rectangle();

Page
50
14. Rectangle r2=new Rectangle();
15.
16. r1.insert(11,5);
17. r2.insert(3,15);
18.
19. r1.calculateArea();
20. r2.calculateArea();
21.}
22.}
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.

1. class Calculation{
2.
3. void fact(int n){
4. int fact=1;
5. for(int i=1;i<=n;i++){
6. fact=fact*i;
7. }
8. System.out.println("factorial is "+fact);
9. }
10.
11.public static void main(String args[]){
12. new Calculation().fact(5);//calling method with annonymous object
13.}
14.}
Output:Factorial is 120

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

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


Let's see the example:

1. class Rectangle{
2. int length;
3. int width;
4.
5. void insert(int l,int w){
6. length=l;
7. width=w;
8. }
9.
10. void calculateArea(){System.out.println(length*width);}
11.
12. public static void main(String args[]){
13. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
14.
15. r1.insert(11,5);
16. r2.insert(3,15);
17.
18. r1.calculateArea();
19. r2.calculateArea();
20.}
21.}
Output:55
45

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.

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

1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10,10,10);
8. obj.sum(20,20);
9.

Page
53
10. }
11.}
Output:30
40

2)Example of Method Overloading by changing


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

1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(double a,double b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10.5,10.5);
8. obj.sum(20,20);
9.
10. } }
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:

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

Page
54
9. }
10.}

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:

1. class Simple{
2. public static void main(int a){
3. System.out.println(a);
4. }
5.
6. public static void main(String args[]){
7. System.out.println("main() method invoked");
8. main(10);
9. }
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:

Page
55
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
1. class Calculation{
2. void sum(int a,long b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(20,20);//now second int literal will be promoted to long
8. obj.sum(20,20,20);
9.
10. }
11.}
Output:40
60

Page
56
Example of Method Overloading with
TypePromotion if matching found
If there are matching type arguments in the method, type promotion is not
performed.

1. class Calculation{
2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b){System.out.println("long arg method invoked");}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(20,20);//now int arg sum() method gets invoked
8. }
9. }
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.

1. class Calculation{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(20,20);//now ambiguity
8. }
9. }
Output:Compile Time Error

One type is not de-promoted implicitly for example double cannot be


depromoted to any type implicitely.

Page
57
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

Page
58
1) Default Constructor
A constructor that has no parameter is known as default constructor.

Syntax of default constructor:


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

1.
2. class Bike{
3.
4. Bike(){System.out.println("Bike is created");}
5.
6. public static void main(String args[]){
7. Bike b=new Bike();
8. }
9. }
Output: Bike is created

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


default constructor.

Page
59
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
1. class Student{
2. int id;
3. String name;
4.
5. void display(){System.out.println(id+" "+name);}
6.
7. public static void main(String args[]){
8. Student s1=new Student();
9. Student s2=new Student();
10.s1.display();
11.s2.display();
12.}
13.}
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 has parameters is known as parameterized constructor.

Page
60
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 has two
parameters. We can have any number of parameters in the constructor.

1. class Student{
2. int id;
3. String name;
4.
5. Student(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student s1 = new Student(111,"Karan");
13. Student s2 = new Student(222,"Aryan");
14. s1.display();
15. s2.display();
16. }
17.}
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


1. class Student{
2. int id;
3. String name;
4. int age;
5. Student(int i,String n){
6. id = i;
7. name = n;
8. }

Page
61
9. Student(int i,String n,int a){
10. id = i;
11. name = n;
12. age=a;
13. }
14. void display(){System.out.println(id+" "+name+" "+age);}
15.
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan",25);
19. s1.display();
20. s2.display();
21. }
22.}
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 Method is used to expose


object. behaviour of 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 Method is not provided by


constructor if you don't have any constructor. compiler in any case.

Constructor name must be same as the class Method name may or may not
name. 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:

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

1. class Student{
2. int id;
3. String name;
4. Student(int i,String n){
5. id = i;
6. name = n;
7. }
8.
9. Student(Student s){
10. id = s.id;
11. name =s.name;
12. }
13. void display(){System.out.println(id+" "+name);}
14.
15. public static void main(String args[]){
16. Student s1 = new Student(111,"Karan");
17. Student s2 = new Student(s1);
18. s1.display();
19. s2.display();
20. }
21.}
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.

1. class Student{
2. int id;
3. String name;
4. Student(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student(){}
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student s1 = new Student(111,"Karan");

Page
63
13. Student s2 = new Student();
14. s2.id=s1.id;
15. s2.name=s1.name;
16. s1.display();
17. s2.display();
18. }
19.}
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.

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
4. nested class

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.

Page
64
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable


1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

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


1. //Program of static variable
2.
3. class Student{
4. int rollno;
5. String name;
6. static String college ="TJC";
7. Student(int r,String n){
8. rollno = r;
9. name = n;
10. }
11. void display (){System.out.println(rollno+" "+name+" "+college);}
12. public static void main(String args[]){
13. Student s1 = new Student (111,"Karan");
14. Student s2 = new Student (222,"Aryan");
s1.display();
15. s2.display();
16. }
17.}
Output:111 Karan TJC
222 Aryan TJC

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

1. class Counter{
2. int count=0;//will get memory when instance is created
3.
4. Counter(){
5. count++;
6. System.out.println(count);
7. }

Page
66
8.
9. public static void main(String args[]){
10.
11.Counter c1=new Counter();
12.Counter c2=new Counter();
13.Counter c3=new Counter();
14.
15.}}
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.

1. class Counter{
2. static int count=0;//will get memory only once and retain its value
3.
4. Counter(){
5. count++;
6. System.out.println(count);
7. }
8.
9. public static void main(String args[]){
10.
11.Counter c1=new Counter();
12.Counter c2=new Counter();
13.Counter c3=new Counter();
14.
15.}}
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.

Page
67
Example of static method
1. //Program of changing the common property of all objects(static field).
2.
3. class Student{
4. int rollno;
5. String name;
6. static String college = "TJC";
7. static void change(){
8. college = "BBDIT";
9. }
10. Student(int r, String n){
11. rollno = r;
12. name = n;
13. }
14. void display (){System.out.println(rollno+" "+name+" "+college);}
15. public static void main(String args[]){
16. Student.change();
17. Student s1 = new Student (111,"Karan");
18. Student s2 = new Student (222,"Aryan");
19. Student s3 = new Student (333,"Sonoo");
20. s1.display();
21. s2.display();
22. s3.display();
23. }
24.}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Another example of static method that performs


normal calculation
1. //Program to get cube of a given number by static method
2.
3. class Calculate{
4. static int cube(int x){
5. return x*x*x;
6. }
7.
8. public static void main(String args[]){
9. int result=Calculate.cube(5);
10. System.out.println(result);
11. }
12.}
Output:125

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

1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
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 create 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 executed before main method at the time of classloading.

Example of static block


1. class A{
2.
3. static{System.out.println("static block is invoked");}
4.
5. public static void main(String args[]){
6. System.out.println("Hello main");
7. }
8. }
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.

Page
69
1. class A{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
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

Page
70
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:

1. class Student {
2. int id;
3. String name;
4.
5. Student (int id,String name){
6. id = id;
7. name = name;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student s1 = new Student (111,"Karan");
13. Student s2 = new Student (321,"Aryan");
14. s1.display();
15. s2.display();
16. }
17.}
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


1. //example of this keyword
2. class Student{
3. int id;
4. String name;
5.
6. Student(int id,String name){
7. this.id = id;
8. this.name = name;
9. }
10. void display(){System.out.println(id+" "+name);}
11. public static void main(String args[]){
12. Student s1 = new Student(111,"Karan");
13. Student s2 = new Student(222,"Aryan");
14. s1.display();

Page
71
15. s2.display();
16.}
17.}
Output111 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


1. class Student{
2. int id;
3. String name;
4.
5. student(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10. public static void main(String args[]){
11. Student e1 = new Student(111,"karan");
12. Student e2 = new Student(222,"Aryan");
13. e1.display();
14. e2.display();

Page
72
15.}
16.}
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.

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


2.
3. class Student{
4. int id;
5. String name;
6. Student (){System.out.println("default constructor is invoked");}
7.
8. Student(int id,String name){
9. this ();//it is used to invoked current class constructor.
10. this.id = id;
11. this.name = name;
12. }
13. void display(){System.out.println(id+" "+name);}
14.
15. public static void main(String args[]){
16. Student e1 = new Student(111,"karan");
17. Student e2 = new Student(222,"Aryan");
18. e1.display();
19. e2.display();
20. }
21.}
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.

1. class Student{
2. int id;

Page
73
3. String name;
4. String city;
5.
6. Student(int id,String name){
7. this.id = id;
8. this.name = name;
9. }
10. Student(int id,String name,String city){
11. this(id,name);//now no need to initialize id and name
12. this.city=city;
13. }
14. void display(){System.out.println(id+" "+name+" "+city);}
15.
16. public static void main(String args[]){
17. Student e1 = new Student(111,"karan");
18. Student e2 = new Student(222,"Aryan","delhi");
19. e1.display();
20. e2.display();
21. }
22.}
Output:111 Karan null
222 Aryan delhi

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

1. class Student{
2. int id;
3. String name;
4. Student (){System.out.println("default constructor is invoked");}
5.
6. Student(int id,String name){
7. id = id;
8. name = name;
9. this ();//must be the first statement
10. }
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[]){
14. Student e1 = new Student(111,"karan");
15. Student e2 = new Student(222,"Aryan");
16. e1.display();
17. e2.display();
18. }
19.}
Output:Compile Time Error

Page
74
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

1. class S{
2. void m(){
3. System.out.println("method is invoked");
4. }
5. void n(){
6. this.m();//no need because compiler does it for you.
7. }
8. void p(){
9. n();//complier will add this to invoke n() method as this.n()
10. }
11. public static void main(String args[]){
12. S s1 = new S();
13. s1.p();
14. }
15.}
Output:method is invoked

Page
75
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:

1. class S{
2. void m(S obj){
3. System.out.println("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8.
9. public static void main(String args[]){
10. S s1 = new S();
11. s1.p();
12. }
13.}
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:

1. class B{
2. A obj;
3. B(A obj){
4. this.obj=obj;
5. }
6. void display(){
7. System.out.println(obj.data);//using data member of A class
8. }
9. }
10.
11.class A{
12. int data=10;
13. A(){
14. B b=new B(this);
15. b.display();

Page
76
16. }
17. public static void main(String args[]){
18. A a=new A();
19. }
20.}
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


1. return_type method_name(){
2. return this;
3. }

Example of this keyword that you return as a


statement from the method
1. class A{
2. A getA(){
3. return this;
4. }
5. void msg(){System.out.println("Hello java");}
6. }
7.
8. class Test{
9. public static void main(String args[]){
10.new A().getA().msg();
11.}
12.}
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.

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

Page
77
4. }
5.
6. public static void main(String args[]){
7. A obj=new A();
8. System.out.println(obj);//prints the reference ID
9.
10.obj.m();
11.}
12.}
Output:A@13d9c02
A@13d9c02

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

In java, array is an object that 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 retrieve 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.

Page
78
Types of Array
There are two types of array.

 Single Dimensional Array


 Multidimensional Array

Single Dimensional Array


Syntax to Declare an Array in java
1. dataType[] arrayRefVar; (or)
2. dataType []arrayRefVar; (or)
3. dataType arrayRefVar[];

Instantiation of an Array in java


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

1. class B{
2. public static void main(String args[]){
3.
4. int a[]=new int[5];//declaration and instantiation
5. a[0]=10;//initialization
6. a[1]=20;
7. a[2]=70;
8. a[3]=40;
9. a[4]=50;
10.
11.//printing array
12.for(int i=0;i<a.length;i++)//length is the property of array
13.System.out.println(a[i]);
14.
15.}}
Output: 10
20
70
40
50

Page
79
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:

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

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

1. class B{
2. public static void main(String args[]){
3.
4. int a[]={33,3,4,5};//declaration, instantiation and initialization
5.
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9.
10.}}
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.

1. class B{
2. static void min(int arr[]){
3. int min=arr[0];
4. for(int i=1;i<arr.length;i++)
5. if(min>arr[i])
6. min=arr[i];
7.
8. System.out.println(min);
9. }
10.
11.public static void main(String args[]){
12.

Page
80
13.int a[]={33,3,4,5};
14.min(a);//passing array in the method
15.
16.}}
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


1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in java


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

Example to initialize Multidimensional Array in java


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

Example of Multidimensional java array


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

1. class B{
2. public static void main(String args[]){
3.
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.
7. //printing 2D array
8. for(int i=0;i<3;i++){
9. for(int j=0;j<3;j++){

Page
81
10. System.out.print(arr[i][j]+" ");
11. }
12. System.out.println();
13.}
14.
15.}}
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


1. public static void arraycopy(
2. Object src, int srcPos,Object dest, int destPos, int length
3. )

Example of arraycopy method


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

Page
82
7. System.arraycopy(copyFrom, 2, copyTo, 0, 7);
8. System.out.println(new String(copyTo));
9. }
10.}
Output:caffein

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

1. class AE{
2. public static void main(String args[]){
3. //creating two matrices
4. int a[][]={{1,3,4},{3,4,5}};
5. int b[][]={{1,3,4},{3,4,5}};
6.
7. //creating another matrix to store the sum of two matrices
8. int c[][]=new int[2][3];
9.
10.//adding and printing addition of 2 matrices
11.for(int i=0;i<2;i++){
12.for(int j=0;j<3;j++){
13.c[i][j]=a[i][j]+b[i][j];
14.System.out.print(c[i][j]+" ");
15.}
16.System.out.println();//new line
17.}
18.
19.}}
Output:2 6 8
6 8 10

Command Line Argument


The command-line argument is an argument passed at the time of running the java
program. The argument can be received in the program and used as an input.

So, it provides a convenient way to check out the behavior of the program on
different values. You can pass N numbers of arguments from the command prompt.

Simple example of command-line argument


In this example, we are receiving only one argument and printing it. For running
this program, you must pass at least one argument from the command prompt.

Page
83
1. class A{
2. public static void main(String args[]){
3.
4. System.out.println("first argument is: "+args[0]);
5.
6. }
7. }
1. compile by > javac A.java
2. run by > java A sonoo
Output:first argument is: sonoo

Example of command-line argument that prints all


the values
In this example, we are printing all the arguments passed from the command-line.
For this purpose, we have traversed the array using for loop.

1. class A{
2. public static void main(String args[]){
3.
4. for(int i=0;i<args.length;i++)
5. System.out.println(args[i]);
6.
7. }
8. }
1. compile by > javac A.java
2. run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc

Java String
In Java, string is basically an object that represents sequence of char values.
An array of characters works same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

is same as:

1. String s="T John College";

Page
84
Java String class provides a lot of methods to perform operations on strings
such as compare(), concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.

The java.lang.String class implements Serializable, Comparable and


CharSequence interfaces.

CharSequence Interface

The CharSequence interface is used to represent the sequence of characters.


String, StringBuffer and StringBuiolder classes implement it. It means, we
can create strings in Java by using these three classes.

The Java String is immutable which means it cannot be changed. Whenever


we change any string, a new instance is created. For mutable strings, you
can use StringBuffer and StringBuilder classes.

Page
85
We will discuss immutable string later. Let's first understand what String in
Java is and how to create the String object.

What is String in Java?

Generally, String is a sequence of characters. But in Java, string is an object


that represents a sequence of characters. The java.lang.String class is used
to create a string object.

How to create a string object?

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal

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

1. String s="welcome";

Each time you create a string literal, the JVM checks the "string constant
pool" first. If the string already exists in the pool, a reference to the pooled
instance is returned. If the string doesn't exist in the pool, a new string
instance is created and placed in the pool. For example:

1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance

Page
86
In the above example, only one object will be created. Firstly, JVM will not
find any string object with the value "Welcome" in string constant pool that is
why it will create a new object. After that it will find the string with the value
"Welcome" in the pool, it will not create a new object but will return the
reference to the same instance.

Note: String objects are stored in a special memory area known as


the "string constant pool".

Why Java uses the concept of String literal?

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

2) By new keyword

1. String s=new String("Welcome");//creates two objects and one referen


ce variable

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

Java String Example

Page
87
StringExample.java

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword

7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}

Output:

java

strings

example

The above code, converts a char array into a String object. And displays the
String objects s1, s2, and s3 on console using println() method.

Java String class methods

The java.lang.String class provides many useful methods to perform


operations on sequence of char values.

No. Method Description

It returns char value for the


1 char charAt(int index)
particular index

2 int length() It returns string length

static String format(String format, Object...


3 It returns a formatted string.
args)

static String format(Locale l, String format, It returns formatted string


4
Object... args) with given locale.

It returns substring for given


5 String substring(int beginIndex)
begin index.

6 String substring(int beginIndex, int It returns substring for given

Page
88
endIndex) begin index and end index.

It returns true or false after


7 boolean contains(CharSequence s) matching the sequence of
char value.

static String join(CharSequence delimiter,


8 It returns a joined string.
CharSequence... elements)

static String join(CharSequence delimiter,


9 Iterable<? extends CharSequence> It returns a joined string.
elements)

It checks the equality of


10 boolean equals(Object another)
string with the given object.

11 boolean isEmpty() It checks if string is empty.

It concatenates the specified


12 String concat(String str)
string.

String replace(CharSequence old, It replaces all occurrences of


14
CharSequence new) the specified CharSequence.

static String equalsIgnoreCase(String It compares another string. It


15
another) doesn't check case.

It returns a split string


16 String[] split(String regex)
matching regex.

It returns a split string


17 String[] split(String regex, int limit)
matching regex and limit.

18 String intern() It returns an interned string.

It returns a string in
23 String toLowerCase()
lowercase.

It returns a string in
24 String toLowerCase(Locale l) lowercase using specified
locale.

It returns a string in
25 String toUpperCase()
uppercase.

It returns a string in
26 String toUpperCase(Locale l) uppercase using specified
locale.

Page
89
It removes beginning and
27 String trim()
ending spaces of this string.

It converts given type into


28 static String valueOf(int value) string. It is an overloaded
method.

Immutable String in Java

A String is an unavoidable type of variable while writing any application


program. String references are used to store various attributes like
username, password, etc. In Java, String objects are immutable.
Immutable simply means unmodifiable or unchangeable.

Once String object is created its data or state can't be changed but a new
String object is created.

Let's try to understand the concept of immutability by the example given


below:

Testimmutablestring.java

1. class Testimmutablestring{
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the e
nd
5. System.out.println(s);//will print Sachin because strings are immutabl
e objects
6. }
7. }

Output:

Sachin

Now it can be understood by the diagram given below. Here Sachin is not
changed but a new object is created with Sachin Tendulkar. That is why
String is known as immutable.

Page
90
As you can see in the above figure that two objects are created but s
reference variable still refers to "Sachin" not to "Sachin Tendulkar".

But if we explicitly assign it to the reference variable, it will refer to "Sachin


Tendulkar" object.

For example:

Testimmutablestring1.java

1. class Testimmutablestring1{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=s.concat(" Tendulkar");
5. System.out.println(s);
6. }
7. }

Output:
Sachin Tendulkar

In such a case, s points to the "Sachin Tendulkar". Please notice that still
Sachin object is not modified.

Page
91
Why String objects are immutable in Java?

As Java uses the concept of String literal. Suppose there are 5 reference
variables, all refer to one object "Sachin". If one reference variable changes
the value of the object, it will be affected by all the reference variables. That
is why String objects are immutable in Java.

Following are some features of String which makes String objects immutable.

1. ClassLoader:

A ClassLoader in Java uses a String object as an argument. Consider, if the


String object is modifiable, the value might be changed and the class that is
supposed to be loaded might be different.

To avoid this kind of misinterpretation, String is immutable.

2. Thread Safe:

As the String object is immutable we don't have to take care of the


synchronization that is required while sharing an object across multiple
threads.

3. Security:

As we have seen in class loading, immutable String objects avoid further


errors by loading the correct class. This leads to making the application
program more secure. Consider an example of banking software. The
username and password cannot be modified by any intruder because String
objects are immutable. This can make the application program more secure.

4. Heap Space:

The immutability of String helps to minimize the usage in the heap memory.
When we try to declare a new String object, the JVM checks whether the
value already exists in the String pool or not. If it exists, the same value is
assigned to the new object. This feature allows Java to use the heap space
efficiently.

Why String class is Final in Java?

The reason behind the String class being final is because no one can override
the methods of the String class. So that it can provide the same features to
the new String objects as well as to the old ones.

Page
92
String comparison in Java
We can compare two given strings on the basis of content and reference.

It is used in authentication (by equals() method),sorting (by compareTo()


method), reference matching (by == operator) 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.

1. class Simple{
2. public static void main(String args[]){
3.
4. String s1="Sachin";
5. String s2="Sachin";
6. String s3=new String("Sachin");
7. String s4="Saurav";
8.
9. System.out.println(s1.equals(s2));//true
10. System.out.println(s1.equals(s3));//true
11. System.out.println(s1.equals(s4));//false
12. }
13.}
Output:true
true
false
1. //Example of equalsIgnoreCase(String) method
2. class Simple{
3. public static void main(String args[]){
4.
5. String s1="Sachin";
6. String s2="SACHIN";
7.
8. System.out.println(s1.equals(s2));//false

Page
93
9. System.out.println(s1.equalsIgnoreCase(s2));//true
10. }
11.}
Output:false
true

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

1. //<b><i>Example of == operator</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s1="Sachin";
7. String s2="Sachin";
8. String s3=new String("Sachin");
9.
10. System.out.println(s1==s2);//true (because both refer to same instance)
11. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpo
ol)
12. }
13.}
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

1. //<b><i>Example of compareTo() method:</i></b>


2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s1="Sachin";
7. String s2="Sachin";
8. String s3="Ratan";
9.
10. System.out.println(s1.compareTo(s2));//0

Page
94
11. System.out.println(s1.compareTo(s3));//1(because s1>s3)
12. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
13. }
14.}
Output:0
1
-1

String Concatenation in Java


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

1. //Example of string concatenation operator


2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin"+" Tendulkar";
7. System.out.println(s);//Sachin Tendulkar
8. }
9. }
Output:Sachin Tendulkar

The compiler transforms this to:

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

1. class Simple{
2. public static void main(String args[]){
3.
4. String s=50+30+"Sachin"+40+40;
5. System.out.println(s);//80Sachin4040

Page
95
6. }
7. }
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){}

1. //<b><i>Example of concat(String) method</i></b>


2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s1="Sachin ";
7. String s2="Tendulkar";
8.
9. String s3=s1.concat(s2);
10.
11. System.out.println(s3);//Sachin Tendulkar
12. }
13.}
Output:Sachin Tendulkar

Substring in Java

Page
96
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


1. //Example of substring() method
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin Tendulkar";
7. System.out.println(s.substring(6));//Tendulkar
8. System.out.println(s.substring(0,6));//Sachin
9. }
10.}
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.

Page
97
2)public boolean equalsIgnoreCase(String Compares this String to another String,
another) ignoring 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


str) differences.

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


lower 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

Page
98
string object.

First seven methods have already been discussed. Now let’s take the example of
other methods:

toUpperCase() and toLowerCase() method


1. //<b><i>Example of toUpperCase() and toLowerCase() method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin";
7. System.out.println(s.toUpperCase());//SACHIN
8. System.out.println(s.toLowerCase());//sachin
9. System.out.println(s);//Sachin(no change in original)
10. }
11.}
Output:SACHIN
sachin
Sachin

trim() method
1. //<b><i>Example of trim() method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s=" Sachin ";
7. System.out.println(s);// Sachin
8. System.out.println(s.trim());//Sachin
9. }
10.}
Output:Sachin
Sachin

startsWith() and endsWith() method


1. //<b><i>Example of startsWith() and endsWith() method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.

Page
99
6. String s="Sachin";
7. System.out.println(s.startsWith("Sa"));//true
8. System.out.println(s.endsWith("n"));//true
9. }
10.}
Output:true
true

charAt() method
1. //<b><i>Example of charAt() method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin";
7. System.out.println(s.charAt(0));//S
8. System.out.println(s.charAt(3));//h
9. }
10.}
Output:S
h

length() method
1. //<b><i>Example of length() method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin";
7. System.out.println(s.length());//6
8. }
9. }
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.

1. //<b><i>Example of length() method</i></b>

Page
100
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s=new String("Sachin");
7. String s2=s.intern();
8. System.out.println(s2);//Sachin
9. }
10.}
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

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

1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello ");
5. sb.append("Java");//now original string is changed
6.
7. System.out.println(sb);//prints Hello Java
8. }
9. }

Example of insert() method of StringBuffer class


The insert() method inserts the given string with this string at the given position.

1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello ");
5. sb.insert(1,"Java");//now original string is changed
6.

Page
102
7. System.out.println(sb);//prints HJavaello
8. }
9. }

Example of replace() method of StringBuffer class


The replace() method replaces the given string from the specified beginIndex and
endIndex.

1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.replace(1,3,"Java");
6.
7. System.out.println(sb);//prints HJavalo
8. }
9. }

Example of delete() method of StringBuffer class


The delete() method of StringBuffer class deletes the string from the specified
beginIndex to endIndex.

1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.delete(1,3);
6.
7. System.out.println(sb);//prints Hlo
8. }
9. }

Example of reverse() method of StringBuffer class


The reverse() method of StringBuilder class reverses the current string.

1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.reverse();
6.
7. System.out.println(sb);//prints olleH
8. }
9. }

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

1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10.sb.append("java is my favourite language");
11.System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12.}
13.}

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.

1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10.sb.append("java is my favourite language");
11.System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12.
13.sb.ensureCapacity(10);//now no change
14.System.out.println(sb.capacity());//now 34
15.
16.sb.ensureCapacity(50);//now (34*2)+2
17.System.out.println(sb.capacity());//now 70

Page
104
18.
19.}
20.}

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.

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

1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello ");
5. sb.append("Java");//now original string is changed
6.
7. System.out.println(sb);//prints Hello Java
8. }
9. }

Example of insert() method of StringBuilder class


The insert() method inserts the given string with this string at the given position.

1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello ");
5. sb.insert(1,"Java");//now original string is changed
6.
7. System.out.println(sb);//prints HJavaello
8. }
9. }

Example of replace() method of StringBuilder class


The replace() method replaces the given string from the specified beginIndex and
endIndex.

1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.replace(1,3,"Java");
6.
7. System.out.println(sb);//prints HJavalo
8. }
9. }

Page
106
Example of delete() method of StringBuilder class
The delete() method of StringBuilder class deletes the string from the specified
beginIndex to endIndex.

1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.delete(1,3);
6.
7. System.out.println(sb);//prints Hlo
8. }
9. }

Example of reverse() method of StringBuilder class


The reverse() method of StringBuilder class reverses the current string.

1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.reverse();
6.
7. System.out.println(sb);//prints olleH
8. }
9. }

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.

1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10.sb.append("java is my favourite language");
11.System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2

Page
107
12.}
13.}

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.

1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10.sb.append("java is my favourite language");
11.System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12.
13.sb.ensureCapacity(10);//now no change
14.System.out.println(sb.capacity());//now 34
15.
16.sb.ensureCapacity(50);//now (34*2)+2
17.System.out.println(sb.capacity());//now 70
18.
19.}
20.}

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.

1. public final class Employee{


2. final String pancardNumber;

Page
108
3.
4. public Employee(String pancardNumber){
5. this.pancardNumber=pancardNumber;
6. }
7.
8. public String getPancardNumber(){
9. return pancardNumber;
10.}
11.
12.}

The above class is immutable because:

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

1. class Student{
2. int rollno;

Page
109
3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
7. this.rollno=rollno;
8. this.name=name;
9. this.city=city;
10. }
11.
12. public static void main(String args[]){
13. Student s1=new Student(101,"Raj","lucknow");
14. Student s2=new Student(102,"Vijay","ghaziabad");
15.
16. System.out.println(s1);//compiler writes here s1.toString()
17. System.out.println(s2);//compiler writes here s2.toString()
18. }
19.}
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.

1. class Student{
2. int rollno;
3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
7. this.rollno=rollno;
8. this.name=name;
9. this.city=city;
10. }
11.
12. public String toString(){//overriding the toString() method
13. return rollno+" "+name+" "+city;
14. }
15. public static void main(String args[]){
16. Student s1=new Student(101,"Raj","lucknow");
17. Student s2=new Student(102,"Vijay","ghaziabad");
18.

Page
110
19. System.out.println(s1);//compiler writes here s1.toString()
20. System.out.println(s2);//compiler writes here s2.toString()
21. }
22.}
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


String delim) delimeter.

StringTokenizer(String str, creates StringTokenizer with specified string, delimeter


String delim, boolean and returnValue. If return value is true, delimiter
returnValue) characters are 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.

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

1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }
Output:my
name
is
khan

Example of nextToken(String delim) method of


StringTokenizer class
1. import java.util.*;
2.
3. public class Test {
4. public static void main(String[] args) {
5. StringTokenizer st = new StringTokenizer("my,name,is,khan");
6.
7. // printing next token
8. System.out.println("Next token is : " + st.nextToken(","));
9. }
10.}

Page
112
Output:Next token is : my

StringTokenizer class is deprecated now. It is recommended to use split()


method of String class or regex (Regular Expression).

Nested classes in Java


A class declared inside a class is known as nested class. We use nested classes to
logically group classes in one place so that it can be more readable and
maintainable code. Moreover, it can access all the members of outer class
including private members.

Syntax of Nested class


1. class Outer_class_Name{
2. ...
3. class Nested_class_Name{
4. ...
5. }
6. ...
7. }

Advantage of nested classes


There are basically three advantages of nested classes. They are

 Nested classes represent a special type of relationship that is it can access all
the members (data members and methods) of outer class including private.
 Nested classes can lead to more readable and maintainable code because it
logically group classes in one place only.
 Code Optimization as we need less code to write.

Que) What is the difference between nested class and


inner class?
Inner class is a part of nested class. Non-static nested classes are known as Inner
classes.

Types of Nested class:


There are two types of nested classes non-static and static nested classes.The

Page
113
non-static nested classes are also known as inner classes.

1. non-static nested class(inner class)


o a)Member inner class
o b)Annomynous inner class
o c)Local inner class
2. static nested class

What we will learn in Nested classes?

 Nested class
 Member inner class
 Annonymous inner class
 Local Inner class
 static nested class
 Nested interface

1)Member inner class


A class that is declared inside a class but outside a method is known as member
inner class.

Page
114
Invocation of Member Inner class
1. From within the class
2. From outside the class

Example of member inner class that is invoked


inside a class
In this example, we are invoking the method of member inner class from the display
method of Outer class.

1. class Outer{
2. private int data=30;
3. class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6.
7. void display(){
8. Inner in=new Inner();
9. in.msg();
10. }
11. public static void main(String args[]){
12. Outer obj=new Outer();
13. obj.display();
14. }
15.}
Output:data is 30

Internal code generated by the compiler for member inner


class:
The java compiler creates a class file named Outer$Inner in this case. The
Member inner classes have the reference of Outer class that is why it can access
all the data members of Outer class including private.

1. import java.io.PrintStream;
2.
3. class Outer$Inner
4. {
5. final Outer this$0;
6. Outer$Inner()
7. { super();
8. this$0 = Outer.this;

Page
115
9. }
10.
11. void msg()
12. {
13. System.out.println((new StringBuilder()).append("data is ")
14. .append(Outer.access$000(Outer.this)).toString());
15. }
16.
17. }

Example of member inner class that is invoked


outside a class
In this example, we are invoking the msg() method of Inner class from outside the
outer class i.e. Test class.

1. <b><i>//Program of member inner class that is invoked outside a class</i></b>


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

Page
116
12. Outer obj=new Outer();
13. Outer.Inner in=obj.new Inner();
14. in.msg();
15. }
16.}
Output:data is 30

2)Annonymous inner class


Classes that have no name are known as annomymous inner class.

Annonymous class can be created by:

1. Class (may be abstract class also).


2. Interface

Program of annonymous inner class by abstract class


1. abstract class Person{
2. abstract void eat();
3. }
4.
5. class Emp{
6. public static void main(String args[]){
7. Person p=new Person(){
8. void eat(){System.out.println("nice fruits");}
9. };
10.
11. p.eat();
12. }
13.}
Output:nice fruits

What happens behind this code?


1. Person p=new Person(){
2. void eat(){System.out.println("nice fruits");}
3. };
4.
5. }
6. }
1. A class is created but its name is decided by the compiler which extends the
Person class and provides the implementation of the eat() method.
2. An object of Annonymous class is created that is reffered by p reference
variable of Person type. As you know well that Parent class reference variable
can refer the object of Child class.

Page
117
The internal code generated by the compiler for
annonymous inner class
1. import java.io.PrintStream;
2. static class Emp$1 extends Person
3. {
4. Emp$1(){}
5.
6. void eat()
7. {
8. System.out.println("nice fruits");
9. }
10.}

Program of annonymous inner class by interface


1. interface Eatable{
2. void eat();
3. }
4.
5. class Emp{
6. public static void main(String args[]){
7.
8. Eatable e=new Eatable(){
9. public void eat(){System.out.println("nice fruits");}
10. };
11. e.eat();
12. }
13.}
Output:nice fruits

What does the compiler for annonymous inner class


created by interface
It performs two main tasks behind this code:

1. Eatable p=new Eatable(){


2. void eat(){System.out.println("nice fruits");}
3. };
4.
5. }
6. }
1. A class is created but its name is decided by the compiler which implements
the Eatable interface and provides the implementation of the eat() method.

Page
118
2. An object of Annonymous class is created that is reffered by p reference
variable of Eatable type. As you know well that Parent class reference
variable can refer the object of Child class.

The internal code generated by the compiler for


annonymous inner class created by interface
1. import java.io.PrintStream;
2. static class Emp$1 implements Eatable
3. {
4. Emp$1(){}
5.
6. void eat(){System.out.println("nice fruits");}
7. }

3)Local inner class


A class that is created inside a method is known as local inner class. If you want
to invoke the methods of local inner class, you must instantiate this class inside
the method.

Program of local inner class


1. class Simple{
2. private int data=30;//instance variable
3. void display(){
4. class Local{
5. void msg(){System.out.println(data);}
6. }
7. Local l=new Local();
8. l.msg();
9. }
10. public static void main(String args[]){
11. Simple obj=new Simple();
12. obj.display();
13. }
14.}
Output:30

Internal code generated by the compiler for local inner


class
In such case, compiler creates a class named Simple$1Local that have the
reference of the outer class.

1. import java.io.PrintStream;

Page
119
2. class Simple$1Local
3. {
4. final Simple this$0;
5.
6. Simple$1Local()
7. {
8. super();
9. this$0 = Simple.this;
10. }
11. void msg()
12. {
13. System.out.println(Simple.access$000(Simple.this));
14. }
15.
16.}

Rule: Local variable can't be private, public or protected.

Rules for Local Inner class


1) Local inner class cannot be invoked from outside the method.

2) Local inner class cannot access non-final local variable.

Program of accessing non-final local variable in local inner


class
1. class Simple{
2. private int data=30;//instance variable
3. void display(){
4. int value=50;//local variable must be final
5. class Local{
6. void msg(){System.out.println(value);}//C.T.Error
7. }
8. Local l=new Local();
9. l.msg();
10. }
11. public static void main(String args[]){
12. Simple obj=new Simple();
13. obj.display();
14. }
15.}
Output:Compile Time Error

Page
120
Program of accessing final local variable in local inner
class
1. class Simple{
2. private int data=30;//instance variable
3. void display(){
4. final int value=50;//local variable must be final
5. class Local{
6. void msg(){System.out.println(data+" "+value);}//ok
7. }
8. Local l=new Local();
9. l.msg();
10. }
11. public static void main(String args[]){
12. Simple obj=new Simple();
13. obj.display();
14. }
15.}
Output:30 50

4)static nested class


A static class that is created inside a class is known as static nested class. It cannot
access the non-static members.

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


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

Program of static nested class that have instance method


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

In this example, you need to create the instance of static nested class because it
has instance method msg(). But you don't need to create the object of Outer class
because nested class is static and static properties, methods or classes can be

Page
121
accessed without object.

Internal code generated by the compiler for static nested class


1. import java.io.PrintStream;
2.
3. static class Outer$Inner
4. {
5. Outer$Inner(){}
6.
7. void msg(){
8. System.out.println((new StringBuilder()).append("data is ")
9. .append(Outer.data).toString());
10.}
11.
12.}

Program of static nested class that have static method


1. class Outer{
2. static int data=30;
3.
4. static class Inner{
5. static void msg(){System.out.println("data is "+data);}
6. }
7.
8. public static void main(String args[]){
9. Outer.Inner.msg();//no need to create the instance of static nested class
10. }
11.}
Output:data is 30

Page
122

You might also like