Module 1
Module 1
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.
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) 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
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are
used for creating mobile applications.
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
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.
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).
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
Page 4
Java Version History
There are many java versions that has been released.
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++).
Object-oriented
Object-oriented means we organize our software as a combination of different
types of objects that incorporates both data and behaviour.
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.
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.
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.
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Output:Hello Java
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:
Page
12
approach to set path.
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.
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.
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
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
Page
17
write in command prompt: set path=copiedpath
For Example:
Page
18
2)Setting Permanent Path of JDK in Windows:
For setting the permanent path of JDK, you need to follow these steps:
For Example:
1)Go to MyComputer properties
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.
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).
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.
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).
Loads code
Verifies code
Executes code
Provides runtime environment
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting 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.
7) Execution Engine:
It contains:
1) A virtual processor
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.
class A{
void method(){
int n=90;//local variable
}
}//end of class
Page
34
Data Type Default Value Default size
Byte 0 1 byte
short 0 2 byte
Int 0 4 byte
Long 0L 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.
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.
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
multiplicative * / %
additive + -
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
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.
Page
38
for(i=1;i<=n;i++)
{
f2=f0+f1;
f0=f1;
f1=f2;
f2=f0;
System.out.println(f2);
}
}
}
}
}
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");
}
}
System.out.println("a= "+a);
System.out.println("b= "+b);
}
}
Page
40
6) Program of factorial number by recursion
class FactRecursion{
return n*=fact(n-1);
}
int f=fact(5);
System.out.println(f);
}
}
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
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.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof
etc.
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.
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.
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
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
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 :
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.
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
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.
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.
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
By new keyword
By newInstance() method
By clone() method
By factory method etc.
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. 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
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?
In java, Methood Overloading is not possible by changing the return type of the
method.
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
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
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:
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
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
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.
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
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
Page
57
Constructor in Java
Constructor is a special type of method that is used to initialize the object.
Types of constructors
Page
58
1) Default Constructor
A constructor that has no parameter is known as default constructor.
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
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.
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.
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.
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
Constructor Method
Constructor must not have return type. Method must have return type.
Constructor name must be same as the class Method name may or may not
name. be same as class name.
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
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
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.
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).
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.
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
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
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
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
3)static block
Is used to initialize the static data member.
It is executed before main method at the time of classloading.
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.
Suggestion: If you are beginner to java, lookup only two usage of this keyword.
Page
70
resolves the problem of ambiguity.
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.
Page
71
15. s2.display();
16.}
17.}
Output111 Karan
222 Aryan
Page
72
15.}
16.}
Output:111 Karan
222 Aryan
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
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
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
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.
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.
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. 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
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).
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
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.
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
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.
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
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:
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.
CharSequence Interface
Page
85
We will discuss immutable string later. Let's first understand what String in
Java is and how to create the String object.
1. By string literal
2. By new keyword
1) String Literal
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.
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
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).
Page
87
StringExample.java
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.
Page
88
endIndex) begin index and end index.
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.
Once String object is created its data or state can't be changed but a new
String object is created.
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".
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:
2. Thread Safe:
3. Security:
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.
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.
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:
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.
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
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
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.
Substring in Java
Page
96
A part of string is called substring. In other words, substring is a subset of another
string.
You can get substring from the given String object by one of the two methods:
In case of string:
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
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.
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.
Page
98
string object.
First seven methods have already been discussed. Now let’s take the example of
other methods:
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
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.
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.
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.
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. }
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. }
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. }
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. }
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.}
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.
Page
105
11.public String substring(int beginIndex, int endIndex): is used to
return the substring 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.append("Java");//now original string is changed
6.
7. System.out.println(sb);//prints Hello Java
8. }
9. }
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. }
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. }
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. }
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.}
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.}
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 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.
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.
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:
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.
Constructor Description
Page
111
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
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
Page
112
Output:Next token is : my
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.
Page
113
non-static nested classes are also known as inner classes.
Nested class
Member inner class
Annonymous inner class
Local Inner class
static nested class
Nested interface
Page
114
Invocation of Member Inner class
1. From within the class
2. From outside the 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
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. }
Page
116
12. Outer obj=new Outer();
13. Outer.Inner in=obj.new Inner();
14. in.msg();
15. }
16.}
Output:data is 30
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.}
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.
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.}
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
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.
Page
122