You are on page 1of 118

OBJECT ORIENTED PROGRAMMING THROUGH JAVA

By.
G.Praveen Kumar
Assit.Prof , IT Dept.
SNIST.

G.Praveen ITDept-SNIST 1
UNIT I

1.History of Java, Java buzzwords,


2.Data types, Variables,
3. Simple java program, Scope and life time of variables,
4.Operators, Expressions,
5.Control Statements,
6.Type conversion and costing,
7.Arrays
8.Classes and objects – concepts of classes, objects,
9.Constructors, methods,
10.Access control, this keyword, Garbage collection,
11.Overloading methods and Constructors,
12.Recursion, String handling, String Tokenizer.

G.Praveen ITDept-SNIST 2
Objective:
On the completion of the unit, a student should be able to:
i)Write compile and execute simple java programs
ii) Understand the syntax of classes and objects creation in java
iii) Explain the differences between classes and objects
iv)differentiate methods and constructors
v) Understand constructor and method overloading
vi) Understand how to handle strings in java

G.Praveen ITDept-SNIST 3
Introduction TO Programming Languages
& Features of JAVA
History of Java, Java buzzwords,

G.Praveen ITDept-SNIST 4
“A programming language is a notational system for describing computation in a
machine-readable and human-readable form. A programming language is a tool for
developing executable models for a class of problem domains.”

OR
“ A programming language is a set of rules that provides a way of telling a
computer what operations to perform”

Type of Programming Languages

1)Compiler Programming Languages


2)Interpreter Programming Languages

G.Praveen ITDept-SNIST 5
Interpreter Compiler
Scans the entire program and
Translates program one statement at a
translates it as a whole into machine
time.
code.
It takes large amount of time to
It takes less amount of time to
analyze the source code but the
analyze the source code but the
overall execution time is
overall execution time is slower.
comparatively faster.
No intermediate object code is Generates intermediate object code
generated, hence are memory which further requires linking, hence
efficient. requires more memory.
Continues translating the program It generates the error message only
until the first error is met, in which after scanning the whole program.
case it stops. Hence debugging is Hence debugging is comparatively
easy. hard.
Programming language like
Programming language like C, C++
HTML,JAVA Script , Python, Ruby
use compilers.
use interpreters.
G.Praveen ITDept-SNIST 6
G.Praveen ITDept-SNIST 7
History of Java
The Birth of JAVA - as a technology for Set Top Boxes !
The Java platform and language began as an internal project at Sun
Microsystems in December 1990, providing an alternative to the C++/C
programming languages. Engineer Patrick Naughton, James Gosling and
Mike Sheridan were attempting to develop a new technology for
programming next generation smart appliances (like set-top boxes!), which
Sun expected to be a major new opportunity. It was called the Green project.

G.Praveen ITDept-SNIST 8
Year Progress
1990 Sun decided to developed software that could be used for
electronic devices. And the project called as Green Project
head by James Gosling.
1991 Announcement of a new language named ―Oak‖
1992 The team verified the application of their new language to
manage a list of home appliances using a hand held device.
1993 The WWW appeared on the Internet and transformed the
text-based interface to a graphical rich environment.
1994 The team developed a new Web browsed called ―Hot
Java‖ to locate and run Applets
1995 Oak was renamed to Java, as it did not survive ―legal‖
registration. Many companies such as Netscape and
Microsoft announced their support for Java.
1996 Java language is now famous for Internet programming as
well as a general purpose
G.Praveen OO language.
ITDept-SNIST 9
Year Progress
1997 Sun releases Java Development Kit(JDK 1.1)
1998 Sun releases Software Development Kit (SDK 1.2)
1999 Sun releases Java 2 platform Standard Edition (J2SE)
and Enterprise Edition(J2EE).
2000 J2SE with SDK 1.3 was released.

2002 J2SE with SDK 1.4 was released.

2004 J2SE with JDK 5.0 was released.

G.Praveen ITDept-SNIST 10
Introduction to JAVA
Java is on Object-Oriented , cross plat form ,
multipurpose programming language Developed by
 James Gosling  and his team at Sun Microsystems.
Gosling's new language needed to be
accessible by a variety of computer processors.
  In 1994, and he understand that such a language would be
ideal for use with web browsers and Java's connection
to the internet began. 
In 1995, Netscape Incorporated released its latest version of
the Netscape browser which was capable of running Java programs.

Why is it called Java? 


??????????????????????????????????
 

G.Praveen ITDept-SNIST 11
The original name of this language was Oak, until it was discovered that a
programming language already existed that was named Oak.

It is customary for the creator of a programming language to name the language
anything he chooses.  As the story goes, after many hours of trying to come up with a
new name, the development team went out for coffee and the name Java was born.

     While Java is viewed as a programming language to design applications for the
Internet, it is in reality a general all purpose language which can be used independent
of the Internet.

G.Praveen ITDept-SNIST 12
Features of JAVA
1. Simple
2.Secure
3.Object Oriented
4. Robust
5.Platform Independent
6.Multi Threading
7.Architectural Neutral
8.Portable
9.High Performance
10.Ease of Use
11.Improved Polyglot programming
12.Improved Security and performance

G.Praveen ITDept-SNIST 13
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand.
The confusing and ambiguous concepts of C++ are either left out in Java or they have
been re-implemented in a cleaner way.

Eg : Pointers and Operator Overloading are not there in java but were an important part of
C++.
2) Secure
Java is very secure language . With java secure features it enable us to develop
virus free, temper free system. Java program always runs in Java runtime environment
with almost null interaction with system OS, hence it is more secure.

Java Security measures

a)) No use of pointers :-


C/C++ language uses pointers, which may cause unauthorized access to memory
blocks when other programs get the pointer values. Unlike conventional C/C++ language,
Java never uses any kind of pointers. Java has its internal mechanism for memory
management. It only gives access to the data to the program if has appropriate verified
authorization.

G.Praveen ITDept-SNIST 14
b)Exception handling concept: The concept of exception handling enables Java to
capture a series of errors that helps developers to get rid of risk of crashing the system.

c) Byte code is another thing that makes Java more secure:-


Every time when a user compiles the Java program, the Java compiler creates a
class file with Byte code, which are tested by the JVM at the time of program execution
for viruses and other malicious files
d)Garbage collection mechanism:-
Garbage collection(gc()) mechanism aids more to the security measures of Java.
It provides a transparent storage allocation and recovering unutilized memory rather than
deallocating memory through manual action. It will help developers to ensure the
integrity of the program during its execution and avoids any JVM crash due to incorrect
freeing of memory.
e) Tested code re-usability:-
The Java object encapsulation provides support for the concept of “programming
by contract”. This allows the developers to re-use the code that has already been
tested while developing Java enterprise applications.
f) Defined order execution:-
All the primitives are defined with a predefined size and all the operations are defined in
a specific order of execution. So the code executed in different Java Virtual Machines
won’t have  a different order of execution.
.
G.Praveen ITDept-SNIST 15
g) Access Control functionality
Java’s access-control functionality on variables and methods within the objects
provide secure program by preventing access to the critical objects from the untrusted
code

h)Protection from security attacks


It allows developers to declare classes or methods as FINAL. We all know that any
class or method declared as final can’t be overridden, which helps developers to
protect code from security attacks like creating a subclass and replacing it with the
original class and override methods.

I) Type-safe reference casting in JVM


Whenever you use an object reference, the JVM monitors you. If you try to cast a
reference to a different type, it will make the cast invalid.  

G.Praveen ITDept-SNIST 16
G.Praveen ITDept-SNIST 17
Introduction to OOP’s (Object-Oriented Programming Concepts)

The concepts used in OOPs are


I.Classes
II. Objects
III. Data Abstraction
IV. Data Encapsulation
V. Inheritance
VI.Polymorphism
VII. Dynamic Binding
VIII. Message Passing

G.Praveen ITDept-SNIST 18
Class:- A class is a set of objects with similar properties (attributes), common behavior
(operations), and common link to other objects. The complete set of data and code of an
object can be made a user defined data type with the help of class. The objects are variable
of type class. A class is a collection of objects of similar type. Classes are user defined
data types and work like the build in type of the programming language. Once the class
has been defined, we can make any number of objects belonging to that class. Each object
is related with the data of type class with which they are formed.
As we learned that, the classification of objects into various classes is based on its
properties (States) and behavior (methods). Classes are used to distinguish are type of
object from another. The important thing about the class is to identify the properties and
procedures and applicability to its instances.
For example:College-
SNIST

IT

XYZ

G.Praveen ITDept-SNIST sub2 19


sub1
Object:- Objects are important runtime entities in object oriented method.
They may characterize a location, a bank account, and a table of data or any
entry that the program must handle.

Data Abstraction:- Data abstraction refers to the act of representing


important description without including the background details or
explanations. Classes use the concept of abstraction and are defined as a list
of abstract attributes such as size, cost and functions operate on these
attributes. They summarize all the important properties of the objects that are
to be created. Classes use the concepts of data abstraction and it is called as
Abstract Data Type (ADT).

Data Encapsulation:- Data Encapsulation means wrapping of data and


functions into a single unit (i.e. class). It is most useful feature of class. The
data is not easy to get to the outside world and only those functions which are
enclosed in the class can access it. These functions provide the boundary
between Object‘s data and program. This insulation of data from direct access
by the program is called as Data hiding.

G.Praveen ITDept-SNIST 20
Polymorphism:- When one task is performed by different
ways  known as polymorphism.
“POLY+MORPHISM=“MANY+FORM”
‘HAVING MANY FORMS is know as Polymorphism.
For example: To convince the
customer differently, to draw something
e.g. shape or rectangle etc.
In java,
we use method overloading
and method overriding to achieve polymorphism.
Abstraction:- Hiding internal details and showing
functionality is known as abstraction. For example: phone call,
we don't know the internal processing.
In java, we use abstract class and interface to achieve
abstraction.

Encapsulation:- Binding (or wrapping) code and data together into a single unit 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.

G.Praveen ITDept-SNIST 21
Robust:-Java makes an effort to eliminate error level codes by highlight mainly
on compile time error checking and runtime checking. But the main areas which
Java improved were Memory Management and mishandled Exceptions by
introducing automatic Garbage Collector and Exception Handling.
Platform Independent:- All programming languages such as C, C++ etc which
are compiled into platform specific machines. Java is guaranteed to be write-
once, run-anywhere language.
A Java program is compiled into byte code. This byte code is platform
independent and can be run on any machine, plus this byte code
format also provide security. Any machine with Java Runtime Environment can
run Java Programs.

G.Praveen ITDept-SNIST 22
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many
tasks simultaneously. Benefit of multithreading is that it utilizes same memory and
other resources to execute multiple threads at the same time, like While typing,
grammatical errors are checked along.

7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer
architecture, hence a Java program is easy to intrepret on any machine.

8) Portable
Java Byte code can be carried to any platform. No implementation dependent
features. Everything related to storage is predefined, example: size of primitive data
types

9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language
like C or C++. But, Java enables high performance with the use of just-in-time
compiler.
G.Praveen ITDept-SNIST 23
JVM (Java Virtual Machine) :- JVM (Java Virtual Machine) is an abstract
machine. It is a specification that provides runtime environment in which java byte
code can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is
platform dependent).

JVM performs following operation:-


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

G.Praveen ITDept-SNIST 24
Internal Architecture of JVM

JVM Architecture
G.Praveen ITDept-SNIST 25
1)Classloader:- Classloader is a subsystem of JVM that is used to load class
files.
2) Class(Method) Area:- Class(Method) Area stores per-class structures such
as the runtime constant pool, field and method data, the code for methods.
3) Heap:- It is the runtime data area in which objects are allocated.
4) Stack:- Java Stack stores frames. It holds local variables and partial results,
and plays a part in method invocation and return. Each thread has a
private JVM stack, created at the same time as thread. A new frame is
created each time a method is invoked. A frame is destroyed when its
method invocation completes.

G.Praveen ITDept-SNIST 26
5) Program Counter Register:- PC (program counter) register. It
contains the address of the Java virtual machine instruction currently
being executed.

6) Native Method Stack:- It contains all the native methods used in the
application
.
7) Execution Engine:- It contains:
a) A virtual processor
b) Interpreter: Read byte code stream then execute the
instructions.
c)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. 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.

G.Praveen ITDept-SNIST 27
Variables and Data Types in Java:-
Variable is name of reserved area allocated in memory. it is a name of memory
location.
eg:- int a=35; //a is varaible it stroes value 35.

Types of Variable :- There are three types of variables in java

G.Praveen ITDept-SNIST 28
1) Local Variable:-
A variable which is declared inside the method is called local variable.
2) Instance Variable:-
A variable which is declared inside the class but outside the method, is called
instance variable . It is not declared as static.
3) 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.

class IT-2A
{  
int data=11;//instance variable  
static int Code=31;//static variable  
void method()
{  
int n=01;//local variable  
}  
}//end of class  

G.Praveen ITDept-SNIST 29
Scope and Lifetime of Variables in Java:-
Scope and Lifetime of Variables. The scope of a variable defines the
section of the code in which the variable is visible. As a general
rule, variables that are defined within a block are not accessible outside that
block. The lifetime of a variable refers to how long the variable exists before it
is destroyed.

G.Praveen ITDept-SNIST 30
Data Types in Java:- Data types are used to allocate the memory .Data types
represent the different values to be stored in the variable. In java, there are two
types of data types:
Primitive data types(or) Predefined
Non-primitive data types (or) User defined

G.Praveen ITDept-SNIST 31
Data Type Default Default Range
Value size
boolean false 1 bit true or false
char '\u0000' 2 byte 0 to 65,536 (unsigned)

byte 0 1 byte -128 to 127


short 0 2 byte -32,768 to 32,767

int 0 4 byte -2,147,483,648 to 2,147,483, 647

long 0L 8 byte -9,223,372,036,854,775,808 to 


9,223,372,036,854,775,807
float 0.0f 4 byte approximately ±3.40282347E+38F 
(6-7 significant decimal digits) 
Java implements IEEE 754 standard
double 0.0d 8 byte approximately
±1.79769313486231570E+308
 (15 significant decimal digits)

G.Praveen ITDept-SNIST 32
Operators:- Operator in java is a symbol that is used to perform special operations.
For example: +, -, *, / etc.
There are basically two types of Operators
1) Unary Operator
2)Binary Operator
1)Unary Operator:- This operator perform operation on single operand (Variable);
eg:-a=a+10;
2) Binary Operator:- This operator perform operation on more than ne operands
Eg:- c=a+b;

operators in java:- java support following operators


1.Arithmetic Operator,
2.Logical Operator,
3.Relational Operator,
4.Assignment Operator.
5.Increment / decrement Operator
6.shift Operator,
7.Bitwise Operator,
8.Ternary Operator and

G.Praveen ITDept-SNIST 33
Java Operator Precedence
Operator Type Category Precedence
Incrment/Decrement postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%


additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |=
<<= >>= >>>=
G.Praveen ITDept-SNIST 34
class Student2a
{
int sno;
String name;
static String college ="SNIST";
void get(int r,String n)
{
sno = r;
name = n;
}
void display ()
{System.out.println(sno+" "+name+" "+college);
}}

G.Praveen ITDept-SNIST 35
class SS
{
public static void main(String args[])
{
Student2a s1 = new Student2a();
Student2a s2 = new Student2a();

s1.get(001,"KIRAN");
s2.get(043,"NAVEEN");
s1.display();
s2.display();
} }
OUTPUT:-
C:\praveen\JAVA>java SS
1 KIRAN SNIST
35 NAVEEN SNIST
G.Praveen ITDept-SNIST 36
G.Praveen ITDept-SNIST 37
class Student2a
{
int sno;
String name;
static String college ="SNIST";
void get(int r,String n)
{
sno = r;
name = n;
}
void display ()
{System.out.println(sno+" "+name+" "+college);
}}
class s11 extends Student2a
{
college="JNTU";//
void show()
{System.out.println(sno+" "+name+" "+college);
}}
G.Praveen ITDept-SNIST 38
class SS1
{

public static void main(String args[])


{
s11 s1 = new s11();//(111,"Karan");
s11 s2 = new s11();//(222,"Aryan");

s1.get(001,"KIRAN");
s2.get(043,"NAVEEN");

s1.display();
s2.display();
}
}

G.Praveen ITDept-SNIST 39
If-else Statement:-  if statement is used to test the condition. It checks boolean
condition: true or false. There are various types of if statement in java.
1)if statement 2) if-else statement 3) nested if statement
IF Statement:- The Java if statement tests the condition.
It executes the if block if condition is true.
Syntax:
if(condition){  
//code to be executed  
}  
Example:-
class Con1
{
public static void main(String args[])
{
int n;
n=10;
if(n%5==0)
{
System.out.println("the number "+n+"is divided by 5");
}
}}
G.Praveen ITDept-SNIST 40
IF-else Statement:- The Java if-else statement also
tests the condition. It executes the if block if
condition is true otherwise else block is executed.
Syntax:
if(condition){  //code if condition is true  }
else{  //code if condition is false  }  

Eg:- import java.util.Scanner;


class Con2
{
public static void main(String args[])
{
Scanner s1 =new Scanner(System.in);
int n;
n=s1.nextInt();
if(n%5==0)
{
System.out.println("the number "+n+"is divided by 5");
}else
{System.out.println("the number "+n+"is not divided by 5");
}}}
G.Praveen ITDept-SNIST 41
IF-else-if ladder Statement:-The if-else-if ladder statement executes one
condition from multiple statements.
Syntax:
if(condition1){  
//code to be executed if condition1 is true  
}else if(condition2){  
//code to be executed if condition2 is true  
}  
else if(condition3){  
//code to be executed if condition3 is true  
}  
...  
else{  
//code to be executed if all the conditions are false  
}  

G.Praveen ITDept-SNIST 42
G.Praveen ITDept-SNIST 43
Switch Statement:-
The Java switch statement executes one statement from multiple conditions.
It is like if-else-if ladder statement.

Syntax:
switch(expression){    
case value1:    
 //code to be executed;    
 break;  //optional  
case value2:    
 //code to be executed;    
 break;  //optional  
......    
    
default:     
 code to be executed if all cases are not matched;    
}    

G.Praveen ITDept-SNIST 44
G.Praveen ITDept-SNIST 45
G.Praveen ITDept-SNIST 46
Compare switch and nested if-else

1. The main difference between switch and if-else is that the


expression in if-else can result to a value of any data type, while
the expression in switch should result to an integer value or to a
value of datatype char.

2. The second difference is that the switch statement can check


only for equality while the if-else statement can check any
condition like equal to, less than, greater than or equal to etc.

G.Praveen ITDept-SNIST 47
G.Praveen ITDept-SNIST 48
Type conversion and costing:-Assigning a value of one type to a variable
of another type is known as Type Casting.
Eg:- int x = 10;
byte y = (byte)x;
Type casting is classified into two types

1. Widening Casting(Implicit)
2. Narrowing Casting(Explicitly done)

1. Widening Casting(Implicit) :-It is also called Automatic Type casting


in this type the target type is larger than the source type.

G.Praveen ITDept-SNIST 49
public class Testcasting1
{
public static void main(String[] args)
{
int i = 25;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}}
OUTPUT:-

C:\praveen>java Testcasting1
Int value 25
Long value 25
Float value 25.0

G.Praveen ITDept-SNIST 50
2. Narrowing Casting(Explicitly done) :- larger type value to a variable of smaller
type is called explicit type casting.

public class Testcasting2


{
public static void main(String[] args)
{
double d = 300.25;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required

System.out.println("Double value "+d); C:\praveen>java Testcasting2


System.out.println("Long value "+l); Double value 300.25
System.out.println("Int value "+i); Long value 300
}} Int value 300

G.Praveen ITDept-SNIST 51
Arrays:- “An array is a Indexed collection of fixed number of homogenous
data elements”.
An array can be either primitive or reference type. It gets memory in heap area.
Index of array starts from zero to size-1.

Advantage of Java Array:-


i. Indexing:-It is always indexed. Index begins from 0.
ii. Memory allocation:-It occupies a contiguous memory location.
iii. Code Optimization: It makes the code optimized, we can retrieve or sort
the data easily.
iv. Random access: We can get any data located at any index position.
Disadvantage of Java Array:-
i. 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.
G.Praveen ITDept-SNIST 52
Array Declaration:-
Syntax :
datatype[ ] identifier; (or) datatype identifier[ ];
Both are valid syntax for array declaration.
Example :
int[ ] a , short S[ ] , int A[ ][ ] ;
Initialization of Array:- new operator is used to initialize an array.
EG:- int a[ ] = new int[10]; //this creates an empty array named a of integer type
whose size is 10.
int b[ ] = {10,20,30,40,50}; //this creates an array named b and assign elements
are given.

Types of Array :- There are two types of array.

1.Single Dimensional Array


2.Multidimensional Array

G.Praveen ITDept-SNIST 53
Note: To find the length of an array, we can use the following
syntax: array_name.length. There are no braces infront of length. Its not length().
G.Praveen ITDept-SNIST 54
G.Praveen ITDept-SNIST 55
OUTPUT:-
C:\praveen>java Bsort
Enter size of array
5
Enter elements in to array
56
89
3
12
1
Array Before Bubble Sort
56 89 3 12 1
Array After Bubble Sort
1 3 12 56 89

G.Praveen ITDept-SNIST 56
Multidimensional array:- A multi-dimensional array is very much similar to a
single dimensional array. It can have multiple rows and multiple columns unlike
single dimensional array.
Array Declaration:-
dataType[][]  identifier; (or)   = int [][] a
dataType [][] identifier ; (or)  = int [][]a
dataType  identifier[][]; (or)  =int a[][]
dataType [] identifier [];   = int []a[]

Initialization of Array:-
int[ ][ ] arr = new int[size-n][size-m]; = int[ ][ ] M = new int[5][5];

int[ ][ K= {{11,22,13,14},{6,,8,9,10},{12,13,14,15}};// 3 by 4 is the size of the


array.

G.Praveen ITDept-SNIST 57
class Twoarray
{
public static void main(String args[]){

//declaring and initializing 2D array


int a[][]={{1,2,3,4},{11,12,14,15},{14,24,34,44}};

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

OUTPUT:-
C:\praveen>java Twoarray
1234
11 12 14 15
14 24 34 44 G.Praveen ITDept-SNIST 58
G.Praveen ITDept-SNIST 59
OUTPUT:-
C:\praveen>java Matadd
enter no of rows matrix A
2
enter no of cols matrix A
2
enter no of rows matrix B
2
enter no of cols matrix B
2
enter elements in to matrix A
2 2 2 2
enter elements in to matrix B
22 2 2
sum matrix is:
4 4
4 4

G.Praveen ITDept-SNIST 60
Jagged Array:- Jagged means to have an uneven edge or surface.A jagged array means to
have a multi-dimensional array with uneven size of rows in it.

G.Praveen ITDept-SNIST 61
Class:- A class is a collection of fields (data members) and methods (procedure or
function) that operate on that data.
(or)
A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created. It is a logical entity.
A class in Java can contain:
fields
methods
constructors
blocks
nested class and interface
Syntax to declare a class:
class ClassName [extends SuperClassName]
{
[fields declaration]
[methods declaration]
}
Note:- fields (data members) are used to create methods and methods are
used to identifies behavior (or) significant of class.

G.Praveen ITDept-SNIST 62
Adding Fields: Class Student with fields
Class Student
{
int stuno;
double stufee;
String studentname;
}
Note:- The fields are also called as instance variables.
Adding Methods :-A class with only data fields has no life. Objects created by such a
class cannot respond to any messages. Methods are declared inside the body of the
class but immediately after the declaration of data fields.
The general form of a method declaration is:
Return-type MethodName (parameter-list)
{
Method-body;
}
Eg:- void get(int a,int b)
{
int c;
c=a+b;
}
G.Praveen ITDept-SNIST 63
Advantage of Method:-
Code Reusability
Code Optimization

An object is a specimen of a class. Software objects are often used to model real-
world objects.
new keyword in Java:-
The new keyword is used to allocate memory at run time. All objects get memory
in Heap memory area.

Syntax:- <class name> obj =new  <classname>();  


Ways to initialize object
There are 3 ways to initialize object in java.
By reference variable
By method
By constructor

G.Praveen ITDept-SNIST 64
G.Praveen ITDept-SNIST 65
Constructor :- Constructor  is a special type of method , method name is same as
class name is called constructor. It is used to initialize memory to the method at
object creation. Java 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 java constructor
There are basically two rules defined for the constructor.
I.Constructor name must be same as its class name
II.Constructor must have no explicit return type

Types of java constructors


There are 4 types of constructors:
1.Default constructor (no-arg constructor)
2.Parameterized constructor
3.Overload Constructor
4.Copy Constructor

G.Praveen ITDept-SNIST 66
Default Constructor:- A constructor that have no parameter is known as default
constructor.
Sy ntax:-
<classname>()
{
……
}
Eg:- class exp()
{
Int a,b;
Exp()
{ }
parameterized constructor:- A constructor that have parameters is known as
parameterized constructor.
Sy ntax:-
<classname>()
{
……
}
Eg:- class exp()
{
int a,b; G.Praveen ITDept-SNIST 67
G.Praveen ITDept-SNIST 68
Difference between constructor and method in java:-

Java Constructor Java Method


Constructor is used to initialize the Method is used to expose behaviour
state of an object. of an object.
Constructor must not have return Method must have return type.
type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default Method is not provided by compiler
constructor if you don't have any in any case.
constructor.
Constructor name must be same as Method name may or may not be
the class name. same as class name.

G.Praveen ITDept-SNIST 69
Method in JAVA:-A Java method is a collection of statements that are grouped
together to perform an operation. When you call the System.out.println() 
Creating Method:-
public static int method Name(int a, int b)
{
// body
}
Here,
public static − modifier
int − return type
methodName − name of the method
a, b − formal parameters
int a, int b − list of parameters

G.Praveen ITDept-SNIST 70
Method definition consists of a method header and a method body.
modifier returnType nameOfMethod (Parameter List)
{ // method body }
The syntax shown above includes −
modifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the
statements.
public static int minFunction(int n1, int n2)
{
int min;
if (n1 > n2) min = n2;
else
min = n1;
return min; }

G.Praveen ITDept-SNIST 71
Method Overloading:- A class has two or more methods by the same name but
different parameters, it is known as method overloading.

G.Praveen ITDept-SNIST 72
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
By changing number of arguments
By changing the data type

G.Praveen ITDept-SNIST 73
This keyword:-this is a keyword in Java which is used as a reference to the
object of the current class, with in an instance method or a constructor.
Using this we can refer the members of a class such as constructors, variables and
methods.

Note − The keyword this is used only within instance methods or constructors


the keyword this is used to −
1. Differentiate the instance variables from local variables if they have same names,
within a constructor or a method.
class Student {
int age;
Student(int age)
{
this.age = age; } }

G.Praveen ITDept-SNIST 74
G.Praveen ITDept-SNIST 75
Garbage Collection:-Garbage means unreferenced objects.
Garbage Collection is process of retrieve the runtime unused memory
automatically. i.e it is a way to destroy the unused objects.
Where as in C language we use free() function and delete() in C++. But, in java it
is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
1.It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
2.It is automatically done by the garbage collector(a part of JVM) so we don't
need to make extra efforts.
object can be unreferenced by following ways
By nulling the reference
By assigning a reference to another
By nulling a reference:-
Student s1 = new Student(); S1=null;
 By assigning a reference to another:-
Emp e1=new Empl();   Emp e2=new Emp();  
e1=e2;//now the first object referred by e1 is available for garbage collection

G.Praveen ITDept-SNIST 76
finalize() method:-
The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing.
This method is defined in Object class as:
 void finalize()
{
}
gc() method:-
The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
public static void gc()
{
}  

  

G.Praveen ITDept-SNIST 77
ACCESS SPECIFIERS:-The Access Modifiers are used to  access  the classes,
constructors, methods and fields out side the world , i.e. a class can control what
information or data can be accessible by other classes.

Java support a wide variety of modifiers they are

I. Access Modifiers
II. Non-Access Modifiers

I. Access Control Modifiers:- Java provides a number of access modifiers to set


access levels for classes, variables, methods and constructors. The four access
levels are −
a.default (Visible to the package, No modifiers are needed.)
b.private (Visible to the class only )
c.public (Visible to the world ).
d.protected (Visible to the package and all subclasses).

G.Praveen ITDept-SNIST 78
a. Default (no value):The default access level is declared by not writing any
access modifier at all. Any class, field, method or constructor that has no
declared access modifier is accessible only by classes in the same package.
b. private: The private (most restrictive) modifiers can be used for members but
cannot be used for classes and Interfaces. Fields, methods or constructors
declared private are strictly controlled, which means they cannot be accessed by
anywhere outside the class
c. protected: The protected fields or methods, cannot be used for classes and
Interfaces. Fields, methods and constructors declared protected in a super-class
can be accessed only by subclasses in other packages. Classes in the same
package can also access protected fields, methods and constructors as well,
even if they are not a subclass of the protected member’s class.
d. public: Members (variables, methods, and constructors) declared public (least
restrictive) within a public class are visible to any class in the Java program,
whether these classes are in the same package or in another package. Below
screen shot shows eclipse view of public class with public members.

G.Praveen ITDept-SNIST 79
Default Access Modifier – (No Keyword) default access modifier means we do not
explicitly declare an access modifier for a class, field, method, etc.

A variable or method declared without any access control modifier is available to


any other class in the same package.

The fields in an interface are implicitly public static final and the methods in an
interface are by default public.
Example:-
Any simple java class program

G.Praveen ITDept-SNIST 80
Private Access Modifier – Private Methods, variables, and constructors that are
declared private can only be accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot
be private. Variables that are declared private can be accessed outside the class, if
public methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hides
data from the outside world.

G.Praveen ITDept-SNIST 81
C:\praveen>javac accprivate.java
accprivate.java:23: error: a has private access in A
System.out.println("Value of a is:"+ob.a); ^
1 error

G.Praveen ITDept-SNIST 82
Public Access Modifier – Public class, method, constructor, interface, etc.
declared public can be accessed from any other class. The fields, methods,
blocks declared inside a public class can be accessed from any class belonging
to the Java Universe.
the public class are access is in a different package, and all the public class still
needs to be imported. Because of class inheritance, all public methods and
variables of a class are inherited by its subclasses.
Protected Access Modifier – Protected Variables, methods, and constructors,
which are declared protected in a super class can be accessed only by the
subclasses in other package.
The protected access modifier cannot be applied to class and interfaces.
Methods, fields can be declared protected,

G.Praveen ITDept-SNIST 83
Access Control and Inheritance
The following rules for inherited methods are enforced −
Methods declared public in a super class also must be public in all subclasses.
Methods declared protected in a super class must either be protected or public in
subclasses; they cannot be private.
Methods declared private are not inherited at all, so there is no rule for them.

G.Praveen ITDept-SNIST 84
II. Non-Access Modifiers:-
Java provides a number of non-access modifiers to achieve many other
functionality.
i. static
ii. Final
iii. Abstract
iv. Synchronized

i. The static modifier for creating class methods and variables.


ii.The final modifier for finalizing the implementations of classes, methods,
and variables.
iii. The abstract modifier for creating abstract classes and methods.
iv. The synchronized and volatile modifiers, which are used for threads.

G.Praveen ITDept-SNIST 85
The Static Modifier
Static Variables:- The static keyword is used to create variables that will exist
independently of any instances created for the class. Only one copy of the static
variable exists regardless of the number of instances of the class.
Static variables are also known as class variables. Local variables cannot be
declared static.

Static Methods:- The static keyword is used to create methods that will exist
independently of any instances created for the class.
Static methods do not use any instance variables of any object of the class they are
defined in. Static methods take all the data from parameters and compute something
from those parameters, with no reference to variables.
Class variables and methods can be accessed using the class name followed by a
dot and the name of the variable or method.

G.Praveen ITDept-SNIST 86
The Final Modifier:-
Final Variables
A final variable can be explicitly initialized only once. A reference variable
declared final can never be reassigned to refer to an different object.
However, the data within the object can be changed. So, the state of the object can
be changed but not the reference.
With variables, the final modifier often is used with static to make the constant a
class variable.
public class Test
{
final int value = 10; // The following are examples of declaring constants:
public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";
public void changeValue()
{
value = 12; // will give an error
}
}

G.Praveen ITDept-SNIST 87
Final Methods:-
A final method cannot be overridden by any subclasses. As mentioned
previously, the final modifier prevents a method from being modified in a
subclass.
The main intention of making a method final would be that the content of the
method should not be changed by any outsider.
Example
You declare methods using the final modifier in the class declaration, as in the
following example 
public class Test
{
public final void changeName()
{
// body of method
}
}

G.Praveen ITDept-SNIST 88
Final Classes:
The main purpose of using a class being declared as final is
to prevent the class from being subclassed. If a class is
marked as final then no class can inherit any feature from the
final class.

public final class Test


{
// body of class
}

G.Praveen ITDept-SNIST 89
The abstract Modifier:-
Abstract Class
An abstract class can never be instantiated. If a class is declared as abstract then
the sole purpose is for the class to be extended.
A class cannot be both abstract and final (since a final class cannot be
extended). If a class contains abstract methods then the class should be declared
abstract. Otherwise, a compile error will be thrown.
An abstract class may contain both abstract methods as well normal methods
EG:-pROG
Abstract Methods
An abstract method is a method declared without any implementation. The
methods body (implementation) is provided by the subclass. Abstract methods
can never be final or strict.
Any class that extends an abstract class must implement all the abstract methods
of the super class, unless the subclass is also an abstract class.
If a class contains one or more abstract methods, then the class must be declared
abstract. An abstract class does not need to contain abstract methods.
The abstract method ends with a semicolon. Example: public abstract sample();

EG:-
G.Praveen ITDept-SNIST 90
The Synchronized Modifier:-
The synchronized keyword used to indicate that a method can be accessed by
only one thread at a time. The synchronized modifier can be applied with any
of the four access level modifiers.
public synchronized void showDetails()
{
.......
}

G.Praveen ITDept-SNIST 91
Java has modifiers other than access modifiers they are
static
final
static: static can be used for members of a class. The static members of the
class can be accessed without creating an object of a class.
final: This modifier applicable to class, method, and variables. This modifier
tells the compiler not to change the value of a variable once assigned. If applied
to class, it cannot be sub-classed. If applied to a method, the method cannot be
overridden in sub-class.
Modifier class constructor method Data/variables

public Yes Yes Yes Yes


protected   Yes Yes Yes
default Yes Yes Yes Yes
private   Yes Yes Yes
static     Yes  
final Yes   Yes  

G.Praveen ITDept-SNIST 92
Modifier class constructor method Data/variables

public Yes Yes Yes Yes

protected   Yes Yes Yes

default Yes Yes Yes Yes

private   Yes Yes Yes

static     Yes  

final Yes   Yes  

G.Praveen ITDept-SNIST 93
Recursion:-A method in java that calls itself is called recursive method.
It makes the code compact.
Syntax:
returntype methodname(){  
//code to be executed  
methodname();//calling same method  
}  
Eg:- public class Receg1 {
static void p(){
System.out.println("SNIST-JAVA");
p();
}

public static void main(String[] args) {


p();
}
}

OUTPUT:-
G.Praveen ITDept-SNIST 94
import java.util.*;
class Recfact {
static int fact(int n)
{
if (n == 1)
return 1;
else
return(n * fact(n-1));
}
public static void main(String[] args) {
Scanner s1= new Scanner(System.in);
int n;
System.out.println("Enter any no");
n=s1.nextInt();
System.out.println("Factorial of 5 is: "+fact(n));
} }
OUTPUT:-
C:\praveen>javac Recfact.java
C:\praveen>java Recfact
Enter any no
9
Factorial of 5 is: 362880 G.Praveen ITDept-SNIST 95
import java.util.*;
class Recfib {
static int n1=0,n2=1,n3=0;
static void fib(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
fib(count-1);
} } OUTPUT:-
public static void main(String[] args) C:\praveen>javac Recfib.java
{
Scanner s1= new Scanner(System.in); C:\praveen>java Recfib
int n; Enter any no
System.out.println("Enter any no"); 8
0 1 1 2 3 5 8 13
n=s1.nextInt();
System.out.print(n1+" "+n2);//printing 0 and 1
fib(n-2);//n-2 because 2 numbers are already printed
}}

G.Praveen ITDept-SNIST 96
Difference between object and class:-
There are many differences between object and class. A list of differences between object and
class are
SNo. given below
Object Class
SNO OBJECT CLASS
1) Object is an instance of a class. Class is a blueprint or template from which objects
are created.
2) Object is a real world entity such as Class is a group of similar objects.
CAR,PEN,MOBILE
3) Object is a physical entity. Class is a logical entity.
4) Object is created through new Class is declared using class keyword e.g.
keyword mainly class Student{}
e.g. Student s1=new Student();
5) Object is created many times as per Class is declared once.
requirement.
6) Object allocates memory when it is Class doesn't allocated memory when it is created.
created.
7) There are many ways to create There is only one way to define class in java using
object in java such as new keyword, class keyword.
new Instance() method, clone()
method, factory method and
deserialization.
G.Praveen ITDept-SNIST 97
Java Command Line Arguments:-The java command-line argument is an
argument i.e. passed at the time of running the java program
The arguments passed from the console can be received in the java program and
it can be used as an input, and it provides a convenient way to check the
behavior of the program for the different values. W e can pass N (1,2,3 and so
on) numbers of arguments from the command prompt.
class Cmd
{
public static void main(String ar[])
{

System.out.print(ar[0]);
System.out.print(ar[1]);
System.out.print(ar[2]);
System.out.print(ar[3]);
}}
OUTPUT:-
C:\praveen>java Cmd SREENIDHI INSTITUTE SCIENCE TECHNOLOGY

SREENIDHIINSTITUTESCIENCETECHNOLOGY
G.Praveen ITDept-SNIST 98
class Cmd2 OUTPUT:-
{ C:\praveen>javac Cmd2.java
public static void main(String ar[]) C:\praveen>java Cmd2 2 12 JAVA CLASS
{ 2
int a,b; 12
a=Integer.parseInt(ar[0]); JAVACLASS
b=Integer.parseInt(ar[1]);
System.out.println(a); class Cmd1
System.out.println(b); {
System.out.print(ar[2]); public static void main(String ar[])
System.out.print(ar[3]); { int a,b,c;
}} a=Integer.parseInt(ar[0]);
b=Integer.parseInt(ar[1]);
Output:- System.out.println(a);
C:\praveen>javac Cmd1.java System.out.println(b);
C:\praveen>java Cmd1 12 13 SNIST ITDEPT c=(a+b);
12 System.out.print(ar[2]);
13 System.out.println(ar[3]);
SNISTITDEPT System.out.println("SUM IS:"+c);
SUM IS:25
}}
G.Praveen ITDept-SNIST 99
Java String:- string is basically an object that represents sequence of char values. An
array of characters works same as java string.
For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};  
String s=new String(ch);  
Creating Strings:-
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. 
Eg:- String s1=“SREENIDHI INSTITUTE OF SCIENCE & TECHNOLOGY”;

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

Eg :- String s2=“SREENIDHI INSTITUTE OF SCIENCE & TECHNOLOGY”;

G.Praveen ITDept-SNIST 100


SREENIDHI
INSTITUTE OF
SCIENCE &
TECHNOLOGY

From the above example only one object will be created. Firstly JVM will not find
any string object with the value "SREENIDHI INSTITUTE OF SCIENCE &
TECHNOLOGY" in string constant pool, so it will create a new object. After that it
will find the string with the value "SREENIDHI INSTITUTE OF SCIENCE &
TECHNOLOGY" in the pool, it will not create new object but will return the
reference to the same instance.
G.Praveen ITDept-SNIST 101
Note: String objects are stored in a special memory area known as string constant pool.
Why java uses concept of string literal?
To make Java more memory efficient (because no new objects are created if it exists already
in string constant pool).
2.By new keyword:-
String s=new String(“JAVA ");//creates two objects and one reference variable  
By using new keyword, JVM will create a new string object in normal(non pool)
heap memory and the literal “JAVA" will be placed in the string constant pool. The
variable s will refer to the object in heap(non pool).
Eg:-
public class Str1{
public static void main(String args[]){
String s1="SNIST";//creating string by java string literal
char ch[]={'I','T','D','E','P','T'};
String s2=new String(ch);//converting char array to string
String s3=new String("JAVA CLASS");//creating java string by new keyword
System.out.println(s1); OUTPUT:-
System.out.println(s2); C:\praveen>java Str1
System.out.println(s3); SNIST
}} ITDEPT
JAVA CLASS
G.Praveen ITDept-SNIST 102
Java String class methods:-The java.lang.String class provides many useful methods to perform
operations on sequence of char values.

Sno Method & Description


1 char charAt(int index)Returns the character at the specified index.
2 int compareTo(Object o)Compares this String to another Object.
3 int compareTo(String anotherString)Compares two strings lexicographically.
4 int compareToIgnoreCase(String str)Compares two strings lexicographically, gnoring
case differences.
5 String concat(String str)Concatenates the specified string to the end of this string.
6 int indexOf(int ch)Returns the index within this string of the first occurrence of the
specified character.
7 int indexOf(String str)Returns the index within this string of the first occurrence of the
specified substring.
8 int indexOf(String str, int fromIndex)Returns the index within this string of the first
occurrence of the specified substring, starting at the specified index.
9 int lastIndexOf(int ch)Returns the index within this string of the last occurrence of the
specified character.
G.Praveen ITDept-SNIST 103
Sno Method & Description
9 int length()Returns the length of this string.
10 String replace(char oldChar, char newChar)Returns a new string resulting from
replacing all occurrences of oldChar in this string with newChar.
11 String substring(int beginIndex)Returns a new string that is a substring of this
string.
12 String substring(int beginIndex, int endIndex)Returns a new string that is a
substring of this string.
13 String toLowerCase()Converts all of the characters in this String to lower case
using the rules of the default locale.
14 String toUpperCase()Converts all of the characters in this String to upper case
using the rules of the default locale.
15 String trim()Returns a copy of the string, with leading and trailing whitespace
omitted.

G.Praveen ITDept-SNIST 104


1. charAt():- charAt() method returns a char value at the given index number. The
index number starts from 0. It returns StringIndexOutOfBoundsException if given
index number is greater than this string or negative index number.
Syntax :-
public char charAt(int index)  
Eg:- String name="SREENIDHI";
char ch=name.charAt(6);
D
StringIndexOutOfBoundsException with charAt():-
If charAt() method where we are passing greater index value. In such case, it
throws StringIndexOutOfBoundsException at run time.
Eg:- String name="SREENIDHI";
char ch=name.charAt(16);
C:\praveen>javac Strfun.java
C:\praveen>java Strfun
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String ind
ex out of range: 16
at java.lang.String.charAt(String.java:658)
at Strfun.main(Strfun.java:4)
G.Praveen ITDept-SNIST 105
string concat():-This method combines specified string at the end of this string.
It returns combined string. It is like appending another string.
public String concat(String anotherString)  

public class ConcatExample{


public static void main(String args[]){
String s1="java class";
s1.concat("is not good"); OUTPUT:-
System.out.println(s1); C:\praveen>java ConcatExample
s1= s1.concat("is not good"); java class
System.out.println(s1); java classis not good
}}

G.Praveen ITDept-SNIST 106


Immutable String in Java:-In java, string objects are immutable. Immutable simply
means un modifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is
created.
public class ConcatExample{
public static void main(String args[]){
String s1="java class";
s1.concat("is not good");
System.out.println(s1);
}}
OUTPUT:-
java class
java class

From the above example java class(s1) is not changed but a new object is
created with java classis not good . That is why string is known as immutable.

G.Praveen ITDept-SNIST 107


java class(s1

java classis not


good

From the above figure that two objects are created but s reference variable still refers to
“Java class" not to “Java class is not good".
But if we explicitely assign it to the reference variable, it will refer to “Java class not good"
object
.For example: above program

G.Praveen ITDept-SNIST 108


Why string objects are immutable in java?
Because java uses the concept of string literal.Suppose there are 5 reference
variables,all referes to one object “JAVA CLASS".If one reference variable
changes the value of the object, it will be affected to all the reference
variables. That is why string objects are immutable in java.

G.Praveen ITDept-SNIST 109


String compare:- We can compare string in java on the basis of content and reference.
There are three ways to compare string in java:
1. By equals() method
2. By = = operator
3. By compareTo() method
1) String compare by equals() method:- The String 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.
class stringcomparison1{
public static void main(String args[]){
String s1="JAVA";
String s2="JAVA";
String s3=new String("JAVA"); OUTPUT:-
String s4="MFCS"; C:\praveen>java stringcomparison1
System.out.println(s1.equals(s2)); true
System.out.println(s1.equals(s3)); true
System.out.println(s1.equals(s4)); false
}
}
G.Praveen ITDept-SNIST 110
class stringcomparison2{
public static void main(String args[]){
String s1="JAVA";
String s2="java"; C:\praveen>java stringcomparison2
String s3=new String("JAVA"); false
true
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
} }
2. String compare by == operator:-The = = operator compares references not values

class stringcomparison3{
public static void main(String args[]){
String s1="JAVA";
String s2="JAVA"; OUTPUT:-
String s3=new String("JAVA"); C:\praveen>java stringcomparison3
System.out.println(s1==s2); true
System.out.println(s1==s3); false
} }
true (because both refer to same instance)  
false(because s3 refers to instance created in nonpool)  

G.Praveen ITDept-SNIST 111


3. compareTo():- compareTo() method compares the given string with current
string lexicographically. It returns positive number, negative number or 0.
It compares strings on the basis of Unicode value of each character in the strings.
If first string is lexicographically greater than second string, it returns positive
number (difference of character value). If first string is less than second string
lexicographically, it returns negative number and if first string is lexicographically
equal to second string, it returns 0.
Syntax:- public int compareTo(String anotherString) ,
if s1 > s2, it returns positive number  if s1 < s2, it returns negative number  
if s1 == s2, it returns 0  
class StrCompare
{
public static void main(String args[]){
String s1="Sreenidhi"; OUTPUT:-
String s2="Inforamtion"; C:\praveen>java StrCompare
String s3="JAVA"; 10
String s4="Class"; -10
System.out.println(s1.compareTo(s2)); 0
System.out.println(s2.compareTo(s1));
System.out.println(s1.compareTo(s1));

}} G.Praveen ITDept-SNIST 112


Java StringBuffer class:- Java StringBuffer class is used to created mutable
(modifiable) string. The StringBuffer class in java is same as String class except it
is mutable i.e. it can be changed.
Important Constructors of StringBuffer class
StringBuffer(): creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str): creates a string buffer with the specified string.
StringBuffer(int capacity): creates an empty string buffer with the specified
capacity as length.
class Strb{
public static void main(String args[]){
String s1=new String ("JAVA");
StringBuffer s2=new
StringBuffer("JAVA");
System.out.println(s1.length()); OUTPUT:-
System.out.println(s2.length()); C:\praveen>java Strb
//System.out.println(s1.capacity()); 4
System.out.println(s2.capacity()); 4
} } 20

G.Praveen ITDept-SNIST 113


Important methods of StringBuffer class
1.Public 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 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 StringBuffer replace(int startIndex, int endIndex, String str): is used to replace
the string from specified startIndex and endIndex.
4. Public StringBuffer delete(int startIndex, int endIndex): is used to delete the string from
specified startIndex and endIndex.
5. Public 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.

G.Praveen ITDept-SNIST 114


StringTokenizer in Java:- the java.util.StringTokenizer class allows you to
break a string into tokens. It is simple way to break string.
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,
String delim, boolean delimeter and returnValue. If return value is true,
returnValue) delimiter characters are considered to be tokens. If it
is false, delimiter characters serve to separate
tokens.

G.Praveen ITDept-SNIST 115


Methods of StringTokenizer class:-
The 6 useful methods of StringTokenizer class are as follows:

Public method Description


boolean hasMoreTokens() checks if there is more tokens available.
String nextToken() returns the next token from the StringTokenizer
object.
String nextToken(String returns the next token based on the delimeter.
delim)
boolean hasMoreElements() same as hasMoreTokens() method.
Object nextElement() same as nextToken() but its return type is Object.
int countTokens() returns the total number of tokens.

G.Praveen ITDept-SNIST 116


import java.util.StringTokenizer;
public class Strto1{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is JAVA"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
} }
OUTPUT:-
C:\praveen>javac Strto1.java
C:\praveen>java Strto1
my
name
is
JAVA

G.Praveen ITDept-SNIST 117


Difference between String and StringBuffer
There are many differences between String and StringBuffer. A list of differences
between String and StringBuffer are given below:

No. String StringBuffer


1) String class is immutable. StringBuffer class is mutable.

2) String is slow and consumes more memory when StringBuffer is fast and
you concat too many strings because every time it consumes less memory when
creates new instance. you cancat strings.

3) String class overrides the equals() method of StringBuffer class doesn't


Object class. So you can compare the contents of override the equals() method
two strings by equals() method. of Object class.

G.Praveen ITDept-SNIST 118

You might also like