Download as pdf or txt
Download as pdf or txt
You are on page 1of 184

1

2Core Java

Introduction to Java & OOP’s concepts and their implementation in java


Java is an object oriented, internet programming language.
Its main features are:-
 Platform Independence.
 Security.

OOP’s
It is a programming model that simplifies software development and maintenance by providing certain
rules which are followed by the designer at the time of designing the software and by the developers at
the time of developing and maintaining the software.
The major advantage of this model is that we have habituated this model in our day to day life.

Basic concepts of OOP’s


i. Object
Classification
i. An object is a discrete (distinct/unique/different) en
ii. Generalization & Inheritance
iii. Polymorphism
iv. Data Encapsulation

Object tity that has well-defined attributes and behavior. It can be a physical thing as well as an abstract
concept.

Classification
Objects with common attributes, common behavior and having common relationship with other objects
are grouped into logical units called classes. This process is called classification.
Classes are used to manage objects.

Generalization & Inheritance


Through generalization we pick up common attributes and behavior of class. In this way we manage the
class by using it.
Generalization is the process of abstraction. Generalization is implemented with the help of inheritance

Polymorphism
It is a natural phenomenon which states that in real life one thing can exists in different forms. E.g. -
Water can be in three forms.

Data Encapsulation (To protect something)


It is a process by which we can encapsulate the data and this way we are protecting the data.
2

Internet Programming
 Internet Programming is the facility of developing such programs which are stored on the web server
and are sent to the client machine as part of the response to be executed within client‟s browser.
 Internet Programming adds interactivity to the web pages.


Evolutionary Revolutionary
To create something new To create purely new thing
(better or advanced) without modifying any
modifying the existing existing thing.
thing.
3
4

Compilation is of 2 types:-
1. OS specific compilation.
2. Architecture specific compilation.

 Processor has its own instruction set.


 Compiler‟s job is to convert one instruction into another.
5


 exe, pdf, jpeg etc are formats.
 And .exe, .pdf, .jpeg are extension.
6

JVM Specification
7

 A language is platform independent if it does not have any dependency on the operating system.
Usually dependency on the O/S is created:-
 At the time of development by invoking O/S library functions from the application,
 At the time of compilation by following O/S specific format in compiled code, and
 At the time of execution by using the O/S for launching the application.

That is, a Language is platform independent if:-


 It is compiled in a platform neutral manner.
 Language provides its own runtime environment for the execution of its application.
 Language provides a comprehensive library for the application developers to develop all types of
application without using the O/S concern.
8

Due to security.

Figure 1 is compiler-based program which directly calls O/S functions during execution.

Figure 2 is interpreter-based program which is executed by JRE. Java application has no direct connectivity with
O/S.
JRE checks whether the application is violating any rules already mentioned in JRE or not. Thus it is a
secured application than any other language‟s application.

 SUN, IBM and Oracle did some Research & Development on JIT regarding performance tuning i.e. to increase the
performance while interpreting the byte code.

See the figure below to understand this concept.


While the performance of interpreted bytecodes is
usually more than adequate, there are situations where
High Performance higher performance is required. The bytecodes can be
translated on the fly (at run time) into machine code for
the particular CPU the application is running on.

If we use an interpreter to execute the bytecodes,


“high performance” is not the term that we would
use. However, on many platforms, there is also
another form of compilation, the justin-time (JIT)
compilers. These work by compiling the bytecodes
into native code once, caching the results, and then
calling them again if needed. This approach
speeds up commonly used code tremendously
since one has to do the interpretation only once.
Although still slightly slower than a true native
code compiler, a just-in-time compiler can give us
a 10- or even 20-fold speedup for some programs
and will almost always be significantly faster than
the Java interpreter. This technology is being
improved continuously and may eventually yield
results that cannot be matched by traditional
compilation systems. For example, a justin-time
compiler can monitor which code is executed
frequently and optimize just that code for speed.
9

Syntax of defining a class –

class Identifier
{
Members definition
}

 NAMING CONVENTIONS OF JAVA

1. First letter of each word of a class name is capitalized.


Example
String
StringBuffer
ArrayIndexOutOfBoundException
etc.
2. In case of methods first letter of each word except the first word is capitalized.
Example
printf()
getPriority()
getKeyMethodMap()
etc.

 Functions (in C or C++) represents an operation which can be independent whereas methods represents
behavior which cannot be independent.
Functions (Task) Methods (Behaviour)
deposit( ) a.deposit(5000);
b.deposit(7000);
What is happening What is happening
Way of doing things Who is doing.

Question : Why in Java‟s main method return type void is used?

Figure 1 is compiler-based program which directly


calls O/S functions during execution. So, here O/S
returns some integer value to acknowledge that
whether the application run successfully or not.

Figure 2 is interpreter-based program which is


executed by JRE. Java application has no direct
connectivity with O/S. It runs on JRE.
10

It is JRE who confirms that all byte codes are valid and do not violate Java‟s security restrictions. Any type of rule
violation led to error(Compile time or runtime) by JRE.
Since JRE is boss of everything and itself capable to handle each type of error, it doesn‟t expect anything to
come back from main(), so we use void in main() method.
11

static KEYWORD

In a class we can have 2 types of members.


i. Instance members – represents attributes and behavior of individual objects.
ii. Class members – represents attributes and behavior of the whole class.

To understand where we need to use static, see the diagram below-


12

 By default all the members of a class are instance members. In order to associate a member of a class static
keyword is used.
 static denotes execution of whole class.

Syntax of compiling –
javac NameOfSourceFile

example -
13

Question : Why command-line arguments?

c:\>java Adder 10 20

Command line argument


System – It is a pre-defined class in java.lang package

Result is : 30 out - it is a static variable inside System class of type


PrintStream(class reference variable) (i.e.) static
PrintStream out;
Explanation of: and PrintStream is a predefined class in java.io package.
Since it is static that’s why we are calling
System.out
[ System.out.println(); ] So, System.out means we are getting the reference to the object
of type PrintStream
class PrintStream
println()– It is the method in PrintStream class for Standard
{ output stream.
public void print(String s) So to access println method , we need PrintStream object
{ which we are getting through System.out.
So finally its System.out.println---- to produce standard output
-----------
Stream.
-----------
-----------
}

public void println(String s)


{
-----------
-----------
-----------
}
-------------
-------------
}

class System
{
public PrintStream out;
public static PrintStream out;
-------------
-------------
-------------
}

JVM, JRE & JDK


14

SET OF SPECIFICATIONS ISSUED BY SUN MICROSYSTEMS THAT COVERS


 An instructions set(Java Assembly).
 Format of class file.
 Class loading mechanism.
 Memory Management etc.

JVM

JDK

 In Java, classes are packaged and distributed in jar format.


Jar - Java Archive
 Sun Microsystems provides classes of core java library through a jar file named “rt.jar.
 C:\NewJava>jar
jar -tf rt.jar
jar -tf rt.jar> a.txt

To compress
jar -crf a.jar *
jar -tf a.jar (to see)
jar -xf a.jar (to extract)
15

The above program in modified form:


PROGRAM first2.java

public class First2


{
public static void main()
{
System.out.println("It is overloaded main.....");
}

public static void main(String args[])


{
System.out.println("Invoked by JRE, invoking overloaded main......");
main();
}
}

OUTPUT –
16

Now we will see how to execute a program without main().


PROGRAM First3.java
public class First3
{
static
{
System.out.println("It is executing without main()......");
System.exit(0);
} }

Output –

PROGRAM :

public class First


{
public static void main()
{
System.out.println("It is overloaded main.....");
}

static
{
main();
}

public static void main(String args[])


{
System.out.println("It is invoked by JRE");
}
}

Output –
17

Signature of Method –
modifier returnType methodName(Argument list)
{
-------------
-------------
-------------
}
Question: What is datatype?
Answer – Datatype is a set of values that has an associated set of operations and a memory representation for its
values.

S. NO. DATA SIGN IN DEFAULT VALUES


TYPE BYTES Integer
1. char 2 \0 (Null data
Character)
2. byte 1 0
3. short 2 0
4. int 4 0
5. long 8 0
Floating Point
6. float 4 0
7. Numbers
double 8 0
8. boolean Not false
defined

class Test1
{
public static void main(String args[])
{
int a;
System.out.println("a = “ + a); // Compilation error
}
}

Output -

Explanation-
 Concept of default value is not applied on local variables of a method i.e. local variables of a method need to be
explicitly assigned.

 Default value will be applied in class variables.


18

Like for example the above program can be rewritten as-

PROGRAM Test1.java

class Test1
{
static int a, b;

public static void main(String args[])


{
System.out.println("a & b is : " + a + " " + b); // No compilation error
}
}

OUTPUT –

PROGRAM Test2.java
class Test2
{
public static void main(String args[])
{
float f = 12.45;
System.out.println("Value of f = " + f);
}
}
What will be the output –
A. Value of f = 12.45
B. Value of f = 12
C. Value of f = 12.00000
D. Compilation Error
Now let’s see the output of the above program.
19

Explanation –
In Java, floating point constants are of double type by default. The value of higher type cannot be directly assigned
to a lower type. In such a case type conversion is required.

Type Casting / Type Conversion


Converting the values of one type to another for the evaluation of an expression is called type casting or type
conversion.

Type casting is of two types:-

1) Upcasting – Conversion of lower types to upper types is called upcasting. Upcasting is implicitly performed.
Upcasting is performed according to the following graph:-

byte

char short

Int Float

Long double

Auto Conversion Graph

Represents conversion without loss of precision.


- - - - - - - - - - - - Represents conversion with possible loss of precision.

Explanation -
a. Let n be an integer and n = 2n then to store n in memory in integer representation k bits are required.

For e.g
32768 = 215
0 111111111111111

15 bits are required to store 32768.

b. In floating point representation number is not stored rather its exponent is stored.
i.e
32768 = 215
Then only 15 need to be stored.
20

n=2k and k = 2l where l<k then to store n only l bits are required.

2) Downcasting – Conversion of higher types to lower type is called downcasting. Downcasting need to be explicitly
performed.

Syntax –
(target type) expression;

Example-

float f = 12.45;

float f = (float)12.45;
By this statement compiler
OR will understand that you are
treating this number as a
float f = 12.45f; floating number.

PROGRAM – Rectangle.java

public class Rectangle


{
private int l, b;

public void Rectangle(int x, int y)


{
l = x;
b = y;
}

public void display()


{
System.out.println("Length = " + l);
System.out.println("Breadth = " + b);
}

public int area()


{
return l * b;
}

public void setDimension(int x, int y)


{
l = x;
b = y;
21

}
}
Syntax of creating object of a class-

className ReferenceVariable = new className();

OR
className ReferenceVariable;

ReferenceVariable = new className();

Reference Variable – is an implicit pointer that contains the reference of a class object. In Java, objects are
dynamically created. Hence, they don‟t have names. They are referred using the name of their reference variable.

In C++ :-
Rectangle r;

Traditionally in languages when we write statement


int a=5, b=6, c=10;
a table is created during compilation.
Variable Type Address Value Scope
Name
a int 0 + 1000 5 main
B int 2 + 1000 6 main
c int 4 + 1000 10 main

+ 1000 - this will be added later during runtime.

int * p;

Now,
22

 Address & Reference denotes two different things.


o Address represents actual memory location whereas Reference represents a mechanism of finding out objects.

 Different JRE provides different implementations of references.


o In Microsft JRE, References are implemented as pointers that is they actually holds the address of object.

o In Sun Microsystem JRE, Reference Variables are implemented as pointer to pointer.

In this implementation, Reference and Address are different.


23

Now we will write a program RectTest.java to test the program Rectangle.java written above.

public class RectTest


{
public static void main(String[] args)
{
Rectangle r = new Rectangle();
r.l = 5;
r.b = 7;
r.setDimension(5, 4);
System.out.println("Dimension of rectangle r ");
r.display();
System.out.println("Area of r = " + r.area());
}
}

Output –

Since variables l and b are declared private so we cannot access it from outside.
24

Now the same program RectTest.java again.

PROGRAM RectTest.java

public class RectTest


{
public static void main(String[] args)
{
Rectangle r = new Rectangle();
//r.l = 5; // Invalid statement
//r.b = 7; // Invalid statement
r.setDimension(5, 4);
System.out.println("Dimension of rectangle r ");
r.display();
System.out.println("Area of r = " + r.area());
}
}

OUTPUT –

 CONSTRUCTOR
 It is special member of a class that has following characteristics :
o It has the same name as of its class.
o It does not have an explicit return type.
o It is implicitly invoked just after an object is created.
o It is used to initialize data members of objects.

Rectangle r = new Rectangle();

1. Rectangle r; //Reference Variable created


2. r = new Rectangle(); //memory allocation for object
3. r.Rectangle(5, 4); //Constructor is invoked

Let‟s see it again :


25

If a class doesn‟t contain any constructor then default constructor is provided by the compiler at the time of
compilation but if a class contains any parameterized constructor and there is an object of the class which requires
default constructor for its initialization then default constructor need to be defined in the class. In this case, it won‟t
be provided by the compiler.

 javap – to know what is kept in .class file

o Question: Why compiler provides a default constructor if a class doesn’t contain any constructor and why it doesn’t provide
the default constructor when a class contains any parameterized constructor?
o Solution
 Overloading – If a class contains multiple implementations of a method or constructor then method or
constructor is said to be overloaded.
 Implementations of overloaded method or constructor are differentiated either by varying the number of
arguments or by varying their type of arguments.
 Overloading is one of the means of implementing polymorphism.
o Let‟s see the advantage of overloading –

PROGRAM Test.java
public class Test
{
public static void main(String[] args)
{
int a = 5;
boolean b = false;
char c = 'A';
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
26

OUTPUT -

class A
{
int a;

public A(int x)
{
a=x;
}

{
System.out.println("It is unusual....");
}

public void display( )


{
System.out.println("a=" +a);
}

public static void main(String[ ] args)


{
A p = new A(10);
A q = new A(20);
p.display();
q.display();
}

Anonymous Block: Is a convenience provided to java developers to define statements common to all
constructors of a class. At the time of compilation statements of anonymous block are moved at the
beginning of each constructor by the compiler.
27

OR
28

The same program we can also write like this:

At the time of compilation,


compiler shall move
This is Anonymous Block. statements of Anonymous
Block at the beginning of
each constructor.

Output-
29

class AB
{

{
----------
----------
----------
----------
}

public AB()
{
----------
----------
----------
----------




}

public AB(int x)
{
----------
----------
----------
----------




}

public AB(int x, int y)


{
----------
----------
----------
----------




}
………
}
30

static Keyword
Is used to define class members.
In a class we can have following 3 types of class members:-
1. STATIC DATA MEMBERS
Represents class attributes. A single copy of static data members is created when the class is loaded.
This copy can be shared by all the objects of the class.
For example -
class A
{
int a, b;
static int c;
-------
-------
}

When we create objects of this class in some other class what happens is explained in the given adjoining fig1.

Fig1.
For the execution of a Java Application, memory is divided into three parts called
 Stack - LOCAL VARIABLES of methods are stored in STACK.
 Heap - OBJECTS are created in the HEAP.
 Class Area - STATIC DATA MEMBERS are saved in CLASS AREA.

2. STATIC INITIALIZE BLOCK


3. STATIC METHODS.

class A
{
int a, b;
static int c;
----------
----------
public static void main(String[] args)
{
A x = new A();
A y = new A();
-------------
-------------
}
}
31

Each object of a class contains


References of class members

Memory Representation During the execution of main() method of class A.

Static Initializer Block- is used to initialize static data members of a class.


Syntax –
static
{
Statements
}

Static initialize is executed only once, just after a class is loaded.


In Java, a class can be loaded in either of the following ways:-
1. Through Explicit Introduction.
2. Through Implicit References.
In the first approach class to be loaded is explicitly introduced to the JRE.

Only a single class is loaded in an application using explicit introduction. Rest of the classes are loaded
through implicit reference.
When a reference of a class is encountered first time in an already loaded class then JRE implicitly loads
it before performing the operation represented by the class reference.
class A
{
public static void main(String[ ] args)
{
B x = new B();//Reference of B is contained in A
-------------
-------------
}
32

class B
{
-------------
-------------
}

At the time of class loading following sequence of steps is performed by JRE:-


1. Static Data Members (if defined) are created in the Class Area.
2. Static Initializer Block (if defined) is executed.
3. Reference of the class which resulted in class loading is resolved i.e. operation represented by the
reference is performed.

class A
{
static
{
System.out.println(“A is loaded.”);
}

public A()
{
System.out.println(“A is instantiated.”);
}
}

class B
{
static int b;

static
{
b=5;
System.out.println(“B is loaded.”);
}
}

class C
{
static
{
System.out.println(“C is loaded.”);
}

public static void display( )


{
System.out.println(“Display( ) of C is invoked.”);
}
}

class D
{
static
{
33

System.out.println(“D is loaded.”);
}

public static void main(String args[])


{
System.out.println(“Instantiating A………”);
A x = new A();
System.out.println(“Referencing static data member b of B……”);
System.out.println(“b of B is : “ + B.b);
System.out.println(“Invoking static method of C……”);
C.display();
System.out.println(“Instantiating A again.”);
A y = new A();
}
}

-------------------------------------------------------------------------------------------------------
class E
{
static int a = 5;

public static void main(String args[])


{
System.out.println(“a = “ + a);
}
}
After
compilation

class E
{
static int a;

static
{
a = 5;
}
----
----
}
-------------------------------------------------------------------------------------------------------
34

class E
{
int a = 5, b=6;

public static void main(String args[])


{
E x = new E();
System.out.println(“a = “ + x.a);
System.out.println(“b = “ + x.b);

}
}
After
compilation
class E
{
int a, b;

E( )
{
a = 5;
b = 6;
}
----
----
}
-------------------------------------------------------------------------------------------------------
class E
{
int a=5, b=6;

public E ()
{
System.out.println(“Default.”);
}

public E(int x)
{
a=x;
System.out.println(“One parameterized.”);
}

public E(int x, int y)


{
b=y;
System.out.println(“Two parameterized.”);
}

public void display()


{
System.out.println(“a = “ + a);
System.out.println(“b = “ + b);
}
35

public static void main(String args[])


{
E x = new E();
E y = new E(10);
E z = new E(40, 50);
x.display();
y.display();
z.display();
}
}

After compilation,

the compiler will do the


following for the same
program

class E
{
int a, b;

public E()
{
a=5, b=6;
System.out.println(“Default.”);
}

public E(int x)
{
a=5, b=6;
a=x;
System.out.println(“One parameterized.”);
}

public E(int x, int y)


{
a=5, b=6;
b=y;
System.out.println(“Two parameterized.”);
}

public void display()


{
System.out.println(“a = “ + a);
System.out.println(“b = “ + b);
}

public static void main(String args[])


{
36

E x = new E();
E y = new E(10);
E z = new E(40, 50);
x.display();
y.display();
z.display();
}
}

 Limitations of static methods & static block:-


o Only static data members of a class can be referred in a static block or method.
o A static block or static method can directly invoke only static methods.
o „this‟ and „super‟ keyword cannot be used in a static method or in a static block.

Program below executes without ‘main’ method –


class Test
{
static
{
System.out.println(“It is executing without main…..”);
System.exit(0);
}
}

Not only we can do this much but also we can do list of things. See the program below : -

class Test2
{
int a;

public Test2(int x)
{
a = x;
}

public void display1()


{
System.out.println("a = " + a);
}

static
{
System.out.println("Test is loaded.");
Test2 t = new Test2(5);
t.display1();
P x = new P();
System.exit(0);
}
}

class P
{
public P()
{
System.out.println("P is instantiated.");
37

static
{
System.out.println("P is loaded.");
}
}
OUTPUT -

Now, as we saw that we can do almost everything without having main( ), then why we need main( )
in our program?
In the sessions ahead, we will get the answer.

Passing arguments to methods-


In Java, primitive type arguments are passed to methods by value i.e. their copy is created in the
invoked method.
Objects are passed by references i.e. in case of objects, copy of their reference variables is created in the
invoked method.

Now the program below is written to swap the values.


Observe it carefully to understand how this issue is being resolved.

public class Swapper


{
public static void swap(int x, int y)
{
int z;
z = x;
x = y;
y = z;
}
}

public class SwapperTest


{
public static void main(String[ ] args)
{
int a =5, b = 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
38

Swapper.swap(a, b);
System.out.println("After swap");
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
The output is -

Our purpose is not solved. Let‟s see the reason for this.
See the fig2. below

Now, let‟s find out solution to this problem.

public class MyNumber


{
int value;
public MyNumber(int x)
{
value = x;
}
}

public class Swapper


{
public static void swap(MyNumber x, MyNumber y)
{
39

int z;
z = x.value;
x.value = y.value;
y.value = z;
}
}

public class SwapperTest


{
public static void main(String[ ] args)
{
MyNumber a = new MyNumber(5);
MyNumber b = new MyNumber(6);
System.out.println("a = " + a.value);
System.out.println("b = " + b.value);

Swapper.swap(a, b);
System.out.println("After swap");
System.out.println("a = " + a.value);
System.out.println("b = " + b.value);
}
}

Output –

Now the problem is fixed as you can see the value is swapped. We handled it by passing value by
reference.

Let see the explanation diagrammatically. (Fig. - 3)


40

Question. Define a class named Rational that contains 2 data members to store the value of numerator
and denominator of a rational number, default & two parameterized constructors, a display ( ) method
that displays the value of a rational object in form and add ( ) methods which are referenced by the
following class.

Answer –
package StaticConceptualPrograms;

public class Rational


{
int numerator, denominator;

public Rational() { }

public Rational(int x, int y)


{
numerator = x;
denominator = y;
}

void display()
{
System.out.println(numerator+"/"+denominator);
}

Rational add(Rational y)
{
numerator = y.denominator*this.numerator + this.denominator * y.numerator;

denominator = y.denominator*this.denominator;

return this;
}
41

Rational add(Rational x, Rational y)


{
numerator = y.denominator*x.numerator + x.denominator * y.numerator;

denominator = y.denominator*x.denominator;

return this;
}

/*
static Rational add(Rational x, Rational y)
{

}
*/
}

package StaticConceptualPrograms;

public class RationalTest


{
public static void main(String[] args)
{
Rational a = new Rational(2, 3);
Rational b = new Rational(4, 5);
System.out.print("Rational a is : ");
a.display();
System.out.println("");

System.out.print("Rational b is : ");
b.display();
System.out.println("");

Rational c = a.add(b);
System.out.print("Sum of a & b : ");
c.display();
System.out.println("");

Rational r = new Rational(6, 5);


Rational s = new Rational(4, 3);
Rational t = new Rational();

t.add(r, s);
System.out.print("Rational r is : ");
r.display();
System.out.println("");

System.out.print("Rational s is : ");
s.display();
System.out.println("");

System.out.print("Rational r & s is : ");


t.display();
System.out.println("");
42

Rational z;
System.out.print("Sum of a, b, r & s is : ");
//z = Rational.add(c, t);
//z.display();
}
}

Output -

public class Rational


{
int p, q;

public Rational() {}

public Rational(int x, int y)


{
p = x;
q = y;
}

public void display()


{
System.out.println(p+"/"+q);
}

Rational add(Rational r)
{
Rational s = new Rational();
s.p = p * r.q + q * r.p;
s.q = q * r.q;
return s;
}

public void add(Rational a, Rational b)


{
43

p = a.p * b.q + a.q * b.q;


q = a.q * b.q;
}

public static Rational add(Rational a, Rational b)


{
Rational c = new Rational();
c.p = a.p * b.q + a.q * b.q;
c.q = a.q * b.q;
return c;
}
}

public class RationalTest


{
public static void main(String[] args)
{
Rational a = new Rational(2, 3);
Rational b = new Rational(4, 5);
System.out.print("Rational a is : ");
a.display();
System.out.println("");

System.out.print("Rational b is : ");
b.display();
System.out.println("");

Rational c = a.add(b);
System.out.print("Sum of a & b : ");
c.display();
System.out.println("");

Rational r = new Rational(6, 5);


Rational s = new Rational(4, 3);
Rational t = new Rational();

t.add(r, s);
System.out.print("Rational r is : ");
r.display();
System.out.println("");

System.out.print("Rational s is : ");
s.display();
System.out.println("");

System.out.print("Rational r & s is : ");


t.display();
System.out.println("");

Rational z;
System.out.print("Sum of a, b, r & s is : ");
z = Rational.add(c, t);
z.display();
}
}

To understand the logic used inside the different methods of Rational class, please see the diagrams below.
44

The dotted line here indicates the


add( ) method’s scope.

Figure (20.a) to understand public Rational add(Rational r) method


45

The dotted line here


indicates the add( ) method’s
scope.
46

The dotted line here indicates


the add( ) method’s scope.

Program -
class Test1
{
int a, b;

public Test1(int a, int b)


{
a=a;
b=b;
}
public static void main(String[] args)
{
Test1 t = new Test1(5, 6);
t.display();
}

public void display()


{
System.out.println("a = " + a);
47

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


}
}

Output -

this keyword-
In Java, each non-static method & constructor has an implicit parameter named this which holds the reference of
the invoking object.
Each non static method and
constructor has this as its first
Program Test1 as understood by JRE is rewritten below:-
class Test1
parameter.
{
int a, b;
Each non static method and
public Test1(Test1 this, int a, int b) constructor has this as its
{
a=a; first parameter.
b=b;
}

public void display(Test1 this)


{
System.out.println("a = " + this.a);
System.out.println("b = " + this.b);
}
48

public static void main(String[] args)


{
Test1 t = new Test1(5, 6);
t.display();
}
}

As understood by JRE
t.display( ); display(t);

The dotted line here indicates the


constructors’ scope.
49

1. First usage of ‘this’:-


 ‘this’ keyword is used to identify data members of invoking objects in a method or constructor. In case, there is
a conflict between object data member and local variables we use –
Syntax:-

this.<memberName>

Example Program -
class Test1
{
int a, b;

public Test1(int a, int b)


{
this.a=a;
this.b=b;
}
public void display()
{
System.out.println("a = " + this.a);
System.out.println("b = " + this.b);
}

public static void main(String[] args)


{
Test1 t = new Test1(5, 6);
t.display();
}
}

Output -

2. Second usage of ‘this’:-


 ‘this’ keyword facilitate chaining of constructors of a class.

o Constructor Chaining is the facility in which one constructor of a class invokes another constructor of the
same class.

Syntax:-
this(arguments if any)
50

NOTE: When ‘this‟ keyword is used to invokes a constructor from another constructor, it
must be the first statement in the invoking constructor.

Example Program -

public class ThisTestInMethod


{
int p, q;

public ThisTestInMethod()
{
this(2, 3);
System.out.println("Default");
}

public ThisTestInMethod(int x)
{
this(x, 3);
System.out.println("One Parameterized Constructor...");
}

public ThisTestInMethod(int x, int y)


{
p = x;
q = y;
System.out.println("Two Parameterized Constructor...");
}

public void display()


{
System.out.println("p = " + p);
System.out.println("q = " + q);
System.out.println("");
}

public static void main(String[] args)


{
ThisTestInMethod a = new ThisTestInMethod();
a.display();

ThisTestInMethod b = new ThisTestInMethod(10);


b.display();

ThisTestInMethod c = new ThisTestInMethod(30, 40);


c.display();
}
}

Output –
51

3. Third usage of „this‟:-


 „this‟ keyword facilitate method chaining.
o Method Chaining is the facility of invoking multiple methods on an object in a single statement.

Program (Swapper) to understand the 3rd usage of „this‟. This is a Swapper program which has been written
without using „this‟ keyword.
Then we will see how efficiently we can write the same program using „this‟ keyword.

1. public class Swapper


2. {
3. int a, b;
4.
5. public Swapper(int x, int y)
6. {
7. a = x;
8. b = y;
9. }
10.
11. public void swap()
12. {
13. int c = a;
14. a = b;
15. b = c;
16. }
17.
18. public void display()
19. {
20. System.out.println("a = " + a);
21. System.out.println("b = " + b);
52

22. }
23.
24. public static void main(String[] args)
25. {
26. Swapper x = new Swapper(5, 6);
27. x.display();
28. x.swap();
29. x.display();
30. }
31. }

Output –
53

Now, in the same program (Swapper), we will do some modifications to understand the 3rd usage of „this‟
keyword.
The same above Swapper program which has been written using „this‟ keyword.

public class Swapper


{
int a, b;

public Swapper(int x, int y) //Constructor implicitly return ‘this’


{
a = x;
b = y;
}

public Swapper swap()


{ The changes being made in these places
int c = a; indicated here.
a = b;
b = c;
return this;
}
public Swapper display()
{
System.out.println("a = " + a);
System.out.println("b = " + b);
return this;
}
public static void main(String[] args)
{
Swapper x = new Swapper(5, 6);
x.display().swap().display(); // Method calls are chained.
}
}

Output -
54

Now, in the same program we will again do some more modifications in the main method. Observe it carefully.

public class Swapper


{
int a, b;

public Swapper(int x, int y) //Constructor implicitly return ‘this’


{
a = x;
b = y;
}

public Swapper swap()


{ The changes being made again only in main
int c = a; method.
a = b;
b = c;
return this;
}
public Swapper display()
{
System.out.println("a = " + a);
System.out.println("b = " + b);
return this;
}
public static void main(String[] args)
{
new Swapper(5, 6).display().swap().display(); // Method calls
are chained.
}
}

Output -

NOTE : All constructors return ‘this’.

Association : - When two classes are related in some way they are said to be associated. Relation between
classes of two types:-
55

i. Is – A Relation
ii. Has – A Relation

Is – A Relation between classes is implemented with the help of inheritance.


Question: What is Inheritance?
Inheritance is the process of extending the functionality of a class by defining a new class which inherits all the
features of the existing class and adds some features of its own. Inheritance is a means of implementing
generalization.
Question: Why Inheritance is used?
Inheritance is used for code Reusability (5%) and runtime polymorphism (95%).
extends - In java ‘extends’ keyword is used to inherit the features of one class into another.
Syntax:-
this(arguments if any)

Syntax :-
class Identifier extends BaseClassName
{
Additional methods
Or
Additional dataMembers & methods
}

Program to understand the working of Inheritance: -


public class Common
{
int l, b;

public Common(int x, int y)


{
l = x;
b = y;
}

public void display()


{
System.out.println("Length = " + l);
System.out.println("Breadth= " + b);
}
}

public class Rect extends Common


{
56

public Rect(int x, int y)


{
super(x, y);
}

public int area()


{
return l * b;
}
}

public class Cuboid extends Common


{
int h;

public Cuboid(int x, int y, int z)


{
super(x, y);
h = z;
}

public void display()


{
super.display();
System.out.println("Height = " + h);
}

public int volume()


{
return l * b * h;
}
}

public class InheritanceTest


{
public static void main(String[] args)
{
Rect r = new Rect(5, 4);
Cuboid c = new Cuboid(6, 5, 8);
System.out.println("Dimension of rectangle : ");
r.display();

System.out.println("Dimension of cuboid : ");


c.display();

System.out.println("Area of Rectangle " + r.area());


System.out.println("Volume of Cuboid " + c.volume());
}

Output –
57

NOTE :
1. Constructor of a class is never inherited in another class.
2. Inheritance is always unidirectional i.e. child class knows everything of parent class but
the reverse is not true.

Usage of ‘super’ keyword


1. ‘super’ keyword is used to chain superclass and subclass constructors, i.e. to invoke a superclass constructor
form a subclass constructor.

Syntax –
super(Argument if any);

NOTE: ‘super’ when used in subclass constructor to invoke superclass constructor than it
must be the first statement.

2. ‘super’ keyword is used to invoke a superclass method from a subclass method.

Syntax –
super.MethodName( );

3. ‘super’ keyword is used to refer superclass data members in a subclass, in case there is a name conflict between
superclass and subclass data members.
58

Syntax –
super.MemberName;

Method Overriding: -
If a class defines a method of same signature as a method of its superclass then the class is said to be overriding
method of the superclass.
Method overriding is one of the means of implementing polymorphism.

HOMEWORK –
Assignment 1. - What is runtime polymorphism in Java?
Polymorphism is the capability of an action or method to do different things based on the object that it
is acting upon. In other words, polymorphism allows you define one interface and have multiple
implementation. This is one of the basic principles of object oriented programming.
The method overriding is an example of runtime polymorphism. You can have a method in subclass
overrides the method in its super classes with the same name and signature. Java virtual machine
determines the proper method to call at the runtime, not at the compile time.
Let's take a look at the following example:

PROGRAM RuntimePolymorphismDemo.java

class Animal {
void whoAmI() {
System.out.println("I am a generic Animal.");
}
}
class Dog extends Animal {
void whoAmI() {
System.out.println("I am a Dog.");
}
}
class Cow extends Animal {
void whoAmI() {
System.out.println("I am a Cow.");
}
}
class Snake extends Animal {
void whoAmI() {
System.out.println("I am a Snake.");
}
}

class RuntimePolymorphismDemo {
public static void main(String[] args) {
Animal ref1 = new Animal();
Animal ref2 = new Dog();
Animal ref3 = new Cow();
Animal ref4 = new Snake();
ref1.whoAmI();
ref2.whoAmI();
ref3.whoAmI();
ref4.whoAmI();
}
}

THE OUTPUT IS-


59

In the example, there are four variables of type Animal (e.g., ref1, ref2, ref3, and ref4). Only
ref1 refers to an instance of Animal class, all others refer to an instance of the subclasses of Animal. From
the output results, we can confirm that version of a method is invoked based on the actually object's
type.
In Java, a variable declared type of class A can hold a reference to an object of class A or an object
belonging to any subclasses of class A. The program is able to resolve the correct method related to the
subclass object at runtime. This is called the runtime polymorphism in Java. This provides the ability to
override functionality already available in the class hierarchy tree. At runtime, which version of the
method will be invoked is based on the type of actual object stored in that reference variable and not on
the type of the reference variable.
60

Date : 26.06.10

In Java, each class is direct or indirect subclass of Object. Relation between Object class and other classes
is implicitly created by the compiler at the time of compilation.
Whenever object of a class is created, Object class must be given a chance to initialize its part of object
state.
Invocation of object constructor is determined by the compiler by performing following steps at the time of
compilation-
1. If a class doesn‟t define any constructor then compiler defines a constructor & writes super to it.
2. If a class contains constructor compiler simply adds super keyword to them.

See the example below -


class A
{
public A()
{
System.out.println("In A.");
}
}

class B extends A
{
public B()
{
System.out.println("In B default.");
}

public B(int x)
{
System.out.println("In B.");
}

}
61

class C extends B
{
public C()
{
System.out.println("In C.");
}
}

class Test extends Object


{
public static void main(String[] args)
{
A x = new A();
B y = new B(5);
C z = new C();
}
}

Output -

NOTE : If a class contains only parenthesized constructors then its subclass must
explicitly invoke then using ‘super’.

POLYMORPHISM DYNAMIC BINDING AND RUNTIME


Resolving a method call i.e. finding out a method definition to be executed for a method call is called
binding.
If a method call is resolved at compilation time it is called Static Binding or Early Binding.
If a method call is resolved at the time of execution it is called Late Binding or Dynamic Binding.
62

In Java, method calls are resolved according to the following rules:-


1. Static methods are statically binded.
2. Non-static methods are dynamically binded except following 3 cases:-
i. Private Non-static methods are statically binded.
ii. Constructors are statically binded.
iii. Methods calls made using super keywords are statically binded.

In JVM assembly there are 4 instructors which are used by JRE invoking methods.
JVM Assembly Purpose Type of Binding
1. invokestatic Used to invoke static static binding
methods
2. invokespecial Used to invoke static binding
Constructors, private non-
static methods & non-
private, non-static
methods using super
keyword.
3. invokevirtual Used to invoke non- dynamic binding
private, non-static
methods without super.
4. invokeinterface Used to invoke interface dynamic binding
methods.

CONCLUSION
 static method static binding
 Constructor / private instance method / non-private method using super static binding
 Non-private instance method dynamic binding
 To invoke interface method dynamic binding

Now the solution for the problem


63

class A
{
public void display()
{
System.out.println("In A.");
}

public static void invoke(A x)


{
x.display(); // how this call shall be resolved
}
}

class B extends A
{
public void display()
{
super.display();
System.out.println("In B.");
}
}

class C extends B
{
public static void main(String[] args)
{
A x = new A();
B y = new B();
A.invoke(x);
A.invoke(y);
}
}

OUTPUT –
64

“ BEHAVIOR ”
IS ASSOCIATED WITH

Class Object Family of


classes
having
common
trend
IS
ASSOCIATE
When a class extends another class then apart from the features of the super class subclass also inherits
D WITH
the name of its superclass i.e. reference variable of a superclass can be used to refer subclass objects.

Let there be following class hierarchy –


65

REFERENCE TYPE OBJECT TYPE


Object, A A
Object, A, B B
Object, A, B, C C
66

Date : 27.06.10
Common Behaviour – In a family of classes can be supported in the following two ways-
1. By Gift – Parent Class defines methods that are to be provided to all subclasses.
e.g. :-

2. By force – In this approach all subclasses of a family are forced which provide implementation of the
common behavior of the family.
a. abstract keyword is used in the implementation of this strategy. abstract keyword is used to define
abstract methods & classes.
b. An abstract method is a method without implementation which represents what is to be done without
specifying how it could be done.
c. If a class contains any abstract method then class is declared as “abstract”. An abstract class has
following characteristics:-
i. It cannot be instantiated.
ii. It imposes the responsibility of providing implementation of all its abstract methods on its subclasses.
iii. If any of its subclass fails to define even a single abstract method of the superclass then subclass is also
declared as “abstract”.

Q1. Problem Statement:-


Define a class name Invoker that contains a public static void method name invoke(). In this method an
object of any subclass of class A is passed as argument. You are required to invoke a method name
show() on this parameter object from the invoke().

Solution –

The problem occurs here is follows : -


67

i. class A is not defined.

Now as soon as we created a abstract class A, the error message went away.
See the figures below –

Again we need to complete our Problem Statement.


68

THE OUTPUT IS -
69

class Invoker
{
public static void invoke(A x)
{
x.show();
}
}

abstract class A
{
abstract public void show();
}

abstract class A
{
abstract public void show();
}

class B extends A
{
int a;

public B(int x)
{
a = x;
}

public void show()


{
System.out.println("a of this object is : " + a);
}
}

class C extends A
{
String name;

public C(String n)
{
name = n;
}

public void show()


{
System.out.println("It is object : " + name);
}
}
70

public class InvokerTest


{
public static void main(String[] args)
{
B b = new B(10);
C c = new C("c");
Invoker.invoke(b);
Invoker.invoke(c);
}
}

Interface : - An interface is a collection of implicit abstract methods and static final data members.
Interfaces are used to abstract the interface of the classes from their implementation.

Syntax of defining an interface:-


interface Identifier
{
static final dataMembers
implicit abstract methods
}

Or
interface Identifier
{
static final dataMembers
}
Or
interface Identifier
{
implicit abstract methods
}

Example –
interface Printable
{
void print();
}
Interfaces are implemented by classes.

Syntax of implementing an interface:-

class className implements InterfaceName


{
public definition of interface methods
addition members (if any) of the class
}

NOTE: If a class implements an interface then it has to provide public definition of all interface
methods otherwise the class is declared as abstract.
71

Example :

Class Interface
1. Degree of Classes support 0 – Interfaces support
abstraction 100% abstraction. only 100%
abstraction.
2. Type of Inheritance Classes facilitate Interfaces facilitate
implementation interface inheritance.
inheritance. In Java, In Java, multiple
multiple interface inheritance
implementation is allowed.
inheritance is not
allowed.
3. Type of classing Classes facilitate Interfaces facilitate
environment static classing dynamic classing
environment & environment across
dynamic classing multiple families.
environment only
within a family.

Type of Inheritance Purpose Anlogy(Similarity)


1. Implementation Code reusability, Represents Blood
72

Inheritance Runtime relation of real life.


polymorphism. E.g. – A is son of B.
2. Type of Inheritance  Runtime Represents Non-
polymorphism. Blood relation of real
 „implements‟ life.
keyword is used. E.g. –
B is friend of C.
C is a teacher.

Literal meaning of Interface is „medium between two things‟.

 Let there be two programmer named A and B who are defining classes One and Two respectively. A need
to refer class of B in his class. class One is simple, A would take at most 30 minutes to complete it. class
Two is complex and B would require at least 10 days to complete it.

A class can be referred in another class in the following three ways:-


1. By Name – In this approach, class is referred in another class directly by its name. This approach has
following problems:-
a. class must be known and available at the time of compiling the referencing class.
b. Reference by name created a type coupling between referencing & referenced class which results in
maintenance problem.
c. The limitation of referencing only known and available classes is called static classing environment.

2. By the name of parent:-


73

Advantage of this approach:


a. In this approach a class is referred in another class by the name of its parent or family. This approach
has following advantages :
i. Only parent class need to be known or available at the time of creating the reference.
ii. Referencing & referenced class are being coupled.
iii. Facility of referencing unknown & unavailable classes is called dynamic classing environment.
Disadvantage of this approach:
a. Disadvantage of this approach is that dynamic classing environment is supported within a family.

3. By the name of its interface:-


In this approach class is referred in another class through the interface implemented by the class.
74

 Let there be three programmers named X, Y and Z. X is defining a class named ABC that contains a(), b()
and c() methods. X wants to expose only a() method of his class to the class of Y and only b() method to
the class of Z.

Now if we make some changes here, everything will go right. See the changes we will do in the figure
below:-

Q2. Problem Statement:-


75

Define a class name Invoker that contains a public static void method name invoke(). In this method, an
object is received as argument. You are required to invoke a method named show() on the argumented
object from the invoke().

Solution -
class Invoker
{
public static void invoke(Showable o)
{
o.show();
}
}

interface Showable
{
void show();
}
76

Dated : 03.07.10

Is-a relation is of 2 types –

Has-a Relation

 Aggregation represents part and whole relation between objects. In case of aggregation part and whole may have
their independent existence.

For example Room has chairs.

 Composition represents a stronger has-a relation between objects in which existence of one object depends on
another.

For example Room has walls.

package HasAIsARelation;

class A

int a;

public A(int x)

a=x;

public void display()

{
77

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

package HasAIsARelation;

class AB

A a;

int b;

public AB(int x, int y)

a=new A(x);

b=y;

public void display()

a.display();

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

package HasAIsARelation;

class HasATest

AB x = new AB(5, 10);

x.display();
78

------------------------------------------------X-----------------------------------------------

NESTED/INNER CLASS

A class that is defined within the scope of another class is called nested or inner class.

Nested classes can be of 2 types:-

1. STATIC INNER class - A class that is defined within the scope of another class and is qualified by static keyword is
called static inner class. It has following characteristics:-
i. It can be instantiated independently, i.e. an object of outer class is not required for the instantiation
of this class.
ii. It can refer all static data members of its outer class irrespective of their scope.

NOTE: If a class is defined within the scope of another class it is referred according to the following syntax.

outerClassName.InnerClassName

See the figure below -


79

Example –
Program InnerTest.java

package InnerClassOuterClass;

class A
{
private static int a;

static
{
a=5;
System.out.println("A is loaded...");
}

// static inner class starts


public static class B
{
int b;

public B(int x)
{
b=x;
}

public void display()


{
System.out.println("a of outer class is : " + a);
System.out.println("b of this object is : " + b);
}
}
// static inner class ends.
}

class InnerTest
{
public static void main(String args[])
{
System.out.println("Initiating static inner class..");
A.B x = new A.B(10);
80

System.out.println("invoking display() method on inner


class object");
x.display();
}
}
Output –

 Explanation of above program (InnerTest.java)


81
82

After compilation contents of inner class are contained in a separate class file which is named according to the
following convention

outerClassName$InnerClassName

To facilitate availability of private static data members of outer class in inner class compiler makes following
modifications:-

A. For each private static data member of outer class which is referenced in inner class a static accessor method
is created in the outer class.
B. Reference of private static data member of outer class are replaced by call to accessor method in inner class.

2. NON-STATIC INNER class

A class that is defined within the scope of another class and is not qualified by static keyword is called NON-
STATIC INNER class.

It has following characterstics:-

a. It cannot be instantiated independently, i.e. an object of outer class is required for the instantiation of
non-static inner class.
b. It can access static as well as non-static data members of its outer class irrespective of their scope.

Example Program for non-static inner class –

package InnerClassOuterClass;

class A

private static int a;

private int b;

public A(int x)

b=x;

static
83

a=5;

System.out.println("A is loaded...");

public void display()

System.out.println("a of this class is : " + a);

System.out.println("b of this class is : " + b);

// non-static inner class starts

public class B

int c;

public B(int x)

c=x;

public void display()

System.out.println("a of outer class is : " + a);

System.out.println("b of this object is : " + b);

System.out.println("c of this object is : " + c);

// non-static inner class ends.

}
84

class InnerTest

public static void main(String args[])

System.out.println("Initiating outer class..");

A x = new A(10);

System.out.println("Initiating non-static inner class..");

A.B y = x.new B(20);

System.out.println("invoking display() method on outer class object");

x.display();

System.out.println("invoking display() method on inner class object");

y.display();

Output –
85

Syntax of creating object of non-static inner class outside the scope of outer class:-

OuterClassName outerRef = new OuterClassName(-);

OuterClassName. InnerClassName innerRef = outerRef.new InnerClassName(-);

To facilitate availability of non-static data members of outer class in the non-static inner class compiler makes
following modifications to the outer and inner classes:

1. In the inner class :


a. A data member of type outer class is contained in the inner class.
86

b. Constructor of inner class is modified to receive an extra parameter of type outer class.

2. In the Outer class:


For each private static data member of outer class static accessor method is created in the outer class.
87

INNER CLASSES provide a convenient mechanism of implementing has-a relation between classes. Non-static
inner classes represents an intimate relation between outer & inner class because

a. Inner class is a member of outer class which means that outer class is incomplete without inner
class.
b. Inner class is defined to provide a service to the outer class i.e. existence of inner class depends
on the existence of outer class.
-----------------------------------------------------------X--------------------------------------------------------

Date: 04.07.10

PACKAGE
A package is a logical container that contains logically related classes, interfaces & subpackages.

Packages are used to provide unique namespace to classes and packages provide a mechanism of
enforcing scope.

Three parties are always involved in programming:-


1. Technology Provider
2. Application Developer
3. Third Party Vendor
Packages provide a mechanism of uniquely identifying classes by associating package name to the class
name i.e. once a class is associated to a package it is referred using the fully qualified name.

packageName.className
88

In order to associate a class to a package, package keyword is used as the first statement in a class
definition.

Syntax:-
package pkgName;

To provide physical separation of classes of different packages classes of a package are saved in a folder
of the same name as the package.

NOTE: Concept of package is applied only on classes not on java files.


89

package p2;

public class Two


{
public void display()
{
System.out.println("It is part of p2....");
}
}

package p1;

public class One


90

{
public static void main(String[] args)
{
System.out.println("Referencing Two of p2....");
p2.Two x = new p2.Two();
x.display();
}
}

Import keyword is a convenience provided to java developers by the java compiler to refer classes of
one package into another without using their fully qualified name.

Syntax –
import pkgName.className;
or
import pkgName.*;
91

Dated : 10.07.10
92

package p1;

public class A
{
protected void display()
{
System.out.println(“protected method of A invoked.”);
}
}

package p2;

public class B extends A


{
93

public void show()


{
System.out.println(“Show of subclass invoked.”);
}
}

package p2;

public class C
{
public static void main(String args[])
{
B x = new B();
x.show();
x.display(); //Compilation error
}
}

package p2;

public class B extends p1.A


{
public void show()
{
System.out.println(“Show of subclass invoked.”);
}
}

----------------------------------------------X-----------------------------------------------

Now,

package p2;

public class B extends p1.A


{
public void show()
94

{
System.out.println(“Show of subclass invoked.”);
}

public static void main(String args[])


{
B x = new B();
x.show();
x.display(); //Compilation error
}
}

----------------------------------------------X-----------------------------------------------
package p2;

public class B extends p1.A


{
public void show()
{
System.out.println(“Show of subclass invoked.”);
}

public void display()


{
System.out.println(“display of subclass invoked.”);
}

public static void main(String args[])


{
B x = new B();
p1.A y = x;
x.show();
x.display(); //Shall not Compile
}
}
95

Protected members of a class can only be referred from a different package using the reference variables
of those classes which are defined in the invoking package.

----------------------------------------------X-----------------------------------------------

Exception Handling

Exceptions are those runtime errors which can be handled programmatically in the application.
Exception handling adds the features of robustness into the language.

In Java, each runtime error is represented by an object. There exists class JRE for describing runtime
errors. At the root of this class hierarchy is class named Throwable which has 2 non-abstract subclasses
named Exception and Error.

Commonly used subclasses of Exception:-


1. ArithmeticException – represents an invalid arithmetical operation such as divide by zero.
96

2. ArrayIndexOutOfBoundsException – represents an attempt to refer non-existent array elements.


3. NullPointerException – represents an attempt to use a null containing reference variable for referencing
object features.
4. NumberFormatException – represents an attempt to correct non-numeric string into a number.
5. etc.

Commonly used subclasses of error –


1. Virtual Machine Error – represents malfunctioning of JRE.
2. StackOverflowError – represents overflowing of stack.
3. NoSuchMethodError – represents an attempt to invoke a non-existent method.
4. NoClassDefFoundError – represents an attempt to load a non-existent class.
5. etc.

Exception handling is facilitated with the help of following keywords:-


a. try keyword is used to mark a block of statements as error prone
try
{
error prone
statements
{
catch(Exception e)
{
Statements to be executed in case of Runtime Error
}
}
}

OR

try
{
97

error prone
Statements
}
finally
{
Statements to be executed whether error occurs or not
}

OR

try
{
error prone
Statements
}
catch(Exception e)
{
Statements to be executed in case of Error
}

finally
{
Statements to be executed whether exception occurs or not
}

b. catch keyword is used to define an exception handler i.e. it defines an alternative course of action that is
taken by the JRE when the error represented by the catch block occurs.
c. throw keyword is used for explicit exception throwing
d. throws
e. finally keyword is used to define a block of statements that is executed by the JRE with 100% certainty
whether an exception occurs or not.

package ExceptionHandling;

class Divide
{
public static void main(String[] args)
{
try
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = a/b;
System.out.println("Result is : " + c);
}
catch(Exception e)
{
System.out.println("Second Number must be non zero");
}
catch(NumberFormatException e)
{
98

System.out.println("Argument must be numeric..");


}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Two Argument must be provided..");
}
}
}

NOTE : If generalized as well as specific Exception handler are associated to a catch block then
generalized exception handler must be the last one.

throw keyword is used for explicit exception throwing.

Syntax – throw (Exception object);


99

Output-

Usage of throw keyword


1. throw keyword is used for throwing user-defined exceptions.
2. throw keyword is used to customize the message of predefined exceptions.
3. throw keyword is used to rethrowing exceptions.
100
101
102

Output-
103

Dated: 11.07.10

In java, a method can have two exit path i.e. it can return a value or it can throw an exception.
Now, modification done in last program –
package ExceptionHandling;

class Divide
{
public static int divide(int x, int y)
{
try
{
return x/y;
}
catch(ArithmeticException e)
{
System.out.println("ArithmeticException caught in divide,
rethrowing.....");
throw(e);
}
}
public static void main(String[] args)
{
try
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = divide(a, b);
System.out.println("Result is : " + c);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
104

throws keyword is used to specify the exceptions that can be thrown by method.
Proper signature of method –
Modifier returntype MethodName(Arg list) throws ExceptionList;
Example –
public static int parseInt(String no) throws NumberFormatException;
Exception can be of 2 types:-
105

1. Checked Exception are those exceptions which are forced by the compiler either to be properly caught
or declared to be thrown.
2. Unchecked exceptions are those exceptions which are not forced by the compiler either to be properly
caught or declared to be thrown.
Unchecked exceptions represents either common logical errors or those runtime errors which cannot be
programmatically handled.
Error and its subclasses, Runtime and its subclasses are unchecked exception or other are checked.

throws keyword is a part of method signature.


throw keyword is a part of method implementation.
finally keyword is used to define a block of statements that is executed by the JRE whether an exception
occurs or not.

class Divide
{
public static int divide(int x, int y)throws ArithmeticException
{
boolean error = false;
try
{
return x/y;
}
catch(ArithmeticException e)
{
error = true;
106

throw(e);
}
finally
{
if(error)
System.out.println("throwing exception....");
else
System.out.println("returning value....");
}
}
public static void main(String[] args)
{
try
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = divide(a, b);
System.out.println("Result is : " + c);
}
catch(Exception e)//generalized exception handler
{
System.out.println(e);
}
}
}

State whether true or false:


1. A value that is returned from a method is always received in the invoking method i.e. it is not listed in
the transit.
2. An Exception that is thrown is always caught either by the application or JRE.
107

NOTE: When branching instructions are executed in finally then these branching instructions
nullifies
other branching instructions executed in the method before finally.

Defining Custom Exception-


Custom Exception is represented by direct or indirect subclass of exception that contains data member
to store error message and provides a mechanism of displaying the error message.

package ExceptionHandling;

class InvalidAgeException extends Exception


{
String message;

public InvalidAgeException()
{
message = "Age range is 18 to 60";
}

public InvalidAgeException(String msg)


{
message = msg;
}

public String toString()


{
return message;
}
}

class CustomTest
{
public static void main(String[] args)
{
if(args.length==0)
System.out.println("Enter your age as command line argument.");
else
{
try
{
int a = Integer.parseInt(args[0]);
if(a<18||a>60)
throw (new InvalidAgeException());
108

System.out.println("Welcome to the group of


freaks....");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
109
110
111
112

Dated :17.07.10
String Handling
Java Library provides 4 classes to represent & manipulate a string.
1. String
2. StringBuffer
3. StringBuilder
4. StringTokenizer
An object of type String represents an immutable sequence of characters.
A string object can be created using following constructors:-
public String();
public String(char[]);
public String(char[], int offset, int NoOfChar);
public String(byte[]);
public String(byte[], int offset, int NoOfBytes);
public String(String s);

Example:-
class StringDemo
{
public static void main(String[] args)
{
char[] a = {'A', 'B', 'C', 'D', 'E', 'F'};
byte b[] = {65, 66, 67, 68, 69, 70};
String s1 = new String(a);
String s2 = new String(a, 2, 3);
String s3 = new String(b);
String s4 = new String(b, 0, 3);
String s5 = new String(s2);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s1==s3);
System.out.println(s2==s5);
System.out.println(s2==s4);
}
}
Output
113

Equals to (==) operator when used to compare objects compares the value of references not the contents
of objects.

To facilitate content wise comparison of objects equals() define by Object class is used.
public boolean equals(Object o);

Default implementation of equals() in Object class compares the references of objects not their contents.
String class overrides this method to facilitate content wise comparison of Strings.
Example
package StringHandling;

class StringDemo
{
public static void main(String[] args)
{
char[] a = {'A', 'B', 'C', 'D', 'E', 'F'};
byte b[] = {65, 66, 67, 68, 69, 70};
String s1 = new String(a);
String s2 = new String(a, 2, 3);
String s3 = new String(b);
String s4 = new String(b, 0, 3);
String s5 = new String(s2);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
//System.out.println(s1==s3);
//System.out.println(s2==s5);
//System.out.println(s2==s4);
System.out.println(s1.equals(s3));
System.out.println(s2.equals(s5));
System.out.println(s2.equals(s4));
}
}

Output –
114

Program

package StringHandling;

class A
{
public static String s1 = "Hello India";
}

class B
115

{
static String s2 = "Hello India";

public static void main(String args[])


{
String s3 = "Hello " + "India";
String s4 = new String ("Hello India");
String s5 = new String ("Hello") + " India";
System.out.println(A.s1==s2);
System.out.println(s2==s3);
System.out.println(s3==s4);
System.out.println(s4==s5);
System.out.println(A.s1.equals(s5));
System.out.println(s4.equals(s2));
}
}
Output –
116

In the pool of string constants, string constants are shared across different classes and scopes. (In Java,
string constants and constant expression that can be evaluated at Compilation time are stored in pool of String
Constants.)

Commonly used methods of String class:-


1. length() method returns the size of a string.
public int length();

2. charAt() method is used to obtain a character stored at the given index in the string.
public char charAt();

3. toCharArray() method returns a character array initialized by the contents of the string.
public char[] toCharArray();

4. getBytes() method returns a byte array initialized with the contents of the string.
public byte[] getBytes();
Example –
package StringHandling;

class GetBytesMethodDemo
{
public static void main(String[] args)
{
String s = "abcdef";
char[] c = s.toCharArray();
for(int i=0; i<c.length; i++)
117

c[i]-= 32;
System.out.println(new String(c));
}
}
Output –

5. indexOf() method is used to find out the index of the first occurrence of the given character or string in the
string.
public int indexOf(char ch);
public int indexOf(String s);

6. lastIndexOf() method is used to find out the index of the last occurrence of the given character or string in
a string.
public int lastIndexOf(char ch);
public int lastIndexOf(String s);

Example –

7. compareTo( ) method is used to find out the order of strings.


public int compareTo (String s);

 return +ve integer if invoking String comes after parameter String, -ve integer otherwise.
 0 if both strings are same.
Example -
118

8. substring( ) method is used to extract part of a string.

public String substring (int startIndex);

public String substring (int startIndex, int endIndex);

Example –

9. concat( ) method is used to concatenate two strings.


119

public String concat (String s);

Example –

10. toUpperCase() & toLowerCase() methods are used for converting the contents in Upper & Lower case
respectively.

public String toLowerCase ( );

public String toUpperCase ( );

11. valueOf( ) method is used to convert a primitive type into string.

public static String valueOf (int i );


public static String valueOf (char c );
public static String valueOf (float f );
public static String valueOf (double d);

Identify & rectify problems (if any) in the given class:-


120

Same Program after modification


121

OR
122

StringBuffer
 Objects of StringBuffer represents mutable strings. Each StringBuffer object creates an array of default or
specified capacity that is used to hold the contents of StringBuffer.
 Default capacity of StringBuffer object is 16 characters.
 StringBuffer objects can be created using following constructors:-

public StringBuffer();
public StringBuffer(int capacity);
public StringBuffer(String s);
Example-
123

Commonly used methods-

1. append ( ) method is used to append a primitive value or contents of a string to the StringBuffer.

public StringBuffer append(int i);


public StringBuffer append(char c);
public StringBuffer append(String s);

Example –
124

2. insert( ) method is used to insert a string at the given position in the StringBuffer object.

public StringBuffer insert(int index, String s);

Example –
125

3. replace( ) method is used to replace part of a StringBuffer object with the given string.

public StringBuffer replace(int startIndex, int endIndex, String s);

Example –
126

4. reverse ( ) method reverses the contents of StringBuffer.

public StringBuffer reverse();

5. toString( ) method returns the content of StringBuffer as an immutable string.

public String toString();

etc.
127

Dated: 18.07.10
StringBuffer b =new StringBuffer();

package StringHandling;

class BufferTest
{
public static void main(String[] args)
{
StringBuffer b = new StringBuffer(7);
b.append("Hello");
System.out.println("Capacity after appending hello: " + b.capacity());
b.append("India");
System.out.println("Capacity after appending India: " + b.capacity());
System.out.println("Contents : " + b);
}
}
Output-

Let‟s see the explanation that after appending “India” how capacity is coming 16.
package StringHandling;

class MyBuffer
{
int capacity;
int length;
char[] contents;

public MyBuffer()
{
this(10);
}

public MyBuffer(int c)
{
capacity = c;
length = 0;
contents = new char[capacity];
}

public MyBuffer(String s)
{
this(s.length()+ 10);
append(s);
}
128

public int capacity()


{
return capacity;
}

public void ensureCapacity(int c)


{
int m = Math.max(2 * capacity + 2, c);
char temp[] = new char[m];
System.arraycopy(contents, 0, temp, 0, length);
contents = temp;
capacity = m;
}

public MyBuffer append(String s)


{
int c = s.length()+ length;
if (c>capacity)
ensureCapacity(c);

System.arraycopy(s.toCharArray(), 0, contents, length, s.length());


length = c;
return this;
}

public String toString()


{
return new String(contents);
}
}

package StringHandling;

class BufferTest
{
public static void main(String[] args)
{
MyBuffer b = new MyBuffer(7);
b.append("Hello");
System.out.println("Capacity after appending hello: " + b.capacity());
b.append("India");
System.out.println("Capacity after appending India: " + b.capacity());
System.out.println("Contents : " + b);
}
}

Output-
129

Eliminating Question in Interviews-


Q. What is the difference between following set of statements?
1. String s = “ABC”;
System.out.println(s.concat(“PQR”).concat(“XYZ”));

2. System.out.println(“ABC” + “PQR” + “XYZ”);

Explanation –
130
131

MULTITHREADING
132

Q. What is the difference between Program & Process?


Answer
 A program represents a set of instructions which are stored in a file. In order to execute a program
various resources such as memory, I/O devices, processor etc. are required. When resources are
allocated to a program it becomes process.
 Multiprocessing is the facility of allocating resources to multiple programs.
 A thread is an independent module of a process that can be concurrently executed with other
threads.
 Facility of executing multiple concurrent threads is called multithreading.

Q. Difference between multithreading and multiprocessing.


1. In Multiprocessing, each process represents an independent application whereas in Multithreading
each thread represents an independent module in the application.

2. In case of Multiprocessing each process has its own address space whereas in case of
Multithreading all the threads share a common address space.
133

3.
O/S incurs less overhead in the management of threads as compare to the management of process.
Because of this multithreading is called lightweight multiprocessing.
The first requirement of multithreading is the identification of independent modules of an application.
For the identification Sun Microsystems provides an interface named Runnable which provides a
method named run(). This method represents a thread.

public interface java.lang.Runnable{


public abstract void run();
}

In order to define a Java Thread implementation of this interface need to be provided. It can be done in
the following 2 ways:-
134

Question. What is relation between Java Threads and objects of Thread class?
Answer – For each thread an object of type Thread is created. This object is used to manage the
Thread.
Let there be 2 active threads in an application.
135
136

Dated : 24/07/10

Commonly used methods of Thread class

1. getName () method returns the name of thread.


public String getName();

2. setName () method is used to change the name of a thread.


public void setName (String name);

3. getPriority () method is used to find out the priority of a thread.


public int getPriority ();

4. setPriority () method is used to change the priority of a thread.


public void setPriority(int priority);

5. sleep () method is used to suspend a thread for the specified time.


public static void sleep (long milliseconds) throws InterruptedException;

6. start () method is used to start a thread i.e. this method loads the run method as a thread.
public void start();

7. isAlive () method is used to find out whether a thread is completed or not.


public boolean isAlive();

8. currentThread () method returns the reference of the thread object for the current thread.
public static Thread currentThread();

etc.
137

Note: To start the execution of an application JRE starts a thread by the name main. This thread is used
by the application developers to start other threads.

Question : Difference between main() and main Thread.


138

package Multithreading;

class ThreadTest
{
static
{
System.out.println("ThreadTest is loaded, obtaining the reference of its
Thread....");
Thread t = Thread.currentThread();
System.out.println("Name & Priority of this thread are: " + t.getName()
+ "\t" +t.getPriority());

try
{
System.out.println("Suspending current thread for 5 seconds...");
Thread.sleep(5000);
}
catch(Exception e)
{
System.out.println("Thread is resumed, Initialization is
completed.");
}
}
}
Output –
139

Now, same program with some modifications –

package Multithreading;

class ThreadTest2
{
static
{
System.out.println("ThreadTest is loaded, obtaining the reference of its
Thread....");
Thread t = Thread.currentThread();
System.out.println("Name & Priority of this thread are: " + t.getName()
+ "\t" +t.getPriority());

try
{
System.out.println("Suspending current thread for 5 seconds...");
Thread.sleep(5000);
System.out.println("Thread is resumed, Changing name and
priority....");
t.setName("MyThread");
t.setPriority(7);
}
catch(Exception e)
{
System.out.println("Initialization is completed.");
}
}
public static void main(String arr[])
{
System.out.println("main() method invoked, obtaining the refernce of its
invoking thread.... ");
Thread t = Thread.currentThread();
System.out.println("Name & Priority of this thread are: " + t.getName()
+ "\t" +t.getPriority());
140

System.out.println("Main thread is completing....");


}
}

Output-

 Defining User Threads

In order to define a user thread implementation of Runnable interface need to be provided.

Note:

javap java.lang.Runnable
javap java.lang.Thread

Program
package Multithreading;

class UserThread extends Thread


{
public UserThread(String name)
{
super(name);
}

public void run()


{
System.out.println("run() method is invoked from " + getName() +
"thread.");

for(int i=1; i<=10; i++)


{
System.out.println(i);
try
141

{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("run() is completed.");
}
}
}
}

class MultiThread
{
public static void main(String[] args)
{
Thread t = Thread.currentThread();
System.out.println("Main() method is invoked by " + t.getName() +
"thread.");
UserThread th = new UserThread("MyThread");
System.out.println("Invoking run().........");
//th.run();
th.start();
for(int i=1; i>10; i--)
{
System.out.println(i);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{}
System.out.println("main() is completed.");
}
}
}
Output –
142

Note :
th.run(); // shall be executed as a method.
th.start(); // shall be executed as a thread.

Note: When direct implementation of Runnable interface is provided then an object of Thread class is
required for starting the thread.
143

1. Synchronous
2. Asynchronous

Execution of threads in Java is asynchronous i.e. context switch between threads cannot be predicted.

Sometimes, synchronization among threads is desirable, especially in cases where a common resource is
shared by multiple threads in order to use the common resource in a mutually exclusive manner.
144

Dated : 25/07/10
PROBLEM
package Multithreading;
import java.io.*;

class MyReader
{
BufferedReader b;
public MyReader()
{
b = new BufferedReader(new InputStreamReader (System.in));
}

public String readData(String msg)


{
try
{
System.out.println(msg);
return b.readLine();
}catch(Exception e)
{
return "Error in I/O";
}
}
}

package Multithreading;

class NameReader extends Thread


{
MyReader reader;

public NameReader(MyReader r)
{
reader = r;
}

public void run()


{
System.out.println("Name Reader started, reading name...");
String name = reader.readData("Enter Name: ");
System.out.println("Welcome, " + name);
}
}

package Multithreading;

class AddressReader extends Thread


{
MyReader reader;

public AddressReader(MyReader r)
{
reader = r;
}

public void run()


{
System.out.println("Address Reader started, reading address...");
String address = reader.readData("Enter Address: ");
145

System.out.println("Your address: " + address + " is successfully


registered in our records.");
}
}

package Multithreading;

class AsynTest
{
public static void main(String[] args)
{
MyReader r = new MyReader();
System.out.println("Creating and starting Name and AddrressReader....");
NameReader nr = new NameReader(r);
AddressReader ar = new AddressReader(r);
nr.start();
ar.start();
}
}

OUTPUT –

To get the solution of last problem, we need to analyze the problem first.
This is the problem shown in figure below –
146

Solution - To share objects among threads in mutual exclusive manner concept of monitor is used.
Monitor represents an exclusive lock that is to be obtained by thread to execute its critical section.

In Java, objects are implicitly locked. Synchronized keyword is used to mark a block of statement as
critical section.

Syntax -
1. To mark whole method as critical section-

synchronized returnType MethodName()


{

……………………..
……………………..
……………………..

2. To mark only a part of method as critical section –

synchronized (Object to be lock)


{

……………………..
……………………..
……………………..

}
147

Note: Synchronization works only if all the threads sharing a resource are synchronized.

Using synchronization only mutual exclusivity of a resource can be determined. Its order of usage
cannot be determined. Sometimes a common resource is to be used in a mutually exclusive manner
among threads in specific order as represented by the following problem.
 PROGRAM

package Multithreading;

class Buffer
{
int a;

public synchronized void produce(int x)


{
a = x;
System.out.println(a + " is produced.");
}

public synchronized void consume()


{
System.out.println(a + " is consumed.");
}
}

package Multithreading;

class Producer extends Thread


{
Buffer b;

public Producer(Buffer buffer)


{
b = buffer;
}

public void run()


{
System.out.println("Producer started, producing values...");
for(int i=1; i<=10; i++)
{
b.produce(i);
}
}
}

package Multithreading;

class Consumer extends Thread


{
Buffer b;

public Consumer(Buffer buffer)


{
b = buffer;
}
148

public void run()


{
System.out.println("Consumer started, consuming values...");
for(int i=1; i<=10; i++)
{
b.consume ();
}
}
}

package Multithreading;

class PC
{
public static void main(String[] args)
{
Buffer buffer = new Buffer();
System.out.println("Starting Producer & Consumer...");
Producer p = new Producer(buffer);
Consumer c = new Consumer(buffer);
c.start();
p.start();
}
}

OUTPUT-
149

 Interthread Communication is used to control the scheduling of threads.

Interthread Communication is facilitated with the help of following methods –


a) wait () method instucts the current thread to release the monitor and to get suspended until some other
thread invokes notify () or notifyAll () method from the same monitor.

public void wait() throws InterruptedException;

b) notify () method is used to send the notification to the thread which is suspended by wait () method.

public void notify();

c) notifyAll () method notifies all the threads which are suspended by the wait() method.

public void notifyAll();

 These method are defined in Object class.

In Java, each object has a monitor associated to it. This monitor is used by the threads to execute their
critical sections with the object. A monitor is implemented as a collection of queues and flags.
150

 PROGRAM

package Multithreading;

class Buffer1
{
int a;

boolean produced = false;

public synchronized void produce(int x)


{
if (produced)
{
System.out.println("Producer entered Monitor out of turn, Suspending ....");
}
try
{
wait();
}catch(Exception e) {}
a = x;
System.out.println(a + " is produced.");
produced = true;
notify();
}

public synchronized void consume()


151

{
if (!produced)
{
System.out.println("Consumer entered Monitor out of turn, Suspending ....");
}
try
{
wait();
}catch(Exception e) {}

System.out.println(a + " is consumed.");


produced = false;
notify();
}
}

package Multithreading;

class Consumer1 extends Thread


{
Buffer1 b1;

public Consumer1(Buffer1 buffer1)


{
b1 = buffer1;
}

public void run()


{
System.out.println("Consumer started, consuming values...");
for(int i=1; i<=10; i++)
{
b1.consume();
}
}
}

package Multithreading;

class Producer1 extends Thread


{
Buffer1 b1;

public Producer1(Buffer1 buffer1)


{
b1 = buffer1;
}

public void run()


{
System.out.println("Producer started, producing values...");
for(int i=1; i<=10; i++)
{
b1.produce(i);
}
}
}
152

package Multithreading;

class PC1
{
public static void main(String[] args)
{
Buffer1 buffer = new Buffer1();
System.out.println("Starting Producer & Consumer...");
Producer1 p = new Producer1(buffer);
Consumer1 c = new Consumer1(buffer);
c.start();
p.start();
}
}

OUTPUT-

 Sometimes output of a thread is used as input by another thread. In such a case later thread must be
suspended until the forward thread is completed.

join () method is used to suspend the current thread until invoking thread completes or specified time is
elapsed.

public void join() throws InterruptedException;


public void join(long milliseconds) throws InterruptedException;

Note : There are 5 ways of suspending a thread.


 By sleep().
 By wait ().
 By join ().
 By I/O.
 By synchronization.
153

Start
InterruptedException is thrown.

Normal execution resumes.


Stop

Runnable
I/O operation
Thread is scheduled.
is completed Thread
Is
Yes interrupted
sleep () is Sleeping for
Waiting for I/O
invoked? specified time. specified
to complete
time
is over
Yes No

I/O operation is wait () is Yes Waiting Thread is interrupted


No
performed for
invoked?
notification

No No Notification
is received

synchronized Yes
join () is Waiting Lock is granted
block is
invoked? executed? for
Joined lock
thread is
completed
or Yes
specified
time Waiting for joined thread to
is over
complete or for specified
Thread is interrupted
time.
154

Dated: 07.08.10

 Daemon Thread is a thread whose existence depends on non-daemon threads i.e. a daemon thread requires
normal thread for its existence. At any point of time queuing the execution of a thread if only a daemon thread
remains as active thread then JRE aborts it and terminated.
 Daemon threads are used to provide services to other threads.
 Garbage Collector in Java is started by the JRE as a daemon thread.
 Each thread has a boolean flag named daemon that is set to make the thread daemon thread.
o setDaemon() method is used for this purpose.

public void setDaemon(boolean flag);

o isDaemon() method is used to find out the value of daemon flag.

public boolean isDaemon();

NOTE: Daemon flag can only be set before a thread is started.

package Multithreading;
class UserThread extends Thread
{
public void run()
{
Thread t = Thread.currentThread();
if(t.isDaemon())
System.out.println("User thread is started as daemon...");
else
System.out.println("User thread started normally....");
for(int i=1; i<=10; i++)
{
System.out.println(i);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{}
}
}
}
class DeamonThreadDemo
{
public static void main(String[] args)
{
System.out.println("Starting user thread.....");
UserThread th = new UserThread();
//th.setDaemon(true);
th.start();
for(int i = 10; i>5; i--)
{
System.out.println(i);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{}
}
System.out.println("Main thread is completed");
155

}
}

Output-
Starting user thread.....
10
User thread started normally....
1
9
2
3
8
7
4
5
6
6
Main thread is completed
7
8
9
10

package Multithreading;
class UserThread extends Thread
{
public void run()
{
Thread t = Thread.currentThread();
if(t.isDaemon())
System.out.println("User thread is started as daemon...");
else
System.out.println("User thread started normally....");
for(int i=1; i<=10; i++)
{
System.out.println(i);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{}
}
}
}
class DeamonThreadDemo
{
public static void main(String[] args)
{
System.out.println("Starting user thread.....");
UserThread th = new UserThread();
th.setDaemon(true);
th.start();
for(int i = 10; i>5; i--)
{
System.out.println(i);
try
{
156

Thread.sleep(1000);
}
catch(Exception e)
{}
}
System.out.println("Main thread is completed");

}
}

Output-
Starting user thread.....
10
User thread is started as daemon...
1
9
2
8
3
7
4
5
6
6
Main thread is completed
157

Input/Output[Part - 1]
 Input/Output in java is stream based. A stream represents sequence of bytes or characters. Stream-
based input/output has following advantages over conventional I/O.
1. Abstraction
2. Flexibility
3. Performance
 In Java, two types of input output streams are defined :-
o Byte oriented streams(8-bit sequence)
o Character oriented streams(16-bit sequence)
 Commonly used byte oriented streams-
InputStream
is an abstract class that is extended by all byte oriented input streams.
 ByteArrayInputStream is an input stream that is used to read bytes from a byte array.
 BufferedInputStream is an input stream used to read bytes from a buffer.
 FileInputStream is an input stream used to read bytes from a file.

InputStream class contains an abstract read() method that is defined by all its subclasses.
 public int read() throws IOException;
 public int read(byte[ ]) throws IOException;

OutputStream
is an abstract class that is extended by all byte oriented output streams.
 ByteArrayOutputStream is an output stream that is use to write bytes to a byte array.
 BufferedOutputStream is an output stream use to write bytes to a buffer.
 FileOutputStream is an output stream used to write bytes to a file.
 PrintStream is an output stream use to write primitive types, characters & strings to another
stream. This stream provides print() and println() methods.

OutputStream class contains an abstract write() method that is defined by all its subclasses. It is used
to write a byte or block of bytes to OutputStream.
 public void write(int byte) throws IOException;
 public void write(byte[ ]) throws IOException;

General Signature of creating an Input/output stream –


public TypeInputStream(Object source);
public TypeOutputStream(Object sink);
Example -
o Create an InputStream to read bytes from a byte array.
byte a[ ] = {1, 2, 3, 4, 5};
ByteArrayInputStream b = new ByteArrayInputStream(a);
b.read();

o Stream to read bytes from a file named “a.txt”.


FileInputStream f = new FileInputStream(a);
f.read();

o Stream to read bytes from keyboard


158

BufferedInputStream b = new BufferedInputStream(System.in);


b.read();

 Commonly used character oriented streams-


Reader
is an abstract class that is extended by all character oriented input streams.
 CharArrayReader is an input stream use to read characters from a character array.
 BufferedReader is an input stream use to read characters and strings from a buffer.
 FileReader is an input stream use to read characters from a file.
 InputStreamReader is an input stream use to convert bytes to characters.

Writer
is an abstract class that is extended by all character oriented output streams.
 CharArrayWriter is an output stream use to write characters to a character array.
 BufferedWriter is an output stream use to write characters to a buffer.
 FileWriter is an output stream use to write characters to a file.
 OutputStreamWriter is an output stream use to convert characters to bytes.
 PrintWriter is the character oriented version of PrintStream.
 etc.

Reader class provides an abstract read() method that is defined by all its subclasses. Apart from read()
method BufferedReader class defines an additional method named readLine() method that reads a
complete line of text from a stream & returns it as a string.

public String readLine() throws IOException;


159
160

o Statements

NOTE : All these I/O streams are defined in java.io package.

 Example1
//to display the contents of a text file on console.
// name of file is given as command line argument.
// data is read from the file byte by byte.
161

import java.io.*;

class Display
{
public static void main(String[] args)
{
try
{
FileInputStream f = new FileInputStream(args[0]);
int ch;
while(true)
{
ch=f.read();
if(ch==1)
break;
System.out.println((char) ch);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

 Example2
//to display the contents of a text file on console.
// name of file is given as command line argument.
// data is read from the file line by line.

import java.io.*;

class Display1
{
public static void main(String[] args)
{
try
{
BufferedReader f = new BufferedReader(new InputStreamReader(new FileInputStream(args[0])));
while(true)
{
String line=f.readLine();
if(line==null)
break;
System.out.println(line);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
162

 Example3
//to display the contents of a text file on console.
// name of file is given as command line argument.
// data is read from the file in one go.

import java.io.*;

class Display3
{
public static void main(String[] args)
{
try
{
FileInputStream f = new FileInputStream(args[0]);
byte a[] = new byte[f.available()];
f.read(a);
String s = new String(a);
System.out.println(s);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
163

Date: 08.08.10
 SequenceInputStream is used to read data from multiple input streams in a sequence. This stream groups
multiple input streams into a single logical input stream.

 SequenceInputStream object can be created using either of the following constructors.

public SequenceInputStream (InputStream stream1, InputStream stream2);


public SequenceInputStream (Enumeration streams);

PROGRAM

“Copier.java”

package IO;
import java.io.*;

// to copy contents of two files to a file.


// file names are provided as command line arguments.

class Copier
{
public static void main(String[] arr)
{
try
{
SequenceInputStream in = new SequenceInputStream(new
FileInputStream(arr[0]), new FileInputStream(arr[1]));
FileOutputStream out = new FileOutputStream(arr[2]);
while(true)
{
int ch = in.read();
if(ch==1)
break;
out.write(ch);
}
out.close();
164

System.out.println("Successfully copied.");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

“Creator.java”

package IO;
import java.io.*;

// to create a text file.


// file name is given as command line arguments.
// contents are read from keyboard line by line and saved to the file.

class Creator
{
public static void main(String[] arr)
{
try
{
BufferedReader b = new BufferedReader(new
InputStreamReader(System.in));

PrintStream out = new PrintStream ( new


FileOutputStream(arr[0]));

System.out.println("Enter text, end to save.");


while(true)
{
String s = b.readLine();
if(s.equals("end"))
break;
out.println(s);
}
out.close();
System.out.println("Successfully created.");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

----------------------------------------------X---------------------------------------------------------------

PROGRAM
“MyCreator.java”
package IO;
import java.io.*;

class MyCreator
{
public static void main(String[] arr)
{
165

try
{
BufferedReader b = new BufferedReader(new
InputStreamReader(System.in));

PrintStream myout = new PrintStream ( new


FileOutputStream(arr[0]));

System.out.println("Enter text, end to save.");


PrintStream temp = System.out; // Reference of standard output stream is
used.
System.setOut(myout); // Standard output is redirected to a file.
while(true)
{
String s = b.readLine();
if(s.equals("end"))
break;
System.out.println('s'); //data shall be written to the file

}
myout.close();
System.out.println(temp); //standard output is reset.
System.out.println("Successfully created.");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

 Serialization is the process of converting the state of an object into a sequence of bytes in such a manner
that given this sequence of bytes object with the same state can be reconstructed at a later stage.
o ObjectOutputStream
o ObjectInputStream
o These classes are used to serialize & deserialize the objects.
o writeObject() method of ObjectOutputStream is used for serializing objects.

public void writeObject(Object o) throws NotSerilizableException;

NOTE: Facility of serialization is not provided to objects of all classes by default.

 In order to serialize objects of a class, class must implement java.io.Serializable interface. This is a marker
interface.
o A marker interface is an interface that doesn‟t contain any methods.
o Example

interface Serializable
{}
o Marker interfaces are used to mark a classes as part of a group so that some additional service
can be provided to the classes of this group.
 Facility of serializable is not provided by default to objects of all classes because state of all objects must
not be serialized.

o State of objects can be of two types-


166

 Application Specific.
 System/JRE Specific.

Example
1.

2.

Dated:14.08.10

package IO;

public class Student implements java.io.Serializable


{
private String name, course;
int fee;

public Student(String n, String c, int f)


{
name = n;
course = c;
fee = f;
}

public void display()


{
System.out.println(name + "\t" + course + "\t" + fee);
}
167

“ObjSaver.java”
package IO;
import java.io.*;

class ObjSaver
{
public static void main(String[] args)
{
try
{
Student s1 = new Student("Amar", "Java", 12000);
Student s2 = new Student("Ravi", ".Net", 8000);
System.out.println("Serializing following objects...");
s1.display();
s2.display();
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("std.obj"));
out.writeObject(s1);
out.writeObject(s2);
out.close();
System.out.println("Successfully serialized.");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

“ObjGetter.java”
package IO;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

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

{
try
{
System.out.println("Deserializing following objects...");
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("std.obj"));

Student s1 = (Student) in.readObject();


Student s2 = (Student) in.readObject();
System.out.println("Following objects are serialized.");
s1.display();
s2.display();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

 transient keyword is used to mark those data members of a Serializable class which are not to be Serialized.

NOTE:
ObjectOutputStream & ObjectInputStream classes generates unique Id’s for the class only if a class does not contain
static final long data member by the name serialversionUID.
 jdk provides a tool by the name serialver that generates a serialversion ID for a class.
 NOTE: Composite objects can only be serialized if all their constituent members are serializable.
169

 Reading & writing primitive types


DataInputStream & DataOutputStream classes were used for reading & writing primitive types. These classes are deprecated in
Jdk 1.5.
From Jdk 1.5 onwards java.util.Scanner class is used for reading primitive values from a stream.
 Commonly used methods of Scanner class are:-
public int nextInt();
public char nextChar();
public byte nextByte();
public float nextFloat();
public String nextLine();
etc.
Example 1
package IO;

import java.util.Scanner;

class Adder
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter First Number....");
int a = s.nextInt();
System.out.println("Enter Second Number....");
int b = s.nextInt();
int c = a+b;
System.out.println("Result is = " + c);
}
}
170

Example 2
package IO;

import java.util.Scanner;
import static java.lang.System.*;

class Adder
{
public static void main(String[] args)
{
Scanner s = new Scanner(in);
out.println("Enter First Number....");
int a = s.nextInt();
out.println("Enter Second Number....");
int b = s.nextInt();
int c = a+b;
out.println("Result is = " + c);
}
}
171

 Types of Application can be made in Java-


1. Console Application.
2. Windows Application.
3. Web Application.
4. Web Services.
5. Network Application.
172

 static import is the facility of using static members of a class without using their fully qualified name
Syntax-
import static pkgName.className.staticMemberName;
or
import static pkgName.className.*;
 for-each loop was introduced to traverse the elements of a collection(group of elements) in a convenient manner.
Syntax –
for(type identifier : collection)
identifier return Next value of the collection in each iteration.

Example –
package IO;
import java.util.*;
import static java.lang.System.*;

class ForEachDemo
{
public static void main(String[] args)
{
int a[] = {1, 2, 3, 4, 5};
out.println("Contents of array using conventional method....");
for(int i=0; i<a.length; i++)
out.println(a[i]);
out.println("Contents of array using for each loop...");
for(int x:a)
out.println(x);
}
}

Output –
Contents of array using conventional method....
1
2
3
4
5
Contents of array using for each loop...
1
2
3
4
5

INPUT-OUTPUT [Part - 2]
 java.io.File provides an interface of the File System to a Java Application i.e. using this class a Java Application can find out
File & Folders of a drive, can obtain or change their attributes, can create or remove file or folders etc.

 File object can be created using either of the following constructors:-


public File (String path);
public File (File path, String name);

Let’s consider the given path in the figure below :-


173

 File objects for A.java & A.class can be created as:-


File f1 = new File(“g:\\myJava\\A.java”);
File f2 = new File(“g:\\myJava\\A.class”);
or
File p = new File(“g:\\A.java”);
File f1 = new File(p, “A.java”);
File f2 = new File(p, “A.class”);

 Commonly used methods of File class:-


o getName() method returns the name of the File or Folder.
public String getName();
o getPath() method returns the path of the File or Folder.
public String getPath();
o isDirectory() method returns true if File object represents a folder.
public boolean isDirectory();
o isFile() method returns true if File object represents a file.
public boolean isFile();
o exists() method returns true if File or Folder for the File object exists in the File system.
public boolean exists();
o isHidden() returns true if File object represents a hidden File or Folder.
public boolean isHidden();
o isReadOnly() returns true if File object represents a read-only File or Folder.
public boolean isReadOnly();
o list() method returns the contents of a folder.
public String[] list();
o mkdir() method is used to create a folder.
public boolean mkdir();
o renameTo() method is used to change the name of the File or Folder.
public boolean renameTo();
o etc.
 Define a class NamedList that contains main method which can be provided path of a folder as command line argument.
This class displays the contents of the specified or current folder in the following format.
174

Dated: 21.08.10

Networking

 java.net package provides classes which facilitate development of networking applications in Java.
o Commonly used classes of this package are –
 InetAddress
 Socket
 ServerSocket
 DatagramSocket
 DatagramPacket
o InetAddress class provides object representation of IP Address of machines on a network. This class
doesn‟t provide public constructors rather it provides factory methods for creating its objects.
 Factory is a creational design pattern that is used to control the creation of objects. This design
pattern is implemented with the help of factory classes. A factory class is a class that contains
factory methods.
o A factory method is a method which creates objects.
 Types of Design Patterns
 Creational Design Pattern.
 Structural Design Pattern.
 Behaviour Design Pattern.
 What is Singleton?
o When we create only one object of a class is called singleton.
175

 Following factory methods are provided by InetAddress class-


o getLocalHost() method returns an InetAddress object which represents the IP Address of the current machine.
public Static InetAddress getLocalHost() throws UnknownHostException;

o getName() method returns an InetAddress object which represents IP Address of the given machine.
public static InetAddress getByName(String hostName) throws UnknownHostException;
o getAllByName() method returns an array of InetAddress objects. Each element of the array represents an IP
Address of the given host.
public static InetAddress[] getAllByName(String hostName) throws UnknownHostException;
o getHostName() method returns name of the machine.
public String getHostName();
o getHostAddress() method returns the IP Address as a String.
public String getHostAddress();
o etc.
176

Output -
177

 Socket is a logical end point of a connection.


o From an application programmer‟s point of view, a socket is a process that is used by the Application
Programmer to send or retrieve data over the network.
o This process handles protocol specific details on behalf of Application Developer.
o To facilitate multiplexing of different logical connections over a single physical medium concept of port
was introduced.
o A port is a numbered socket.
o Port Number 0 to 1024 are reserved for standard protocols such as TCP/IP, Http, Ftp, SMTP etc.

 java.net.Socket class represents a TCP/IP socket.


A Socket object can be created using either of the following constructors:-
public Socket (String hostname, int port) throws UnknownHostException, IOException;
public Socket (InetAddress ipAddress, int port) throws UnknownHostException, IOException;

o Methods-
 getInputStream() method returns an InputStream to read data from a Socket.
public InputStream getInputStream();
 getOutputStream() method returns an OutputStream to write data to a Socket.
public OutputStream getOututStream();
 close() method is used to close the Socket.
public void close();
178

 java.netServerSocket class represents the functionality of a TCP/IP server.


 A TCP/IP server is responsible for receiving & completing TCP/IP connection requests.
179

 A ServerSocket object can be created using either of the following constructor.


public ServerSocket(int port);
public ServerSocket(int port, int maxQueueLength);

Methods-
o accept() method is used to instruct TCP/IP server to start listening connection request.
This method blocks the TCP/IP server until a connection request is received.
public Socket accept();
o close() is used to close the TCP/IP server.
public void close();
180

Dated : 22.08.10
Program (Server.java)

import java.net.*;
import java.io.*;

class Server
{
public static void main(String[] args)
{
try
{
ServerSocket server = new ServerSocket(2000);
System.out.println("Server is ready, waiting for connection request...");
Socket s = server.accept();
System.out.println("Waiting for message...");
BufferedReader b = new BufferedReader(new InputStreamReader(s.getInputStream()));
String msg = b.readLine();
Thread.sleep(1000);
System.out.println("Following message received : " + msg);
System.out.println("Sending acknowledgement ....");
Thread.sleep(2000);
PrintWriter out = new PrintWriter(s.getOutputStream());
out.println("Hello Client, Your message is received.");
out.flush();
System.out.println("Acknowledgement sent, closing connection....");
Thread.sleep(5000);
System.out.println("Connection closed.");
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Program (Client.java)

import java.net.*;
import java.io.*;

class Client
{
public static void main(String[] args)
{
try
{
181

System.out.println("Client started, sending connection request...");


Thread.sleep(2000);
Socket s = new Socket("localhost", 2000);
Thread.sleep(1000);
System.out.println("Connection completed, sending message...");
PrintWriter out = new PrintWriter(s.getOutputStream());
Thread.sleep(2000);
out.println("Hello Server!");
out.flush();
System.out.println("Message sent, waiting for acknowledgement.....");
BufferedReader b = new BufferedReader(new InputStreamReader(s.getInputStream()));
String msg = b.readLine();
Thread.sleep(1000);
System.out.println("Following acknowledgement received : " + msg);
System.out.println("Closing connection...");
Thread.sleep(5000);
System.out.println("Connection Closed.");
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output-

 DatagramSocket class provides the facility of sending & receiving UDP packets.
182

public DatagramSocket (int port);


Methods-
o send() method is used to send UDP packets.
public void send(DatagramPacket packet);

o receive() method is used to receive UDP packets.


public void receive(DatagramPacket packet);

o close() method is used to close DatagramSocket.


public void close();

 DatagramPacket class provides the object representation of UDP packets.


 Constructors are –
public DatagramPacket (byte[] data, int size, InetAddress hostAddress, int port); // used to send data
public DatagramPacket (byte[] data, int size); // used to receive data

 Methods are –
public byte[] getData();
public InetAddress getHost();
public int getPort();
etc.

Program (UdpSender.java)

import java.net.*;
import java.util.Scanner;
import java.io.*;

class UdpSender
{
public static void main(String[] args)
{
try
{
DatagramSocket sender = new DatagramSocket(3000);
Scanner in = new Scanner(System.in);
while(true)
{
System.out.println("Enter Message, end to terminate...");
String msg = in.nextLine();
if(msg.equals("end"))
break;
DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.length(),
InetAddress.getLocalHost(), 4000);
sender.send(packet);
System.out.println("Successfully sent.");
}
sender.close();
183

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

Program (UdpReceiver.java)

import java.net.*;
import java.io.*;

class UdpReceiver
{
public static void main(String[] args)
{
try
{
DatagramSocket receiver = new DatagramSocket(4000);
System.out.println("Receiver is ready, press ctrl+c to terminate...");
while(true)
{
System.out.println("Waiting for mesaages...");
DatagramPacket packet = new DatagramPacket(new byte[100], 100);
receiver.receive(packet);
String msg = new String(packet.getData());
System.out.println("Following message is received: " + msg.trim());
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output-
184

You might also like