Professional Documents
Culture Documents
1 - Core Java, Package, String, Io, Exception, Multithreading
1 - Core Java, Package, String, Io, Exception, Multithreading
2Core Java
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.
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.
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.
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.
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.
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.
class Identifier
{
Members definition
}
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.
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
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
c:\>java Adder 10 20
class System
{
public PrintStream out;
public static PrintStream out;
-------------
-------------
-------------
}
JVM
JDK
To compress
jar -crf a.jar *
jar -tf a.jar (to see)
jar -xf a.jar (to extract)
15
OUTPUT –
16
Output –
PROGRAM :
static
{
main();
}
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.
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.
PROGRAM Test1.java
class Test1
{
static int a, b;
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.
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
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
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
}
}
Syntax of creating object of a class-
OR
className ReferenceVariable;
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;
int * p;
Now,
22
Now we will write a program RectTest.java to test the program Rectangle.java written above.
Output –
Since variables l and b are declared private so we cannot access it from outside.
24
PROGRAM RectTest.java
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.
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.
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....");
}
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
Output-
29
class AB
{
{
----------
----------
----------
----------
}
public AB()
{
----------
----------
----------
----------
…
…
…
…
}
public AB(int x)
{
----------
----------
----------
----------
…
…
…
…
}
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.
class A
{
int a, b;
static int c;
----------
----------
public static void main(String[] args)
{
A x = new A();
A y = new A();
-------------
-------------
}
}
31
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
{
-------------
-------------
}
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.”);
}
class D
{
static
{
33
System.out.println(“D is loaded.”);
}
-------------------------------------------------------------------------------------------------------
class E
{
static int a = 5;
class E
{
static int a;
static
{
a = 5;
}
----
----
}
-------------------------------------------------------------------------------------------------------
34
class E
{
int a = 5, b=6;
}
}
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.”);
}
After compilation,
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.”);
}
E x = new E();
E y = new E(10);
E z = new E(40, 50);
x.display();
y.display();
z.display();
}
}
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;
}
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.
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
int z;
z = x.value;
x.value = y.value;
y.value = z;
}
}
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.
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 Rational() { }
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
denominator = y.denominator*x.denominator;
return this;
}
/*
static Rational add(Rational x, Rational y)
{
}
*/
}
package StaticConceptualPrograms;
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("");
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("");
Rational z;
System.out.print("Sum of a, b, r & s is : ");
//z = Rational.add(c, t);
//z.display();
}
}
Output -
public Rational() {}
Rational add(Rational r)
{
Rational s = new Rational();
s.p = p * r.q + q * r.p;
s.q = q * r.q;
return s;
}
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("");
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("");
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
Program -
class Test1
{
int a, 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;
}
As understood by JRE
t.display( ); display(t);
this.<memberName>
Example Program -
class Test1
{
int a, b;
Output -
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 ThisTestInMethod()
{
this(2, 3);
System.out.println("Default");
}
public ThisTestInMethod(int x)
{
this(x, 3);
System.out.println("One Parameterized Constructor...");
}
Output –
51
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.
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.
Output -
54
Now, in the same program we will again do some more modifications in the main method. Observe it carefully.
Output -
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
Syntax :-
class Identifier extends BaseClassName
{
Additional methods
Or
Additional dataMembers & methods
}
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.
Syntax –
super(Argument if any);
NOTE: ‘super’ when used in subclass constructor to invoke superclass constructor than it
must be the first statement.
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();
}
}
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.
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.");
}
}
Output -
NOTE : If a class contains only parenthesized constructors then its subclass must
explicitly invoke then using ‘super’.
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
class A
{
public void display()
{
System.out.println("In A.");
}
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
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”.
Solution –
Now as soon as we created a abstract class A, the error message went away.
See the figures below –
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;
}
class C extends A
{
String name;
public C(String n)
{
name = n;
}
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.
Or
interface Identifier
{
static final dataMembers
}
Or
interface Identifier
{
implicit abstract methods
}
Example –
interface Printable
{
void print();
}
Interfaces are implemented by classes.
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.
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.
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:-
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
Has-a Relation
Aggregation represents part and whole relation between objects. In case of aggregation part and whole may have
their independent existence.
Composition represents a stronger has-a relation between objects in which existence of one object depends on
another.
package HasAIsARelation;
class A
int a;
public A(int x)
a=x;
{
77
package HasAIsARelation;
class AB
A a;
int b;
a=new A(x);
b=y;
a.display();
package HasAIsARelation;
class HasATest
x.display();
78
------------------------------------------------X-----------------------------------------------
NESTED/INNER CLASS
A class that is defined within the scope of another class is called nested or inner class.
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
Example –
Program InnerTest.java
package InnerClassOuterClass;
class A
{
private static int a;
static
{
a=5;
System.out.println("A is loaded...");
}
public B(int x)
{
b=x;
}
class InnerTest
{
public static void main(String args[])
{
System.out.println("Initiating static inner class..");
A.B x = new A.B(10);
80
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.
A class that is defined within the scope of another class and is not qualified by static keyword is called NON-
STATIC INNER class.
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.
package InnerClassOuterClass;
class A
private int b;
public A(int x)
b=x;
static
83
a=5;
System.out.println("A is loaded...");
public class B
int c;
public B(int x)
c=x;
}
84
class InnerTest
A x = new A(10);
x.display();
y.display();
Output –
85
Syntax of creating object of non-static inner class outside the scope of outer class:-
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:
b. Constructor of inner class is modified to receive an extra parameter of type outer class.
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.
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.
package p2;
package p1;
{
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;
package p2;
public class C
{
public static void main(String args[])
{
B x = new B();
x.show();
x.display(); //Compilation error
}
}
package p2;
----------------------------------------------X-----------------------------------------------
Now,
package p2;
{
System.out.println(“Show of subclass invoked.”);
}
----------------------------------------------X-----------------------------------------------
package p2;
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.
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
NOTE : If generalized as well as specific Exception handler are associated to a catch block then
generalized exception handler must be the last one.
Output-
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.
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);
}
}
}
NOTE: When branching instructions are executed in finally then these branching instructions
nullifies
other branching instructions executed in the method before finally.
package ExceptionHandling;
public InvalidAgeException()
{
message = "Age range is 18 to 60";
}
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
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";
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.)
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 –
return +ve integer if invoking String comes after parameter String, -ve integer otherwise.
0 if both strings are same.
Example -
118
Example –
Example –
10. toUpperCase() & toLowerCase() methods are used for converting the contents in Upper & Lower case
respectively.
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
1. append ( ) method is used to append a primitive value or contents of a string to the StringBuffer.
Example –
124
2. insert( ) method is used to insert a string at the given position in the StringBuffer object.
Example –
125
3. replace( ) method is used to replace part of a StringBuffer object with the given string.
Example –
126
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
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
Explanation –
130
131
MULTITHREADING
132
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.
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
6. start () method is used to start a thread i.e. this method loads the run method as a thread.
public void start();
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.
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
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
Output-
Note:
javap java.lang.Runnable
javap java.lang.Thread
Program
package Multithreading;
{
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));
}
package Multithreading;
public NameReader(MyReader r)
{
reader = r;
}
package Multithreading;
public AddressReader(MyReader r)
{
reader = r;
}
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-
……………………..
……………………..
……………………..
……………………..
……………………..
……………………..
}
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;
package Multithreading;
package Multithreading;
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
b) notify () method is used to send the notification to the thread which is suspended by wait () method.
c) notifyAll () method notifies all the threads which are suspended by the wait() method.
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;
{
if (!produced)
{
System.out.println("Consumer entered Monitor out of turn, Suspending ....");
}
try
{
wait();
}catch(Exception e) {}
package Multithreading;
package Multithreading;
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.
Start
InterruptedException is thrown.
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
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.
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;
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.
o Statements
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.
PROGRAM
“Copier.java”
package IO;
import java.io.*;
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.*;
class Creator
{
public static void main(String[] arr)
{
try
{
BufferedReader b = new BufferedReader(new
InputStreamReader(System.in));
----------------------------------------------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));
}
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.
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.
Application Specific.
System/JRE Specific.
Example
1.
2.
Dated:14.08.10
package IO;
“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"));
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
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
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.
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
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
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
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
DatagramSocket class provides the facility of sending & receiving UDP packets.
182
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