Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
II – UNIT
1. Procedure Oriented Programming
2. Object Oriented Programming Paradigm
3. Basic Concepts of OOPS
4. Benefits of OOPS
5. Class fundamentals
6. Declaring Objects
7.Assigning Object References
8. Introducing Methods
9. Constructors
10. this keyword
11. Garbage Collection
12. finalize ( ) Method
13. Overloading Methods
14. Object as parameters
15. Returning Objects
16. Access Control
17. static and final keyword
18. Nested classes and Inner Class
19. Classes with Command Line
arguments
20.Packages
21.Enums in Java
1
PROCEDURE ORIENTED PROGRAMMING
1. In Procedural programming, Programmer combines related sequences of
statements into one single place, called procedure.
2. A procedure call is used to invoke the procedure.
3. After the sequence is processed, flow of control proceeds right after the
position where the call was made.
4. But the approach in oops is that classes and objects are used to model real
world entity taking help of methods which performs the functions.
5. This technique is also known as Top – down programming
OBJECT ORIENTED PROGRAMMING PARADIGM
1. The major objective of object oriented approach is to eliminate some of the
flaws encountered in the procedural approach.
2. OOP treats data as a critical element to the program development and does
not allow it to flow freely around the system.
3. It ties data more closely to the function that operate on it an protects it2from
unintentional modification by other functions.
4. OOP allows us to decompose a problem into a number of entities called
Objects and then build data and functions (known as methods in Java)
around these entities.
5. The combination of data and methods make up an object
Methods
Methods
Data
Methods
Methods
Object = Data + Methods
6. The data of an object can be accessed only by the methods associated with
that object.
3
7. However, methods of one object can access the methods of other object.
Procedural vs. Object-Oriented
Procedural
Withdraw, deposit, transfer
Object-Oriented
Customer, money, account
4
Procedural vs. Object-Oriented –
Contd.,
• Real world Objects are mapped to
software in OOPs
• Objects in the problem domain are
mapped to objects in software
Questions
• What are Objects?
• What are Classes?
• What are Messages?
Answers
• Objects reflect instances that embody those concepts.
• Classes reflect concepts.
• Messages are communication between objects.
object
Rita
class
Gita
Sita
Mita
What are Objects?
• “An object is a software bundle of variables and related methods”
• Software objects are model real-world objects or abstract concepts
• Real-world objects have states and behaviors
– Dogs' states: name, color, breed, hungry
– Dogs' behaviors: barking fetching
• Software objects implement real-world objects by:
– Using variables to implement states
– Using methods to implement behaviors
Visual Representation of a
Software Object
8. Some of the features of object oriented paradigm are:
•
Emphasis is on data rather than procedure.
•
Programs are divided into what are known as Objects.
•
Data Structures are designed such that they characterize the objects.
•
Methods that operate on the data of an object are tied together in the
data structure.
•
Data is hidden and cannot be accessed by external functions.
•
Objects may communicate with each other through methods.
•
New data and methods can be easily added whenever necessary.
•
Follows bottom – up approach in program design.
9. Our definition of object oriented programming is: Object oriented
programming is an approach that provides a way of modularizing
programs
by creating partitioned memory area for both data and function that
can be
used as templates for creating copies of such modules on demand.
10
BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING
1. Class
2. Objects
3. Data Abstraction
4. Data Encapsulation
5. Data Hiding
6. Inheritance
7. Polymorphism
8. Dynamic Binding
9. Message Communication
1. Class
The entire set of data and code of an object can be made a user – defined data
type using the concept of a class. A class may be thought of as a ‘data type’ and an
object as a ‘variable’ of that data type. Once a class has been defined, we can create
any number of objects belonging to that class. Each object is associated with the
data of type class with which they are created. A class is thus a collection of objects
of similar type.
2. Objects
Objects are the basic runtime entities in an object – oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the
program may handle. They may also represent user – defined data types such as
11 the
vectors and lists. Any programming problem is analyzed in terms of objects and
nature of communication between them.
What are Classes?
• A class is a blueprint or prototype defining the
variables and methods common to all objects of a
certain kind.
• An object is an instance of a certain class.
• After you have created a class, you must create
an instance of it before you can use.
• The benefit of Classes: Reusability
• A class captures the common properties of the
objects instantiated from it
• A class characterizes the common behavior of all
the objects that are its instances
Person
Object
Name
Data
BasicPay
Salary()
Methods
Tax()
Representation of an object
3. Data Abstraction, 4. Data Encapsulation and 5. Data Hiding
The wrapping up of data and methods into a single unit is known as
encapsulation. Data encapsulation is the most striking feature of a class. The data is not
accessible to the outside world and only those methods, which are wrapped in the class,
13 the
can access it, these methods provide the interface between the object’s data and
program,
This insulation of the data from direct access by the program is called data hiding.
Encapsulation makes it possible for objects to be treated like ‘black boxes’, each
performing a specific task without any concern for internal implementation.
Information “in”
Data
And
Method
Information “out”
Abstraction refers to the act of representing essential features without including the
background details or explanations. Classes use the concept of abstraction and are
defined as a list of abstract attributes such as size, weight and cost, and methods that
operator on these attributes, They encapsulate all the essential properties of the objects
that are to be created.
6. Inheritance
Inheritance is the process by which objects of one class acquire the properties
of objects of another class. Inheritance supports the concept of hierarchical
classification. In OOP, the concept of inheritance provides the idea of reusability. This
means that we can add additional features to an existing one. The new class will have
the combined features of both the classes.
14
Thus the real appeal and power of the inheritance mechanism is that it allows the
programmer to reuse a class that is almost, but not exactly, what he wants, and to tailor
the class in such a way that it does not introduce any undesirable side effects into the
rest of the classes. In java, the derived class is known as ‘subclass’
Bird
Attributes:
Feathers
Lay eggs
Flying Bird
Non FlyingBird
15
7. Polymorphism
Polymorphism is another important OOP concept. Polymorphism means the
ability to take more than one form. For example, an operation may exhibit different
behaviour in different instances. The behaviour depends upon the types of data used in
the operation. For example consider the operation of addition. For two number, the
operation will generate a sum. If the operands are strings, then the operation would
produce a third string by concatenation. Consider the following example:
Shape
Draw()
Circle Object
Box Object
Triangle Object
Draw(circle)
Draw(box)
Draw(triangle)
Polymorphism plays an important role in allowing objects having different
interval structures to share the same external interface. This means that a general class
of operations may be accessed in the same manner even though specific actions
associated with each operation may differ. Polymorphism is extensively used
in
16
implementing inheritance.
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at runtime. It is associated with
polymorphism and inheritance. A procedure call associated with a polymorphic reference
depends on the dynamic type of that reference.
Message Communication
An object – oriented program consists of a set of objects that communicate with
each other. The process of programming in an object – oriented language, therefore,
involves the following basic steps:
1. Creating classes that define objects and their behaviour
2. Creating objects from class definitions.
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information
much the same way as people pass messages to one another. The concept of message
passing makes it easier to talk about building systems that directly model or simulate
their real world counterparts.
17
Network of objects communicating between them
Object 1
Object 5
Object 2
Object 3
Object 4
18
Benefits of OOPS
1. Through inheritance, we can eliminate redundant code and extend the use of
existing classes.
2. We can build programs from the standard working modules that
communicate with one another, rather than having to start writing the code
from scratch. This leads to saving of development time and higher
productivity.
3. The principle of data binding helps the programmer to build secure programs
that cannot be invaded by code in other parts of the program.
4. It is possible to map objects in the problem domain to those objects in the
program.
5. It is possible to have multiple objects to coexist without any interference.
6. It is easy to partition the work in a project based on objects.
7. The data – centered design approach enables us to capture more details of
a model in an implementable form.
8. Object – Oriented systems can be easily upgraded from small to large
systems.
9. Message passing techniques for communication between objects make the
19
interface descriptions with external systems much simpler.
Application of OOPS
1. Real – time systems.
2. Simulation and modelling.
3. Object – oriented databases.
4. Hypertext, hypermedia and expertext.
5. AI and expert systems.
6. Neural networks and parallel programming.
7. Decision support.
8. Office automation systems.
9. CIM / CAD / CAM system.
20
The Java Buzzwords or Java Features or Java Characteristics
■ Simple
■ Secure
■ Portable
■ Object-oriented
■ Robust
■ Multithreaded
■ Architecture-neutral
■ Interpreted
■ High performance
■ Distributed
■ Dynamic
21
Methods Introductions
22
Introduction
• Methods are nothing but function.
• It is a set of statements which can be included in java
class.
• It can be called at any point in java class by simply
calling method name.
• Methods have so much of power and flexibility.
• Methods should be declared in the class.
• It can be public, private, and protected.
• Methods are of two types, one is with argument and
another is without argument.
23
Types of Methods
• Methods are used to access the data
fields in a class
• These methods are linked with the objects
• Class creates an object using new
keyword, and this object can be used for
calling the methods.
• An instance method is called by prefixing
it with an object
24
• Methods can be declared using various types such as
1. Return type method -returns value or does not return any
values (void).
2. Modifiers – it is public private, and protected
3. Parameter – it should be listed in parentheses,().
4. Method body – declare between braces
• Method declaration
• static - class method, no need to create class
reference
• final - method cannot be overridden
• abstract - method is not implemented in another cl
• ass/method
25
Empty Method
class emptymethod {
int i,j,k;
void method1() {
i=10;
j=10;
k=i*j;
System.out.println(" Result k is:"+k);}
public static void main(String args[])
{
emptymethod e=new emptymethod();
e.method1();
}}
• Output :
• Result K is 100
26
Method using argument
class argument {
int i;
String st;
void meth(int a, String s) {
int i=a;
String st=s;
System.out.println("Employee Id:"+i);
System.out.println("Employee Id:"+st); }
public static void main(String args[])
{
argument obj=new argument();
obj.meth(5001,"Kumar"); }}
27
Methods using return keyword
class example {
int c;
int add(int a, int b) {
return a+b; }
int subtract(int a, int b){
return a-b;}
int multiply(int a, int b){
return a*b;}
int division(int a, int b) {
return a/b; }}
class returnexa {
public static void main(String[]
args) {
example obj= new example();
obj.add(10,20);
System.out.println("Addition: "
+obj.add(30,15));
System.out.println("Subtraction: "
+obj.subtract(30,15));
System.out.println("Multiplication:
" +obj.multiply(30,15));
System.out.println("Division: " +
obj.division(30,15)); }}
28
CLASS FUNDAMENTALS
29
The General Form of a Class
Class contains data and the code that operates on that data.
While very simple classes may contain only code or only data, most real-world classes
contain both.
A class is declared by use of the class keyword. The general form of a class definition
is shown here:
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}
30
// APPLICATION OF CLASSES AND OBJECTS
using System;
class Rectangle
{
public int length, width;
public void GetData(int x,int y)
{
length = x;
width = y;
}
public int RectArea ()
{
int area = length * width;
return (area);
}
}
class RectArea
{
public static void Main()
{
int area1,area2;
Rectangle rect1 = new Rectangle ();
Rectangle rect2 = new Rectangle ();
rect1.length = 15;
rect1.width = 10;
area1 = rect1.length * rect1.width ;
rect2.GetData (20,10);
area2 = rect2.RectArea ();
System.out.println("Area1 = " + area1);
System.out.println("Area2 = " + area2);
}
}
31
Assigning Object Reference Variables
Object reference variables act differently than you might expect when an
assignment takes place. For example, what do you think the following fragment does?
Box b1 = new Box();
Box b2 = b1;
You might think that b2 is being assigned a reference to a copy of the object referred to
by b1. That is, you might think that b1 and b2 refer to separate and distinct objects.
However, this would be wrong. Instead, after this fragment executes, b1 and b2 will both
refer to the same object. The assignment of b1 to b2 did not allocate any memory or
copy any part of the original object. It simply makes b2 refer to the same object as does
b1. Thus, any changes made to the object through b2 will affect the object to which b1 is
referring, since they are the same object. This situation is depicted here:
Although b1 and b2 both refer to the same object, they are not linked in any other way.
For example, a subsequent assignment to b1 will simply unhook b1 from the original
object without affecting the object or affecting b2. For example:
Box b1 = new Box();
Box b2 = b1;
// ...
32
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.
ADDING METHODS
class Box
{
double width;
double height;
double depth;
// display volume of a box
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3
{
public static void main(String args[]
{
Box mybox1 = new Box();
Box mybox2 = new Box();
33
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume();
// display volume of second box
mybox2.volume();
}
}
34
Returning a Value
class Box
{
double width;
double height;
double depth;
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class BoxDemo4
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
35
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
36
Adding a Method That Takes Parameters
class Box
{
double width;
double height;
double depth;
// compute and return volume
double volume()
{
return width * height * depth;
}
// sets dimensions of box
void setDim(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
}
37
class BoxDemo5
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// initialize each box
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
38
Constructors
class Box
{
double width;
double height;
double depth;
// This is the constructor for Box.
Box()
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
39
class BoxDemo6
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
40
Parameterized Constructors
class Box
{
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
41
class BoxDemo7
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
42
The this Keyword
Sometimes a method will need to refer to the object that invoked it. To allow
this, Java defines the this keyword. this can be used inside any method to refer to the
current object. That is, this is always a reference to the object on which the method was
invoked. You can use this anywhere a reference to an object of the current class’ type is
permitted. To better understand what this refers to, consider the following version of
Box( ):
// A redundant use of this.
Box(double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
Garbage Collection
Since objects are dynamically allocated by using the new operator, you might
be wondering how such objects are destroyed and their memory released for later
reallocation. In some languages, such as C++, dynamically allocated objects must be
manually released by use of a delete operator. Java takes a different approach; it
handles deallocation for you automatically. The technique that accomplishes 43
this is
called garbage collection.
The finalize( ) Method
The constructor method is used to initialize an object when it is declared. This process is
known as initalisation. Similarly, Java supports a concept called finalization, which is just
opposite to initialization. We know that java run – time is an automatic garbage collecting
system. It automatically frees up the memory resources used by the objects. But objects
may hold other non – object resources such as file descriptors or window system fonts.
The garbage collector cannot free these resources. In order to free resources we must
use a finaliser method. This is similar to destructor in C++.
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
44
Overloading Methods
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a)
{
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
}
45
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
46
Overloading Constructors
class Box
{
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
47
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class OverloadCons
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
48
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
49
Using Objects as Parameters
// Objects may be passed to methods.
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o)
{
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb
{
public static void main(String args[])
{
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
50
Returning Objects
// Returning an object.
class Test
{
int a;
Test(int i)
{
a = i;
}
Test incrByTen()
{
Test temp = new Test(a+10);
return temp;
}
}
class RetOb
{
public static void main(String args[])
{
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: “ + ob2.a);
}
}
51
ACCESS CONTROL
Access Specifier
Accessing Level
private
Same Class in Same Package
private protected
Sub Class in Same Package
friendly (not a keyword
Non – Sub Class in Same Package
protected
Sub Class in Other Package
public
Other Class in Other Package
class Test
{
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i)
// set c's value
{
c = i;
}
int getc()
// get c's value
{
return c;
}
}
52
class AccessTest
{
public static void main(String args[])
{
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc());
}
}
53
Understanding static
There will be times when you will want to define a class member that will be used
independently of any object of that class. Normally a class member must be accessed
only in conjunction with an object of its class. However, it is possible to create a member
that can be used by itself, without reference to a specific instance. To create such a
member, precede its declaration with the keyword static. When a member is declared
static, it can be accessed before any objects of its class are created, and without
reference to any object. You can declare both methods and variables to be static. The
most common example of a static member is main( ). main( ) is declared as static
because it must be called before any objects exist. Instance variables declared as static
are, essentially, global variables. When objects of its class are declared, no copy of a
static variable is made. Instead, all instances of the class share the same static
variable.
Methods declared as static have several restrictions:
■ They can only call other static methods.
■ They must only access static data.
■ They cannot refer to this or super in any way.
54
class UseStatic
{
static int a = 3;
static int b;
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[ ])
{
meth(42);
}
}
55
Nested and Inner Classes
It is possible to define a class within another class; such classes are known as
nested classes. The scope of a nested class is bounded by the scope of its enclosing
class. Thus, if class B is defined within class A, then B is known to A, but not outside of
A. A nested class has access to the members, including private members, of the class in
which it is nested. However, the enclosing class does not have access to the members
of the nested class.
There are two types of nested classes: static and non-static. A static nested
class is one which has the static modifier applied. Because it is static, it must access
the members of its enclosing class through an object. That is, it cannot refer to members
of its enclosing class directly. Because of this restriction, static nested classes are
seldom used.
The most important type of nested class is the inner class. An inner class is a
non-static nested class. It has access to all of the variables and methods of its outer
class and may refer to them directly in the same way that other non-static members of
the outer class do. Thus, an inner class is fully within the scope of its enclosing class.
56
// Demonstrate an inner class.
class Outer
{
int outer_x = 100;
void test()
{
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner
{
void display()
{
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
}
57
Using Command-Line Arguments
Sometimes you will want to pass information into a program when you run it. This is
accomplished by passing command-line arguments to main( ). A command-line
argument is the information that directly follows the program’s name on the command
line when it is executed. To access the command-line arguments inside a Java program
is quite easy—they are stored as strings in the String array passed to main( ). For
example, the following program displays all of the command-line arguments that it is
called with:
// Display all command-line arguments.
class CommandLine
{
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}
Try executing this program, as shown here:
java CommandLine this is a test 100 -1
When you do, you will see the following output:
args[0]: this
args[1]: is
args[2]: a
args[4]: 100
args[5]: -1
args[3]: test
58
II – UNIT
1. Inheritance
2. Inheritance with Super Keyword
3. Inheritance with Method Overriding
4. Inheritance with Abstract Class
5. Inheritance with Final Keyword
6. Interfaces
7. Packages
8. String Functions
9. StringBuffer Functions
59
INHERITANCE
60
INHERITANCE
What is Inheritance?
Inheritance is the mechanism which allows a class B to inherit properties/characteristicsattributes and methods of a class A. We say “B inherits from A".
A
Super Class or Base Class or Parent Class
B
Sub Class or Derived Class or Child Class
What are the Advantages of Inheritance
1. Reusability of the code.
2. To Increase the reliability of the code.
3. To add some enhancements to the base class.
61
Inheritance achieved in two different forms
1. Classical form of Inheritance
2. Containment form of Inheritance
Classical form of Inheritance
A
Super Class or Base Class or Parent Class
B
Sub Class or Derived Class or Child Class
We can now create objects of classes A and B independently.
Example:
A a;
//a is object of A
B b;
//b is object of B
62
In Such cases, we say that the object b is a type of a. Such relationship between a and b
is referred to as ‘is – a’ relationship
Example
1. Dog is – a type of animal
2. Manager is – a type of employee
3. Ford is – a type of car
Animal
Horse
Dog
Lion
63
Containment Inheritance
We can also define another form of inheritance relationship known as
containership between class A and B.
Example:
class A
{
-------}
class B
{
--------A a;
// a is contained in b
}
B b;
-----------64
In such cases, we say that the object a is contained in the object b. This relationship
between a and b is referred to as ‘has – a’ relationship. The outer class B which contains
the inner class A is termed the ‘parent’ class and the contained class A is termed a ‘child’
class.
Example:
1. car has – a radio.
2. House has – a store room.
3. City has – a road.
Car object
Radio object
65
Types of Inheritance
1. Single Inheritance (Only one Super Class and One Only Sub Class)
2. Multilevel Inheritance (Derived from a Derived Class)
3. Hierarchical Inheritance (One Super Class, Many Subclasses)
1. Single Inheritance (Only one Super Class and Only one Sub Class)
A
B
66
2. Multilevel Inheritance (Derived from a Derived Class)
A
B
C
4. Hierarchical Inheritance (One Super class, Many Subclasses)
A
B
C
D
67
Single Inheritance (Only one Super Class and One Only Sub Class)
//Single Inheritance
class Room
{
protected int length, breadth;
Room()
{
length = 10;
breadth = 20;
}
void Room_Area()
{
System.out.println("The Area of the Room is:" + (length * breadth));
}
}
class HallRoom extends Room
{
int height;
HallRoom()
{
length = 10;
breadth = 20;
height = 30;
}
void HallRoom_Volume()
{
System.out.println("The Valoume of the HallRoom is:" + (length * breadth * height));
68
}
}
class MainRoom
{
public static void main(String [] args)
{
HallRoom hr = new HallRoom();
hr.Room_Area();
hr.HallRoom_Volume();
}
}
69
Multilevel Inheritance (Derived from a Derived Class)
//Multilevel Inheritance
class Room
{
protected int length, breadth;
Room()
{
length = 10;
breadth = 20;
}
void Room_Area()
{
System.out.println("The Area of the Room is:" + (length * breadth));
}
}
class HallRoom extends Room
{
int height;
HallRoom()
{
length = 10;
breadth = 20;
height = 30;
}
void HallRoom_Volume()
{
System.out.println("The Volume of the HallRoom is:" + (length * breadth *
height));
70
}
}
class BedRoom extends HallRoom
{
int height_1;
BedRoom()
{
length = 10;
breadth = 20;
height = 30;
height_1 = 40;
}
void BedRoom_Volume1()
{
System.out.println("The Volume of the the BedRoom is:" + (length *
breadth * height * height_1));
}
}
class MainRoom
{
public static void main(String [] args)
{
BedRoom br = new BedRoom();
br.Room_Area();
br.HallRoom_Volume();
br.BedRoom_Volume1();
}
71
}
Hierarchical Inheritance (One Super Class, Many Subclasses)
//Hierarchical Inheritance
class Room
{
protected int length, breadth, height;
Room()
{
length = 10;
breadth = 20;
height = 30;
}
}
class HallRoom extends Room
{
void HallRoom_Area()
{
System.out.println("The Area of the HallRoom is:" + (length * breadth));
}
}
72
class BedRoom extends Room
{
void BedRoom_Volume()
System.out.println("The Volume of the BedRoom is:" + (length *
breadth * height));
}
}
class MainRoom
{
public static void main(String [] args)
{
HallRoom hr =new HallRoom();
BedRoom br = new BedRoom();
hr.HallRoom_Area();
br.BedRoom_Volume();
}
}
73
INHERITANCE WITH
super KEYWORD
74
The purpose of the ‘super’ keyword:
1. Using super to call Superclass Constructors
2. Using super to call Superclass Methods
1. Using super to Call Superclass Constructor
A Subclass can call a constructor method defined by its superclass by use of
the following form of super:
super (parameter – list)
Here, parameter – list specifies any parameter needed by the constructor in the
superclass, super() must always be the first statement executed inside a subclass
constructor.
Restriction of the Subclass constructor
1. super may only be used within a subclass constructor method.
2. The call to superclass constructor must appear as the first statement
within the subclass constructor
3. The parameters in the super call must match the order and type of
the instance variable declared in the superclass.
75
class Room
{
protected int length, breadth, height;
Room(int length, int breath)
{
this.length = length;
this.breadth = breath;
}
void Room_Area()
{
System.out.println("The Area of the Room is:" + (length * breadth));
}
}
class HallRoom extends Room
{
int height;
HallRoom(int length, int breath, int height)
{
super(length,breath);
this.height = height;
}
void HallRoom_Volume()
{
System.out.println("The Volume of the HallRoom is:" + (length *
breadth * height));
76
}
}
class MainRoom
{
public static void main(String [] args)
{
HallRoom hr =new HallRoom(10,20,30);
hr.Room_Area();
hr.HallRoom_Volume();
}
}
77
//super keyword in Multilevel Inheritance
class Room
{
protected int length, breadth, height;
Room(int length, int breath)
{
this.length = length;
this.breadth = breath;
}
void Room_Area()
{
System.out.println("The Area of the Room is:" + (length * breadth));
}
}
class HallRoom extends Room
{
int height;
HallRoom(int length, int breath, int height)
{
super(length,breath);
this.height = height;
}
void HallRoom_Volume()
{
System.out.println("The Volume of the HallRoom is:" + (length * breadth *
height));
78
}
}
class BedRoom extends HallRoom
{
int height_1;
BedRoom(int length, int breath, int height, int height_1)
{
super(length,breath,height);
this.height_1 = height_1;
}
void BedRoom_Volume_1()
{
System.out.println("The Volume 1 of the BedRoom is:" + (length *
breadth * height * height_1));
}
}
class MainRoom
{
public static void main(String [] args)
{
BedRoom br =new BedRoom(10,20,30,40);
br.Room_Area();
br.HallRoom_Volume();
br.BedRoom_Volume_1();
}
}
79
2. Using super to Call Superclass Method
//super keyword call Super Class Methods
class Room
{
void Room_Super()
{
System.out.println("The Room Base is Displayed");
}
}
class HallRoom extends Room
{
void HallRoom_Intermetiate()
{
System.out.println("The Hall Room is Displayed");
}
}
class BedRoom extends HallRoom
{
void BedRoom_Sub()
{
super.Room_Super();
super.HallRoom_Intermetiate();
System.out.println("The Bed Room is Displayed");
}
}
class MainRoom
{
public static void main(String [] args)
{
BedRoom br = new BedRoom();
br.BedRoom_Sub();
80
Inheritance
with
Method Overriding
81
1. Method overriding in java means a subclass method overriding a super
class method.
2. Superclass method should be non-static.
3. Subclass uses extends keyword to extend the super class.
4. In the example class B is the sub class and class A is the super class.
5. In overriding methods of both subclass and superclass possess same
signatures.
6. Overriding is used in modifying the methods of the super class.
7. In overriding return types and constructor parameters of methods
should match.
82
//Method Overriding
class Room
{
void Room_Super()
{
System.out.println("The Room Base is Displayed");
}
}
class HallRoom extends Room
{
void Room_Super()
{
System.out.println("The Sub Class Room Base is Displayed");
}
}
class MainRoom
{
public static void main(String [] args)
{
HallRoom br = new HallRoom();
br.Room_Super();
}
}
83
Super Keyword in Method Overriding
If your method overrides one of its super class's methods, you can invoke the
overridden method through the use of the keyword super. You can also use super to
refer to a hidden field (although hiding fields is discouraged).
//Super keyword in Method Overriding
class Room
{
void Room_Super()
{
System.out.println("The Room Base is Displayed");
}
}
class HallRoom extends Room
{
void Room_Super()
{
System.out.println("The Sub Class Room Base is Displayed");
super.Room_Super();
}
}
class MainRoom
{
public static void main(String [] args)
{
HallRoom br = new HallRoom();
br.Room_Super();
}
}
84
Inheritance with Abstract Class
85
Abstract Class
You can require that certain methods be overridden by subclasses by specifying the
abstract type modifier. These methods are sometimes referred to as subclasser
responsibility because they have no implementation specified in the super class . Thus,
a subclass must override them – it cannot simply use the version defined in the
superclass. To declare an abstract method, use this general form:
abstract type name (parameter – list)
Any class that contains one or more abstract methods must also be declared
abstract. To declare a class abstract, you simply use the abstract keyword in from of
the class keyword at the beginning of the class declaration.
Conditions for the Abstract Class
1. We cannot use abstract classes to instantiate objects directly. For
example. Shape s = new Shape(); is illegal because shape is an
abstract class.
2. The abstract methods of an abstract class must be defined in its
subclass.
3. We cannot declare abstract constructors or abstract static methods.
86
//Abstract Class Implementation
abstract class A
{
abstract void callme( );
// Abstract Method
void callmetoo( )
// Concrete Method
{
System.out.println("This is a Concrete method");
}
}
class B extends A
{
void callme( )
//Redefined for the Abstract Method
{
System.out.println("B's Implementation of Callme");
}
}
class MainRoom
{
public static void main(String [] args)
{
B b = new B( );
}
b.callme( );
b.callmetoo( );
}
87
Inheritance with
final Keyword
88
What is the purpose of final keyword?
1. Can’t initialize to variable again and again (Equivalent to Constant)
2. Can’t Method Overriding
3. Can’t Inherited
1. Can’t initialize to variable again and again (Equivalent to Constant)
class Final
{
public static void main(String args[])
{
final int a = 45;
a = 78; //cannot assign the value to final Variable
System.out.println("The A Value is:" + a);
}
}
89
2. Can’t Method Overriding
class Super
{
final void Super_Method()
{
System.out.println("This is Super Method");
}
}
class Sub extends Super
{
//Super method in sub cannot override Super_Method() in super; Overridden
//method is final
void Super_Method()
{
System.out.println("This is Sub Method");
}
}
class Final
{
public static void main(String args[])
{
Sub s = new Sub();
s.Super_Method();
90
}
}
3. Can’t Inherited
final class Super
{
void Super_Method()
{
System.out.println("This is Super Method");
}
}
class Sub extends Super
//cannot inherit from final super
{
void Super_Method()
{
System.out.println("This is Sub Method");
}
}
class Final
{
public static void main(String args[])
{
Sub s = new Sub();
s.Super_Method();
}
}
91
Quiz What is the output of this program?
class A {
int i;
void display() {System.out.println(i);}}
class B extends A {int j;
void display() {System.out.println(j);}}
class inheritance_demo {
public static void main(String args[]){
B obj = new B();obj.i=1;obj.j=2; obj.display();
}}
92
Quiz What is the output of this program?
class A { int i; }
class B extends A {
int j;
void display() {super.i = j + 1;
System.out.println(j + " " + i);} }
class inheritance {
public static void main(String args[]){
B obj = new B();obj.i=1;obj.j=2; obj.display(); }}
93
Quiz What is the output of this program?
class A {
public int I;public int j;
A() { i = 1;j = 2;}}
class B extends A {
int a;
B() { super(); } }
class super_use {
public static void main(String args[]){
B obj = new B();
System.out.println(obj.i + " " + obj.j) } }
94
Interface
95
Why are you using Interface?
1. Java does not support multiple inheritances. That is, classes in java cannot
have more than one superclass. For instances,
class A extends B extends C
{
------------------------------------}
2. a is not permitted in Java. However, the designers of java could not overlook
the importance of multiple inheritances.
3. A large number of real life applications require the use of multiple
inheritances whereby we inherit methods and properties from several distinct
classes.
4. Since C++ like implementation of multiple inheritances proves difficult and
adds complexity to the language, Java provides an alternate approach
known as interfaces to support the concept of multiple inheritances.
5. Although a java class cannot be a subclass or more than one superclass, it
can implement more than one interface, thereby enabling us to create
classes that build upon other classes without the problems created by
multiple inheritances.
96
Defining Interfaces
An interface is basically a kind of class. Like classes, interfaces contain
methods and variables but with major difference. The difference is that interfaces define
only abstract methods and final fields. This means that interfaces do not specify any
code to implement these methods and data fields contain only constants.
Syntax:
interface Interface_name
{
Variable declaration;
Method declaration;
}
Ex:
interface Item
{
static final int code = 1001;
static final String name = “CCET”;
void display ();
}
Ex:
interface Area
{
final static float pi = 3.142F;
float compute (float x,float y);
void show();
}
97
How to Interface implements to the Classes
Syntax:
class class_name implements interface_name
{
//Member of the Classes
//Definition of the Interfaces
}
Ex:
interface student
{
int slno = 12345;
String name = "CCET";
void print_details();
}
class Inter_Def implements student
{
void print_details()
{
System.out.println("The Serial Number is:" + slno);
System.out.println("The Student name is:" + name);
98
}
}
Difference between Abstract Classes and Interfaces
Abstract classes
Interfaces
Abstract classes are used only when there
is a “is-a” type of relationship between the
classes.
Interfaces can be implemented by classes
that are not related to one another.
You cannot extend more than one abstract
class.
You can implement more than one
interface.
it contains both abstract methods and non
Abstract Methods
Interface contains all abstract methods
Abstract class can implemented some
methods also.
Interfaces can not implement methods.
With abstract classes, you are grabbing
away each class’s individuality.
With Interfaces, you are merely extending
each class’s functionality.
99
Difference between Classes and Interfaces
1. Interface is little bit like a class... but interface is lack in instance variables....that's u
can't create object for it.
2. Interfaces are developed to support multiple inheritances.
3. The methods present in interfaces are pure abstract.
4. The access specifiers public, private, protected are possible with classes. But the
interface uses only one spcifier public
5. Interfaces contain only the method declarations.... no definitions.......
6.
In Class the variable declaration as well as initialization, but interface only for
initializing.
100
Types of Interfaces
A
Interface
A
Class
D
Interface
Implementation
Extension
B
Extension
Class
Implementation
B
Extension
C
Class
Class
E
Interface
Extension
C
A
Class
Interface
Implementation
B
Class
C
Class
101
Interface
A
B
Interface
Extension
C
Interface
Implementation
D
Class
102
// HIERARICHICAL INHERITANCE USING INTERFACE
interface Area
{
final static float pi = 3.14F;
float compute (float x,float y);
}
class Rectangle implements Area
{
public float compute(float x,float y)
{
return (x * y);
}
}
class Circle implements Area
{
public float compute(float x,float y)
{
return (pi * x * x);
}
}
A
Interface
Implementation
B
Class
C
Class
103
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect = new Rectangle ();
Circle cir = new Circle();
Area area;
//Interface object
area = rect;
System.out.println("Area of Rectangle = " + area.compute(10,20));
area = cir;
System.out.println("Area of Circle = " + area.compute(10,0));
}
}
104
//HYBRID INHERITANCE USING INTERFACES
class Student
{
int rollnumber;
void getnumber(int n)
{
rollnumber = n;
}
void putnumber()
{
System.out.println("Roll No: " + rollnumber);
}
}
class Test extends Student
{
float part1, part2;
void getmarks(float m1,float m2)
{
part1 = m1;
part2 = m2;
}
void putmarks()
{
System.out.println("Marks obtained");
System.out.println("Part1 = " + part1);
System.out.println("Part2 = " + part2);
}
}
Class
A
Interface
Extension
Class
B
D
Extension
Implementation
Class
C
105
interface Sports
{
float sportwt = 6.0F;
void putwt();
}
class Results extends Test implements Sports
{
float total;
public void putwt()
{
System.out.println("Sports Wt = " + sportwt);
}
void display()
{
total = part1 + part2 + sportwt;
putnumber();
putmarks();
putwt();
System.out.println("Total Score = " + total);
}
}
106
class Hybrid
{
public static void main(String args[])
{
Results stud = new Results();
stud.getnumber(1234);
stud.getmarks(27.5F, 33.0F);
stud.display();
}
}
107
What is Partial Implementation?
The Interface is implementation to the Abstract class is called Partial
Implementation.
Example:
interface Partial_Interface
{
public void display_one();
}
abstract class Abstract_Class implements Partial_Interface
{
public void display_one()
//Definition for the Interface Method
{
System.out.println("This is Interface Method");
}
void display_two()
//Concrete Method
{
System.out.println("This is Concrete Method");
}
abstract void display_three();
}
//Abstract Method
108
class Pure_Class extends Abstract_Class
{
void display_three()
//Definition for the Abstract Method
{
System.out.println("This is Abstract Method");
}
}
class Final
{
public static void main(String args[])
{
Pure_Class pc = new Pure_Class();
pc.display_one();
pc.display_two();
pc.display_three();
}
}
109
Package
110
What is Packages?
Packages are java’s way of grouping a variety of classes and / or interfaces
together. The grouping is usually done according to functionality. In fact, packages act as
“containers” for classes.
What are the benefits of Packages?
1. The classes contained in the packages of other programs can be easily
reused.
2. In packages, classes can be unique compared with classes in other
packages. That is, two classes in two different packages can have the same
name. They may be referred by their fully qualified name, comprising the
package name and class name.
3. Packaged provide a way to “hide classes thus preventing other programs or
package from accessing classes that are meant for internal use only.
4. Packages also provide a way for separating “design” from “coding”. First we
can design classes and decide their relationships, and then we can
implement the java code needed for the methods. It is possible to change the
implementation of any method without affecting the rest of the design. 111
Types of Packages
Java packages are therefore classified into two types.
1. Pre – defined packages (Java API Packages)
2. User – defined packages
1.Java API Packages
Package Name
Contents
java.lang
Language support classes. These are classes that java compiler itself uses and
therefore they are automatically imported. They include classes for primitive types,
strings, math functions, threads and exceptions
java.util
Language utility classes such as vectors, hash tables, random numbers, date, etc.
java.io
Input / Output support classes. They provide facilities for the input and output of
data.
java.awt
Set of classes for implementing graphical user interface. They include classes for
windows, buttons, lists, menus and so on.
java.net
Classes for networking. They include classes for communicating with local
computers as well as with internet servers.
java.applet
Classes for creating and implementing applets.
112
2. USER DEFINED PACKAGES
How to Creating our own Packages
Creating our own package involves the following steps:
1. Declare the package at the beginning of a file using the form
package package_name;
2. Define the class that is to be put in the package and declare it public
3. Create a subdirectory under the directory where the main source files are
stored.
4. Store the listing as the classname.java file in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory.
6. The subdirectory name must match the package name exactly.
Note:
Java also supports the concept of package hierarchy. This done by
specifying multiple names in a package statement, separated by dots.
Example:
package firstPackage.secondpackage;
113
Example:
Create Package:
package package1;
public class ClassA
{
public void displayA()
{
System.out.println("Class A");
}
}
How to import the package:
import package1.ClassA;
class PackageTest1
{
public static void main(String args[])
{
ClassA objectA = new ClassA()
objectA.displayA();
}
}
114
ACCESS PROTECTION
Access Modifier
Access Location
Public
Protected
friendly
(default)
private protected
private
Same Class
Yes
Yes
Yes
Yes
Yes
Subclass in same
package
Yes
Yes
Yes
Yes
No
Other classes in
same
package
Yes
Yes
Yes
No
No
Subclass in other
package
Yes
Yes
No
Yes
No
Non – subclasses
in other
packages
Yes
No
No
No
No
115
Example program for the above Access Protection Tabular
Protection.java:
package p1;
public class Protection
{
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
116
This is file Derived.java:
package p1;
class Derived extends Protection
{
Derived()
{
System.out.println("derived constructor");
System.out.println("n = " + n);
//System.out.println("n_pri = " + n_pri); //Cannot Access because
//accessing level is same class
//in same package
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
117
This is file SamePackage.java:
package p1;
class SamePackage
{
SamePackage()
{
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);
//System.out.println("n_pri = " + p.n_pri); //Cannot Access because
//accessing level is same
//class in same package
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
118
This is file OtherPackage.java:
package p2;
class Protection2 extends p1.Protection
{
Protection2()
{
System.out.println("derived other package constructor");
// System.out.println("n = " + n);
//Cannot Access because
//accessing level is non – sub
//class same class
// System.out.println("n_pri = " + n_pri); //Cannot Access because
//accessing level is same
//class in same package
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
119
This is file OtherPackage.java:
package p2;
class OtherPackage
{
OtherPackage()
{
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// System.out.println("n = " + p.n);
// Cannot access because the
// accessing level is non – sub
// class in same package
// System.out.println("n_pri = " + p.n_pri);
// Cannot access
// because the accessing
// level is same class in
// same package
// System.out.println("n_pro = " + p.n_pro);
// Cannot access
// because the accessing
// level is sub – class in
// other package
System.out.println("n_pub = " + p.n_pub);
}
}
120
String
functions
121
SPECIAL STRING OPERATIONS
1. Automatic creation of new String instances from string literals.
2. Concatenation of multiple String object by used of the + operators
3. Conversion of other data types to a string representation.
1. String Literals
class String_Operation
{
public static void main(String args[])
{
char chars [ ] = {'a', 'b', 'c'};
String s1 = new String(chars);
String s2 = "Chettinad";
//Use String Literals, Java automatically
//constructs a String object
System.out.println("The Displayed String_1 is:" + s1);
System.out.println("The Displayed String_2 is:" + s2);
System.out.println("The Length of the String is: " +
"Chettinad".length());
}
}
122
2. String Concatenation
class String_Operation
{
public static void main(String args[])
{
String age = " 9 ";
String s = "He is" + age + "Years old.";
//Java does not allow ( +
// )operators to be
// applied to String
// objects.
System.out.println(s);
}
}
123
3. String Concatenation with Other Data Types
class String_Operation
{
public static void main(String args[])
{
int age = 9;
String s1 = "He is " + age + " Years old. ";
// The int value in age is
// automatically
// converted into its string
// representation within a
//String object.
System.out.println(s1);
String s2 = "four: " + 2 + 2;
System.out.println(s2);
String s3 = "four: " + (2 + 2);
System.out.println(s3);
}
}
124
4. String Conversion and toString()
To implement toString(), simply return a String object that contains the human readable
string.
class Box
{
double width;
double height;
double depth;
Box(double w,double h,double d)
{
width = w;
height = h;
depth = d;
}
public String toString()
{
return "Dimensions are " + width + " by " + depth + " by " + height + ".";
}
}
125
class String_Operation
{
public static void main(String args[])
{
Box b = new Box(10, 12, 14);
String s = "Box b: " + b;
// Concatenate Box object
System.out.println(b);
System.out.println(s);
}
}
126
CHARACTER EXTRACTION
The String class provides a number of ways in which characters can be
extracted form a String object. That is Character Extraction.
1. charAt()
Syntax:
char charAt(int where)
class String_Operation
{
public static void main(String args[ ])
{
char ch;
ch = "Chettinad".charAt(4);
System.out.println("The 4 Character is:" + ch);
}
}
127
2. getChars()
If you need to extract more than one character at a time, you can use
the getChars() method.
Syntax:
void getChars(int sourceStart,int sourceEnd,char target [ ],int targetStart)
class String_Operation
{
public static void main(String args[])
{
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf [ ] = new char[end - start];
s.getChars(start,end,buf,0);
System.out.println(buf);
}
}
128
3. getBytes()
There is an alternative to getChars() that stores the character in an array of
bytes. This method is called getBytes(), and it uses the default character-to-byte
conversions provided by the platform.
Here is its simplest form:
byte [] getBytes();
Other forms of getBytes are also available. getBytes is most useful when you
are exporting a String value into an environment that does not support 16 - bit unicode
character. For example, most Internet protocols and text file formats use 8 - bit ASCII for
all text interchage.
class String_Operation
{
public static void main(String args[])
{
String msg="HelloWorld";
byte b[ ]=msg.getBytes();
System.out.println("The Character in array of Bytes is: " + b);
}
}
129
4. toCharArray()
If you want to convert all the characters in a String object into a character array,
the easiest way is to call toCharArray(). It returns an array of characters for the entire
string.
It has this general form:
char [ ] toCharArray()
This function is provided as a convenience, since it is possible to use
getChars() to achieve the same result.
class String_Operation
{
public static void main(String args[])
{
String str = "einstein relativity concept is still a concept of great
discussion";
char heram[ ] = str.toCharArray();
System.out.print("Converted value from String to char array is: ");
System.out.println(heram);
}
}
130
STRING COMPARISON
1. equals() and equalsIgnoreCase()
To compare two strings for equality, use equals()
Syntax:
boolean equals(Object str)
Here, str is the String object being compared with the invoking String
object. It returns true if the strings contain the same characters in the same order,
and false otherwise. The comparison is case - sensitive.
To perform a comparison that ignores case differences, call equalsIgnoreCase().
When it compares two string, it considers A - Z to be the same as a - z.
Syntax:
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the invoking String
object. It, too, returns true if the strings contain the same characters in the same
order, and false otherwise.
131
class String_Operation
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good - Bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
}
}
132
2. regionMatches()
The regionMatches() method compares a specific region inside a string with
another specific region in another string. There is an overloaded form that allows you to
ignore case in such comparisions
Syntax:
boolean regionMatches(int startIndex,String str2,int str2StartIndex,int
numChars)
boolean regionMatches(boolena ignorCase,int startIndex,String str2,int
strStrartIndex,int numChars)
133
class String_Operation
{
public static void main(String args[])
{
String str1 = new String("Java is a wonderful language");
String str2 = new String("It is an object-oriented language");
boolean result = str1.regionMatches(20, str2, 25, 0);
System.out.println(result);
}
}
class String_Operation
{
public static void main(String args[])
{
String str1 = new String("Java is a wonderful language");
String str2 = new String("It is an object-oriented language");
boolean result = str1.regionMatches(true, 20, str2, 25, 0);
System.out.println(result);
}
}
134
3. startsWith() and endsWith()
The startsWith() method determines whether a given String begins with a
specified string.
The endsWith() method determines whether the String in questions ends with a
specified string.
Syntax:
boolean startsWith(String str)
boolean endsWith(String str)
str is the String object being tested. If the string matches, true is
returned. Otherwise false is returned
class String_Operation
{
public static void main(String args[])
{
boolean a, b;
a = "Chettinad".startsWith("Chi");
b = "Chettinad".endsWith("nad");
System.out.println("The Start of the String is: " + a);
System.out.println("The Ends of the String is:" + b);
}
}
135
4. equals() Versus ==
The equals function and == operator are perform two different operations
The equals() method compares the characters inside a String object.
The == operator compares two object references to see whether they refer to
the same instance.
class String_Operation
{
public static void main(String args[])
{
String s1 = "Hello1234";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
The Contents of the two String objects are identical, but they are distinct object,
This
136
means that s1 and s2 do not refer to the same objects.
5. compareTo()
Syntax:
int compareTo(String str);
Value
Meaning
Less than zero
The invoking string is less than str.
Greater than zero
The invoking string greater than str.
Zero
The two strings are equal.
137
class String_Operation
{
public static void main(String args[])
{
String s1 = "Chettinad";
String s2 = "Chettinad";
int n = s1.compareTo(s2);
if (n==0)
System.out.println("The Two String are Equal");
else if(n>0)
System.out.println("The First Strings is Greater than the
Second String");
else if(n<0)
System.out.println("The First String is Smaller than the
Second String");
}
}
138
MODIFYING A STRING
1. substring()
substring() has tow forms.
1. String substring(int startIndex)
2. String substring(int startIndex,int endIndex)
class String_Operation
{
public static void main(String args[ ])
{
String s1 = "This is a test. This is, too.";
String s2 = s1.substring(5);
String s3 = s1.substring(5,8);
System.out.println("The Sub String of S2 is: " + s2);
System.out.println("The Sub String of S3 is: " + s3);
}
}
139
2. concat()
You can concatenate two strings using concat()
Syntax:
String concat(String str);
class String_Operation
{
public static void main(String args[ ])
{
String s1 = "One";
String s2 = s1.concat(" Two");
System.out.println("The Concatenation of Two String is: " + s2);
}
}
140
3. replace()
The replace() method replaces all occurences of one character in the
invoking string with another character.
Syntax:
String replace(char original, char replacement)
class String_Operation
{
public static void main(String args[ ])
{
String s = "Hello".replace('l','w');
System.out.println("The Replacement of the String is:" + s);
}
}
4. trim()
The trim() method returns a copy of the invoking string from which any leading
and trailing whitespace has been removed.
Syntax:
String trim()
class String_Operation
{
public static void main(String args[ ])
{
String s = " Hello world
".trim();
System.out.println("The Removable Whitspace of the String is: " + s);
}
}
141
StringBuffer Functions
1. StringBuffer is a peer class of String that provides much of the functionality of strings.
2. String Buffer represents growable and writeable character sequences.
3. String Buffer may have characters and substrings inserted in the middle or appended
to the end.
4. String Buffer will automatically grow to make room for such additions and often has
more characters preallocated than are actually needed, to allow room for growth.
StringBuffer Constructors
StringBuffer defined these three constructors:
1. StringBuffer()
2. StringBuffer(int size)
3. StringBuffer(String str)
142
(1) The default constructor reserves room for 16 characters without reallocation.
(2) The second version accepts an integer argument that explicitly sets the size of
the buffer.
(3) The third version accepts a String argument that sets the initial contents of the
StringBuffer object and reserves room for 16 more characters without reallocation.
1. length() and capacity()
Syntax:
int length()
int capacity()
class String_Operation
{
public static void main(String args[ ])
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println("Buffer = " + sb);
System.out.println("Length = " + sb.length());
System.out.println("Capacity = " + sb.capacity()); //Its capacity is 21
//because room for 16 additional characters is automatically added.
143
}
}
2. ensureCapacity()
1. If you want to preallocate room for a certain number of characters after a
StringBuffer has been constructed, you can use ensureCapacity() to set the size of the
buffer.
2. This is useful if you know in advance that you will be appending a large
number of small strings to a StringBuffer.ensureCapacity() has this general form:
void ensureCapacity(int capacity);
Here, capacity specifies the size of the buffer.
class String_Operation
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Rose India");
//Returns the current capacity of the String buffer.
System.out.println("Buffer : "+sb+"\nCapacity : " + sb.capacity());
//Increases the capacity, as needed, to the specified amount in the
//given string buffer object
sb.ensureCapacity(27);
System.out.println("New Capacity = " + sb.capacity());
}
144
3. setLength()
To set the length of the buffer within a StringBuffer object, use
setLength().
Syntax:
void setLength(int len)
Here, len specifies the length of the buffer. This value must be non negative.
when you increase the size of the buffer, null characters are added to
the end of the existing buffer.
class String_Operation
{
public static void main(String[ ] args)
{
// Construct a StringBuffer object:
StringBuffer s = new StringBuffer("Hello world!");
// Change the length of buffer to 5 characters:
s.setLength(5);
System.out.println(s);
}
}
145
4. charAt() and setCharAt()
1. The value of a single character can be obtained from a StringBuffer via the charAt()
method.
Syntax:
char charAt(int where)
For charAt(), where specifies the index of the character being
obtained.
2. You can set the value of a character within a StringBuffer using setCharAt().
Syntax:
void setCharAt(int where,char ch)
For setCharAt(), where specifies the index of the character being set,
and ch specifies the new value of that character.
For both methods, where must be nonnegative and must not specify a
location beyond the end of the buffer.
146
class String_Operation
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println("Buffer before = " + sb);
System.out.println("charAt (1) before = " + sb.charAt(1));
sb.setCharAt(1,'i');
sb.setLength(2);
System.out.println("Buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}
}
147
5. getChars()
To copy a substring of a StringBuffer into an array, use the getChars() method.
Syntax:
void getChars(int sourceStart,int sourceEnd,char target[],int
targetStart);
class String_Operation
{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer src = new StringBuffer("To learn JAVA, start with
keywords.");
// Declare a new char array:
char[] dst = new char[2];
// Copy the chars #9 and #10 to dst:
src.getChars(9,11,dst,0);
// Display dst:
System.out.println(dst);
}
}
148
6. append()
1. The append() method concatenates the string representation of any other
type of data ot the end of the invoking StringBuffer object.
2. It has overloaded versions for all the built - in types and for Object.
3. Here are a few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
4. String.valueOf() is called for each parameter to obtain its string
representation.
5. The result is appended to the current StringBuffer object. The buffer itself is
returned by each version of append().
StringBuff append(String str)
public class String_Operation
{
public static void main(String[] args)
{
// Construct a String object:
String s1 = new String("3.14");
// Construct a StringBuffer object:
StringBuffer s = new StringBuffer("The ratio is: ");
// Append the string and display the buffer:
System.out.println(s.append(s1) + ".");
}
}
149
StringBuffer append(int num)
class String_Operation
{
public static void main(String args[])
{
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}
StringBuffer append(Object obj)
/*class String_Operation
{
public static void main(String[] args)
{
// Declare and initialize an object:
Object d = new Double(3.14);
// Construct a StringBuffer object:
StringBuffer s = new StringBuffer("The ratio is: ");
// Append the object and display the buffer:
System.out.println(s.append(d) + ".");
}
}
150
7. insert()
1. The insert() method inserts one string into another.
2. It is overloaded to accept values of all the simple types, plus Strings and
Objects.
3. Like append(), it calls String.valueOf() to obtain the string representation of
the value it is called with.
4. These are a few of its forms:
StringBuffer insert(int index,String str)
StringBuffer insert(int index,char ch)
StringBuffer insert(int index, object obj)
Here, index specifies the index at which point the string will be inserted into the
invoking StringBuffer object.
StringBuffer insert(int index,String str)
class String_Operation
{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer buf = new StringBuffer("Hello !");
// Construct a String object:
String s = new String("there");
// Insert the string "s" at offset 6:
buf = buf.insert(6,s);
// Display the buffer:
System.out.println(buf);
}
}
151
StringBuffer insert(int index,char ch)
public class String_Operation
{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer buf = new StringBuffer("Hello #!");
// Insert 'J' at the offset 6:
buf = buf.insert(6,'J');
// Display the buffer:
System.out.println(buf);
}
}
StringBuffer insert(int index, object obj)
class String_Operation
{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer buf = new StringBuffer("Hello !");
// Construct an object:
Object d = new Double(3.45);
// Insert d at the offset 6:
buf = buf.insert(6,d);
// Display the buffer:
System.out.println(buf);
}
}
152
8. reverse()
You can reverse the character within s StringBuffer object using
reversed().
Syntax:
StringBuffer reverse()
class String_Operation
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
153
9. delete() and deleteCharAt()
StringBuffer the ability to delete characters using the methods delete() and
deleteCharAt().
Syntax:
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
class String_Operation
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("This is a Test.");
sb.delete(4,7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}
154
10. replace()
It replace one set of character with another set inside a StringBuffer object.
StringBuffer replace(int startIndex, int endIndex, String str);
class String_Operation
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5,7, "was");
System.out.println("After Replace: " + sb);
}
}
155
11. substring()
Syntax:
String substring(int startIndex)
String substring(int startIndex,int endIndex)
class String_Operation
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Chettinad");
sb.substring(6);
System.out.println("The Substring is: " + sb);
sb.substring(2,5);
System.out.println("The Substring is: " + sb);
}
}
156
UNIT – III
Balance Chapters
157
THE
CHARACTER
STREAMS
158
The character Streams
1. While the byte stream classes provide sufficient functionality to handle any type of I/O
operation, they cannot work directly with Unicode characters.
2. Since one of the main purposes of Java is to support the “write once, run anywhere”
philosophy, it was necessary to include direct I/O support for characters.
3. At the top of the character stream hierarchies are the Reader and Writer abstract classes.
Reader
Reader is an abstract class that defines java’s model of streaming character input. All of
the methods in this class will throw an IOException on error conditions.
Writer
Writer is an abstract class that defines streaming character output . All of the methods
in this class return a void value and throw an IOException in the case of errors.
159
The Methods Defined by Reader
Method
abstract void close()
Description
Closes the input source. Further read attempts will generate
an IOException.
void mark(int numChars) Places a mark at the current point in the input stream that
will remain valid until numChars characters are read
boolean markSupported() Returns true if mark() / reset() are supported on this stream
int read()
Returns an integer representation of the next available
character from the invoking input stream. -1 is returned
when the end of the file is encountered.
int read(char buffer[])
Attempts to read up to buffer.length characters into buffer
and returns the actual number of character that were
successfully read. -1 is returned when the end of the file
encountered.
abstract int read(
char buffer[],
int offset,
int numChars)
Attempts to read up to numChars characters into buffer
starting at buffer[offset], returning the number of characters
successfully read. -1 is returned when the end of the file is
encountered.
160
Method
Description
boolean ready()
Returns true if the next input request will not wait.
Otherwise, it returns false.
void reset()
Resets the input pointer to the previously set mark
long skip(
Skips over numChars characters of input , returning the
long numChars) number of characters actually skipped.
161
The Methods Defined by Writer
Method
Description
abstract void close()
Closes the output stream. Further write attempts will generate an
IOException.
abstract void flush()
Finalizes the output state so that any buffers are cleared. That is, it
flushes the output buffers.
void write (int ch)
Writes a single character to the invoking output stream. Note that
the parameter is an int, which allows you to call write with
expressions without having to cast them back to char.
void write(char buffer[])
Writes a complete array of characters to the invoking output
stream.
abstract void write(
char buffer[],
int numChars)
Writes a subrange of numChars characters from the array buffer,
beginning at buffer[offset] to the invoking output stream.
void write(String str)
Writes str to the invoking output stream.
void write(String str,
int offset,
int numChars)
Writes a subrange of numChars characters from the array str,
beginning at the specified offset.
162
FileReader
The FileReader class creates a Reader that you can use to read the contents of a file.
Its most commonly used constructors are shown here:
FileReader (String filePath)
FileReader (File filObj)
Note:
Either can throw a FileNotFoundException. Here, filePath is the full path name of a
file and fileobj is a File object that describes the file.
163
import java.io.*;
class FileReaderDemo
{
public static void main(String args[]) throws IOException
{
FileReader fr = new FileReader("FileReaderDemo.java");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null)
{
System.out.println(s);
}
fr.close();
}
}
164
FileWriter
The FileWriter class creates a Writer that you can use to writet to a file. Its most
commonly used constructors are shown here:
FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)
They can throw an IOException. Here, filePath is the full path name of a file, and fileObj is a
File Object that describes the file. If append is true, then output is appended to the end fo the
file.
165
import java.io.*;
class FileWriterDemo
{
public static void main(String args[])
{
try
{
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}
catch (Exception e)
{
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
166
CharArrayReader
CharArrayReader is an implementation of an input stram that uses a character array as the
source. The class has two constructos, each of which requires a character array to provide the
data source:
CharArrayReader(char arrray[])
CharArrayReader(char array[],int start,int numChars)
Here, array is the input source. The second constructor creates a Reader from a subset of your
character array that begins with the character at the index specified by start and is numChars
long.
167
import java.io.*;
class CharArrayReaderDemo
{
public static void main(String args[]) throws IOException
{
String tmp = "abcdefghijklmnopqrstuvwxyz";
int length = tmp.length();
char c[] = new char[length];
tmp.getChars(0, length, c, 0);
CharArrayReader input1 = new CharArrayReader(c);
CharArrayReader input2 = new CharArrayReader(c, 0, 5);
int i;
System.out.println("input1 is:");
while((i = input1.read()) != -1)
{
System.out.print((char)i);
}
System.out.println();
System.out.println("input2 is:");
while((i = input2.read()) != -1)
{
System.out.print((char)i);
}
System.out.println();
}
}
168
CharArrayWriter
CharArrayWriter is an implementation of an output stram that uses a character array as the
destination. The class has two constructos, each of which requires a character array to provide
the data destination:
CharArrayWriter()
CharArrayWriter(int numChars)
In the first form, a buffer with a default size is created. In the second, a buffer is created with a
size equal to that specified by numChars. The buffer is held in the buf field of
CharArrayWriter. The buffer size will be increased automatically, if needed. The number of
characters held by the buffer is contained in the count field of CharArrayWriter. Both buf
and count are protected fields.
169
import java.io.*;
class CharArrayWriterDemo
{
public static void main(String args[]) throws IOException
{
CharArrayWriter f = new CharArrayWriter();
String s = "This should end up in the array";
char buf[] = new char[s.length()];
s.getChars(0, s.length(), buf, 0);
f.write(buf);
System.out.println("Buffer as a string");
System.out.println(f.toString());
System.out.println("Into array");
char c[] = f.toCharArray();
for (int i=0; i<c.length; i++)
{
System.out.print(c[i]);
}
System.out.println("\nTo a FileWriter()");
FileWriter f2 = new FileWriter("test.txt");
f.writeTo(f2);
f2.close();
System.out.println("Doing a reset");
f.reset();
for (int i=0; i<3; i++)
f.write('X');
System.out.println(f.toString());
}}
170
BufferedReader
BufferedReader improves performance by buffering input. It has two constructors:
BufferedReader(Reader inputStream)
BufferedReader(Reader inputStream,int bufsize)
The first form creates a buffered character stream using a default buffer size. In the second,
the size of the buffer is passed in bufsize.
171
import java.io.*;
class BufferedReaderDemo
{
public static void main(String args[]) throws IOException
{
String s = "This is a © copyright symbol " + "but this is © not.\n";
char buf[] = new char[s.length()];
s.getChars(0, s.length(), buf, 0);
CharArrayReader in = new CharArrayReader(buf);
BufferedReader f = new BufferedReader(in);
int c;
while((c = f.read()) != -1)
{
System.out.print((char)c);
}
}
}
172
BufferedWriter
A BufferedWriter is a Writer that adds a flush() method that can be used to ensure that data
buffers are physically wirtten to the actual output stream. Using a BufferedWriter can increase
performance by reducing the number of times data is actually physically written to the output
stream. A BufferedWriter has these two constructors:
BufferedWriter(Writer outputStream)
BufferedWriter(Writer outputStream,int bufsize)
The first form creates a buffered character stream using a default buffer size. In the second,
the size of the buffer is passed in bufsize.
173
import java.io.*;
class BufferedWriterDemo
{
public static void main(String args[]) throws Exception
{
// Create a new instance of a BufferedWriter object using a StringWriter.
StringWriter sw = new StringWriter();
BufferedWriter bw = new BufferedWriter(sw);
// Write to the underlying StringWriter.
String str = new String("This is the string being written.");
// Print out the 6 characters.
bw.write(str, 12, 6);
bw.flush();
System.out.println(sw.getBuffer());
// Close the BufferedWriter object and the underlying StringWriter object.
sw.close();
bw.close();
}
}
174
PushbackReader
The PushbackReader class allows one or more characters to be returned to the input stream.
This allows you to look ahead in the input stream. Here are its two constructors:
PushbackReader(Reader inputStream)
PushbackReader(Reader inputStream,int bufSize)
The first form creates a buffered stream that allows one character to be pushed back.
In the second, the size of the pushback buffer is passed in bufSize.
PushbackReader provides unread(), which returns one or more characters to the
invoking input stream. It has the three forms shown here:
void unread(int ch)
void unread(char buffer[])
void unread(char buffer[], int offset, int numChars)
The first form pushes back the character passed in ch. This will be the next character returned by
a subsequent call to read(). The second form returns the characters in buffer. The third form
pushes back numChars characters beginning at offset from buffer. An IOException 175
will be
thrown if there is an attempt to return a character when the pushback buffer is full.
import java.io.*;
class PushbackReaderDemo
{
public static void main(String args[]) throws IOException
{
String s = "if (a == 4) a = 0 ; \\n";
char buf[] = new char[s.length()];
s.getChars(0, s.length(), buf, 0);
CharArrayReader in = new CharArrayReader(buf);
PushbackReader f = new PushbackReader(in);
int c;
while ((c = f.read()) != -1)
{
switch(c)
{
case '=':
if ((c = f.read()) == '=')
System.out.print(".eq.");
else
{
System.out.print("<-");
f.unread(c);
}
break;
default:
System.out.print((char) c);
break;
}
}
}
}
176
PrintWriter
PrintWriter is essentially a character – oriented version of PrintStream. It provides the
formatted output methods print() and println(). PrintWriter has four constructors:
PrintWriter(OutputStream outputStream)
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
PrintWriter(Writer outputStream)
PrintWriter(Writer outputStream, boolean flushOnNewline)
Where flushOnNewline controls whether Java flushes the output stream every time println() is
called. If flushOnNewline is true, flushing automatically takes place. If false, flushing is not
automatic. The first and third constructors do not automatically flush.
177
import java.io.*;
class PrintWriterDemo
{
public static void main(String args[])
{
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}
178
SERIALIZATION
179
Serialization
1. Serialization is the process of writing the state of an object to a byte stream.
2. This is useful when you want to save the state of your program to a persistent
storage area, such as a file.
3. At a later time, you may restore these objects by using the process of
deserialization.
4. Serialization is also needed to implement Remote Method Invocation (RMI).
5. RMI allows a Java object on one machine to invoke a method of a Java object on
a different machine.
6. An object may be supplied as an argument to that remote method.
7. The sending machine serializes the object and transmits it.
8. The receiving machine deserializes it.
180
Serializable
1. Only an object that implements the Serializable interface can be saved and restored by the
serialization facilities.
2. The Serializable interface defines no members. It is simply used to indicate that a class may be
serialized.
3. If a class is serializable, all of its subclasses are also serializable.
4. Variables that are declared as transient are not saved by the serialization facilities.
5. Also static variable are not saved.
Externalizable
1. The Java facilities for serialization and deserialization have been designed so that much of the
work to save and restore the state of an object occurs automatically.
2. However, there are cases in which the programmer may need to have control over these
processes.
3. For example, it may be desirable to use compression or encryption techniques. The
Externalizable interface is designed for these situations.
4. The Externalizable interface defines these two methods:
void readExternal(ObjectInput inStream) throws IOException, ClassNotFoundException
void writeExternal(ObjectOutput outStream) throws IOException
181
In these methods, inStream is the byte stream from which the object is to be read, and outStream is
the byte stream to which the object is to be written.
ObjectOutput
The ObjectOutput interface extends the DataOutput interface and support object
Serialization. The following Methods is called the serialize an object. All of these
methods will throw an IOException on error condition.
Method
Description
void close()
Closes the invoking stream. Further write attempts will
generate an IOException.
void flush()
Finalizes the output state so that any buffers are cleared.
That is, it flushes the output buffers.
void wirte(byte buffer[])
Writes an array of bytes to the invoking stream.
void write(byte buffer[], int
offset, int numBytes)
Writes a subrange of numBytes bytes from the array
buffer, beginning at buffer[offset].
void write(int b)
Writes a single byte to the invoking stream. The byte
written is the low – order byte of b.
Void writeObject(Object obj) Writes object obj to the invoking stream.
182
ObjectOutputStream
The ObjectOutputStream class extends the OutputStream class and implements the
ObjectOutput interface. It is responsible for writing objects to a stream. A constructor of
this class is:
ObjectOutputStream(OutputStream outStream) throws IOException
The argument outStream is the output stream to which serialized objects will be written.
Method
Description
void close()
Closes the invoking stream. Further write attempts will
generate an IOException.
void flush()
Finalizes the output state so that any buffers are cleared.
That is, it flushes the output buffers.
void wirte(byte buffer[])
Writes an array of bytes to the invoking stream.
void write(byte buffer[], int
offset, int numBytes)
Writes a subrange of numBytes bytes from the array
buffer, beginning at buffer[offset].
void write(int b)
Writes a single byte to the invoking stream. The byte
written is the low – order byte of b.
void writeBoolean(boolean b)
Writes boolean to the invoking stream.
183
Method
Description
void writeByte(int b)
Writes a byte to the invoking stream. The byte written is
the low – order byte of b.
void writeBytes(String str)
Writes the bytes representing str to the invoking stream.
void writeChar(int c)
Writes a char to the invoking stream.
void writeChars(String str)
Writes the characters in str to the invoking stream.
void writeDouble(double d)
Writes a double to the invoking stream.
void writeFloat(float f)
Writes a float to the invoking stream.
void writeInt(int i)
Writes a int to the invoking stream.
void WriteShort(int i)
Writes a short to the invoking stream.
void writeLong(long i)
Writes a long to the invoking stream.
final void writeObject(Object obj)
Writes a obj to the invoking stream.
184
ObjectInput
The ObjectInput interface extends the DataInput interface and support object
Serialization. The following Methods is called the serialize an object. All of these
methods will throw an IOException on error condition.
Method
Description
int available()
Returns the number of bytes that are now available in
the input buffer.
void close()
Closes the invoking stream. Further read attempts will
generate an IOException.
int read()
Returns an integer representation of the next available
byte of input. -1 is returned when the end of the file is
encountered.
int read(byte buffer[])
Attempts to read up to buffer length bytes into buffer,
returning the number of bytes that were successfully
read. -1 is returned when the end of the file is
encountered.
int read(byte buffer[], int
offset, int numBytes)
Attempts to read up to numBytes bytes into buffer
starting at buffer[offset], returning the number of bytes
that were successfully read. -1 is returned when the end
of the file is encountered.
185
Method
Description
Object readObject()
Reads an object from the invoking stream.
Long skip(long numBytes)
Ignores(that is, skips) numBytes bytes in the invoking
stream, returnign the number of bytes actually ignored.
ObjectInputStream
The ObjectInputStream class extends the InputStream class and implements the
ObjectInput interface. It is responsible for Reading objects from a stream. A constructor
of this class is:
ObjectInputStream(InputStream inStream) throws IOException,
StreamCorruptedException
The argument inStream is the input stream from which serialized objects should be read.
186
Method
Description
int available()
Returns the number of bytes that are now available in the
input buffer.
void close()
Closes the invoking stream. Further read attempts will
generate an IOException
int read()
Returns an integer representation of the next available byte
of input. -1 is returned when the end of the file is
encountered.
int read(byte buffer[],int offset,int
numBytes)
Attempts to read up to numBytes bytes into buffer starting at
buffer[offset], returning the number of bytes successfully
read. -1 is returned when the end of the file is encountered.
boolean readBoolena()
Reads and returns boolean from the invoking stream.
byte readByte()
Reads and returns a byte from the invoking stream.
char readChar()
Reads and returns a char from the invoking stream.
double readDouble()
Reads and returns a double from the invoking stream.
float readFloat()
Reads and returns a float from the invoking stream.
void readFully(byte buffer[])
Reads buffer length bytes into buffer. Returns only when all
bytes have been read.
void readFully(byte buffer[], int
offset, int numBytes)
187
Reads numBytes bytes into buffer starting at buffer[offset].
Returns only when numBytes have been read.
Method
Description
int readInt()
Reads and returns an int from the invoking stream.
long readLong()
Reads and returns a long from the invoking stream.
final Object readObject()
Reads and returns an object from the invoking stream.
short readShort()
Reads and returns a short from the invoking stream.
int readUnsignedByte()
Reads and returns an unsigned byte from the invoking stream.
int readUnsignedShort()
Reads an unsigned short from the invoking stream.
188
import java.io.*;
class SerializationDemo
{
public static void main(String arg[])
{
//Object Serialization
try
{
MyClass object1 = new MyClass("Hello", -7,2.7e10);
System.out.println("Object1: " + object1);
FileOutputStream fos = new FileOutputStream("serial");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object1);
oos.flush();
oos.close();
}
catch(Exception e)
{
System.out.println("Exception during serialization: " + e);
System.exit(0);
189
}
//Object Deserialization
try
{
MyClass object2;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
object2 = (MyClass)ois.readObject();
ois.close();
System.out.println("object2: " + object2);
}
catch(Exception e)
{
System.out.println("Exception during deserialization: " + e);
System.exit(0);
}
}
}
class MyClass implements Serializable
{
String s;
int i;
double d;
public MyClass(String s,int i,double d)
{
this.s = s;
this.i = i;
this.d = d;
}
public String toString()
{
return "S=" + s + "; i=" + i + "; d=" + d;
}
}
190
Converting Primitive Numbers to Object Numbers using Constructor Methods
Constructor Calling
Conversion Action
Integer intval = new Integer(i)
Primitive integer to Integer object
Float floatval = new Float(f)
Primitive float to Float object
Double doubleval = new Double(d)
Primitive double to Double object
Long longval = new Long(l)
Primitive long to Long object
Converting Object Numbers to Primitive Numbers using typeValue() method
Method Calling
Conversion Action
int i = IntVal.intValue()
Object to Primitive integer
float f = FloatVal.floatValue()
Object to Primitive float
long l = LongVal.longValue()
Object to Primitive long
double d = DoubleVal.doubleValue()
Object to Primitive double
191
Converting Numbers to Strings Using a String( ) Method
Constructor Calling
Conversion Action
str = Integer.toString(i)
Primitive Integer to string
str = Float.toString(f)
Primitive float to string
str = Double.toString(d)
Primitive double to string
str = Long.toString(l)
Primitive long to string
Converting String Objects to Numeric Object Using the Static Method ValueOf()
Method Calling
Conversion Action
DoubleVal = Double.ValueOf(str)
Converts String to Double object
FloatVal = Float.ValueOf(str)
Converts String to Float object
IntVal = Integer.ValueOf(str)
Converts string to Integer object
LongVal = Long.Valueof(str)
Converts string to Long object
192
Converting Numberic Strings to Primitive Numbers Using Parsing Methods
Constructor Calling
Conversion Action
int i = Integer.parseInt(str)
Converts String to Primitive Integer
long l = Long.parseLong(str)
Converts String to Primitive long
193
UNIT - V
194
StringTokenizer
1. The processing of text often consists of parsing a formatted input string.
2. Parsing is the division of text into a set of discrete parts, or tokens, which in a certain
sequence can convey a semantic meaning.
3. The StringTokenizer class provides the first step in this parsing process, often
called the lexer (lexical analyzer) or scanner.
4. StringTokenizer implements the Enumeration interface.
5. Therefore, given an input string, you can enumerate the individual tokens contained
in it using StringTokenizer.
6. To use StringTokenizer, you specify an input string and a string that contains
delimiters.
7. Delimiters are characters that separate tokens.
8. Each character in the delimiters string is considered a valid delimiter—for example,
“,;:” sets the delimiters to a comma, semicolon, and colon.
9. The default set of delimiters consists of the whitespace characters: space, tab,
newline, and carriage return.
10. The StringTokenizer constructors are shown here:
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
StringTokenizer(String str, String delimiters, boolean delimAsToken)
195
196
import java.util.StringTokenizer;
class STDemo
{
static String in = "title=Java: The Complete Reference;" +
"author=Schildt;" + "publisher=Osborne/McGraw-Hill;" +
"copyright=2002";
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer(in, "=;");
while(st.hasMoreTokens())
{
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "\t" + val);
}
}
}
197
BitSet
A BitSet class creates a special type of array that holds bit values. This array can
increase in size as needed. This makes it similar to a vector of bits. The BitSet
constructors are shown here:
BitSet( )
BitSet(int size)
The first version creates a default object. The second version allows you to specify its
initial size (that is, the number of bits that it can hold). All bits are initialized to zero.
BitSet implements the Cloneable interface and defines the methods.
198
199
200
// BitSet Demonstration.
import java.util.BitSet;
class BitSetDemo
{
public static void main(String args[])
{
BitSet bits1 = new BitSet(16);
BitSet bits2 = new BitSet(16);
// set some bits
for(int i=0; i<16; i++)
{
if((i%2) == 0) bits1.set(i);
if((i%5) != 0) bits2.set(i);
}
System.out.println("Initial pattern in bits1: ");
System.out.println(bits1);
System.out.println("\nInitial pattern in bits2: ");
System.out.println(bits2);
// AND bits
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);
// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}
201
Calendar
1. The abstract Calendar class provides a set of methods that allows you to convert a
time in milliseconds to a number of useful components.
2. Some examples of the type of information that can be provided are: year, month, day,
hour, minute, and second.
3. It is intended that subclasses of Calendar will provide the specific functionality to
interpret time information according to their own rules.
4. This is one aspect of the Java class library that enables you to write programs that
can operate in several international environments.
5. An example of such a subclass is GregorianCalendar.
6. Calendar provides no public constructors.
7. Calendar defines several protected instance variables.
8. areFieldsSet is a boolean that indicates if the time components have been set.
9. fields is an array of ints that holds the components of the time.
10. isSet is a boolean array that indicates if a specific time component has been set.
11. time is a long that holds the current time for this object.
12. isTimeSet is a boolean that indicates if the current time has been set.
202
Calendar defines the following int constants, which are used when you get or set
components of the calendar:
203
204
205
206
// Demonstrate Calendar
import java.util.Calendar;
class CalendarDemo
{
public static void main(String args[])
{
String months[] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
// Create a calendar initialized with the
// current date and time in the default
// locale and timezone.
Calendar calendar = Calendar.getInstance();
// Display current time and date information.
System.out.print("Date: ");
System.out.print(months[calendar.get(Calendar.MONTH)]);
System.out.print(" " + calendar.get(Calendar.DATE) + " ");
System.out.println(calendar.get(Calendar.YEAR));
System.out.print("Time: ");
System.out.print(calendar.get(Calendar.HOUR) + ":");
System.out.print(calendar.get(Calendar.MINUTE) + ":");
System.out.println(calendar.get(Calendar.SECOND));
// Set the time and date information and display it.
calendar.set(Calendar.HOUR, 10);
calendar.set(Calendar.MINUTE, 29);
calendar.set(Calendar.SECOND, 22);
System.out.print("Updated time: ");
System.out.print(calendar.get(Calendar.HOUR) + ":");
System.out.print(calendar.get(Calendar.MINUTE) + ":");
System.out.println(calendar.get(Calendar.SECOND));
}
}
207
GregorianCalendar
1. GregorianCalendar is a concrete implementation of a Calendar that implements the
normal Gregorian calendar with which you are familiar.
2. The getInstance( ) method of Calendar returns a GregorianCalendar initialized
with the current date and time in the default locale and time zone.
3. GregorianCalendar defines two fields: AD and BC.
4. These represent the two eras defined by the Gregorian calendar.
5. There are also several constructors for GregorianCalendar objects.
6. The default, GregorianCalendar( ), initializes the object with the current date and
time in the default locale and time zone.
7. Three more constructors offer increasing levels of specificity:
GregorianCalendar(int year, int month, int dayOfMonth)
GregorianCalendar(int year, int month, int dayOfMonth, int hours, int minutes)
GregorianCalendar(int year, int month, int dayOfMonth, int hours, int minutes, int seconds)
All three versions set the day, month, and year. Here, year specifies the number of years
that have elapsed since 1900. The month is specified by month, with zero indicating
January. The day of the month is specified by dayOfMonth. The first version sets the
time to midnight. The second version also sets the hours and the minutes. The
third
208
version adds seconds.
You can also construct a GregorianCalendar object by specifying either the locale
and/or time zone. The following constructors create objects initialized with the current
date and time using the specified time zone and/or locale:
GregorianCalendar(Locale locale)
GregorianCalendar(TimeZone timeZone)
GregorianCalendar(TimeZone timeZone, Locale locale)
GregorianCalendar provides an implementation of all the abstract methods in
Calendar. It also provides some additional methods. Perhaps the most interesting is
isLeapYear( ), which tests if the year is a leap year. Its form is
boolean isLeapYear(int year)
This method returns true if year is a leap year and false otherwise.
209
import java.util.*;
class GregorianCalendarDemo
{
public static void main(String args[])
{
String months[] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug","Sep",
"Oct", "Nov", "Dec"};
int year;
// Create a Gregorian calendar initialized
// with the current date and time in the
// default locale and timezone.
GregorianCalendar gcalendar = new GregorianCalendar();
// Display current time and date information.
System.out.print("Date: ");
System.out.print(months[gcalendar.get(Calendar.MONTH)]);
System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
System.out.println(year = gcalendar.get(Calendar.YEAR));
System.out.print("Time: ");
System.out.print(gcalendar.get(Calendar.HOUR) + ":");
System.out.print(gcalendar.get(Calendar.MINUTE) + ":");
System.out.println(gcalendar.get(Calendar.SECOND));
// Test if the current year is a leap year
if(gcalendar.isLeapYear(year))
{
System.out.println("The current year is a leap year");
}
else {
System.out.println("The current year is not a leap year");
}
}
}
210
TimeZone
Another time-related class is TimeZone. The TimeZone class allows you to work with
time zone offsets from Greenwich mean time (GMT), also referred to as Coordinated
Universal Time (UTC). It also computes daylight saving time. TimeZone only supplies
the default constructor.
211
212
import java.util.*;
public class TimeZones
{
public static void main(String[] args)
{
Date date = new Date();
String TimeZoneIds[] = TimeZone.getAvailableIDs();
for(int i = 0; i < TimeZoneIds.length; i++)
{
TimeZone tz = TimeZone.getTimeZone(TimeZoneIds[i]);
String tzName = tz.getDisplayName(tz.inDaylightTime(date),
TimeZone.LONG);
System.out.print(TimeZoneIds[i] + ": ");
// Get the number of hours and minutes from GMT
int rawOffset = tz.getRawOffset();
int hour = rawOffset / (60*60*1000);
int minute = Math.abs(rawOffset / (60*1000)) % 60;
System.out.println(tzName + " " + hour + ":" + minute);
}
}
}
213
Locale
1. The Locale class is instantiated to produce objects that each describe a
geographical or cultural region.
2. It is one of several classes that provide you with the ability to write programs that can
execute in several different international environments.
3. For example, the formats used to display dates, times, and numbers are different in
various regions.
4. Internationalization is a large topic that is beyond the scope of this book.
5. However, most programs will only need to deal with its basics, which include setting
the current locale.
6. The Locale class defines the following constants that are useful for dealing with the
most common locales:
CANADA
CANADA_FRENCH
CHINA
CHINESE
ENGLISH
FRANCE
FRENCH
GERMAN
GERMANY
ITALIAN
ITALY
JAPAN
JAPANESE
KOREA
KOREAN
PRC
SIMPLIFIED_CHINESE
TAIWAN
TRADITIONAL_CHINESE
UK
US
214
For example, the expression Locale.CANADA represents the Locale object for Canada.
The constructors for Locale are
Locale(String language)
Locale(String language, String country)
Locale(String language, String country, String data)
These constructors build a Locale object to represent a specific language and in the
case of the last two, country. These values must contain ISO-standard language and
country codes. Auxiliary browser and vendor-specific information can be provided in
data. The first constructor was added by Java 2, version 1.4.
Locale defines several methods. One of the most important is setDefault( ), shown
here:
static void setDefault(Locale localeObj)
This sets the default locale to that specified by localeObj. Some other interesting
methods are the following:
final String getDisplayCountry( )
final String getDisplayLanguage( )
215
final String getDisplayName( )
import java.text.*;
import java.util.Locale;
public class SettingLocale
{
public static void main(String[] args)
{
// Getting default locale
Locale locale = Locale.getDefault();
System.out.println("Before setting, Locale is = " + locale);
// Setting default locale
locale = Locale.ITALY;
Locale.setDefault(locale);
System.out.println("After setting, Locale is = " + locale);
}
}
216
Random
The Random class is a generator of pseudorandom numbers. These are called
pseudorandom numbers because they are simply uniformly distributed sequences.
Random defines the following constructors:
Random( )
Random(long seed)
The first version creates a number generator that uses the current time as the starting,
or seed, value. The second form allows you to specify a seed value manually.
217
// Demonstrate random Gaussian values.
import java.util.Random;
class RandDemo
{
public static void main(String args[])
{
Random r = new Random();
for(int i=0; i<100; i++)
{
System.out.println("The Next Gaussian Number is:" +
r.nextGaussian());
}
}
}
218
Currency
Java 2, version 1.4 adds the Currency class. This class encapsulates information about
a currency. It defines no constructors.
219
// Demonstrate Currency.
import java.util.*;
class CurDemo
{
public static void main(String args[])
{
Currency c;
c = Currency.getInstance(Locale.US);
System.out.println("Symbol: " + c.getSymbol());
System.out.println("Default fractional digits: " +
c.getDefaultFractionDigits());
}
}
220
JDBC – ODBC DRIVERS
221
JDBC DRIVERS
• The JDBC API defines the Java interfaces and classes that programmers use to
connect to databases and send queries. A JDBC driver implements these interfaces
and classes for a particular DBMS vendor.
• A Java program that uses the JDBC API loads the specified driver for a particular
DBMS before it actually connects to a database. The JDBC DriverManager class
then sends all JDBC API calls to the loaded driver.
Type of JDBC Drivers
1. JDBC – ODBC Bridge
2. Native – API Partly Java Driver
3. JDBC – Net pure Java Driver
4. Native – Protocol Pure Java Driver
222
JDBC – ODBC bridge plus ODBC driver, also called Type 1.
Translates JDBC API calls into Microsoft Open Database Connectivity (ODBC)
calls that are then passed to the ODBC driver. The ODBC binary code must be
loaded on every client computer that uses this type of driver.
Native – API, partly Java driver, also called Type 2.
Converts JDBC API calls into DBMS-specific client API calls. Like the bridge
driver, this type of driver requires that some binary code be loaded on each
client computer.
JDBC – Net, pure Java driver, also called Type 3.
Sends JDBC API calls to a middle-tier net server that translates the calls into
the DBMS-specific network protocol. The translated calls are then sent to a
particular DBMS.
Native – protocol, pure Java driver, also called Type 4.
Converts JDBC API calls directly into the DBMS-specific network protocol
without a middle tier. This allows the client applications to connect directly
223 to
the database server.
JDBC Implementation
JDBC is implemented as the java.sql.package. Some of the classes of this
package are:
CLASSES
PACKAGES
Drivers
java.sql.Driver
java.sql.DriverManager
java.sql.DriverPropertyInfo
Connection
java.sql.Connection
Statements
java.sql.Statement
java.sql.PreparedStatement
java.sql.CallableStatement
ResultSet
java.sql.ResultSet
Exceptions
java.sql.SQLException
Date
java.sql.Date
224
How to Java Application or Applets Connected to the Database
1. Loading the Driver
2. Making the Connection
3. Creating and Executing a JDBC statement
4. Retrieving Data From the Result Sets
1. Loading the Driver
If you are using the JDBC – ODBC Bridge driver, use the following statement to
load it.
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
2. Making the Connection
To get the driver connected to the database, which is done by creating a
Connection object and initializing it with connection obtained from the DriverManager
Connection con = DriverManager.getConnection(url,
225
“LoginName”, “pwd”);
3. Creating and executing a JDBC statement
a. A statement object is used to send the SQL statement to the database.
b. You create a statement object and then execute it, supplying the appropriate
execute method with the SQL statement you want to send.
c. For a SELECT statement, the method used is executeQuery. For statements
that create or modify tables, the method used is executeUpdate
Statement stmt = con.createStatement();
Example:
stmt.executeQuery (SELECT * FROM MARK WHERE SLNO = "+ t1.getText() +"“);
Stmt.executeUpdate(UPDATE MARK SET SLNO="+ s1 +",NAME='"+ s2 +"'
WHERE SLNO="+ s1 +“);
226
4. Retrieving Data from the Result Sets
JDBC uses ResultSet object to return the output. So the previous
executeQuery statement can be fully written as:
ResultSet rs = stmt.executeQuery (“select * from mark”);
227
IMPORTANT PROGRAMS
228
JAVA APPLICATION PROGRAMS
Simple Interest Calculation
Interest = P * N * R
P -> Principal Amount
N -> No. of Periods
R -> Rate of Interest
Compound Interest Calculation
Interest = P(1+(R/100))n
P -> Principal Amount
R -> Rate of Interest
n -> No. of Periods
Celsius to Fahrenheit and Fahrenheit to Celsius
229
Write a simple menu driven calculator program using switch statement.
Write a program for Electricity Bill Preparation for the following condition:
1 – 50 Units
-
0.75 paise
51 – 100 Units
-
0.85 paise
101 – 200 Units
-
Rs. 1.50
201 – 600 Units
-
Rs. 2.20
Above 600 Units -
Rs. 3.50
Write a program to Multiply for the two Matrices, Addition of the two Matrics and
Subtraction of Two Matrics.
Write a program to find factorial of a given number
Write a program to check whether the given no is Palindrome or Not
230
Write a program to sort numbers in an array in ascending order and descending order
Write a program to given no. is prime or Not.
Write a program to generate Fibonacci Series Up to N numbers.
Applet Programs
Write a applet program to the creating Student Mark Statement.
Write a applet program to the creating Empolyee Salary Bill Preparation.
Write a applet program to the creating EB Bill Preparation.
Write a applet program to the Inventory Management System.
Write a applet program to the Hospital Management System.
231
Write a applet program to the creating User Authentication (username and password)
Write a applet program to the following Events
1. ActionEvent
2. AdjustmentEvent
3. FocusEvent
4. ItemEvent
5. MouseEvent (including MouseMotion)
6. KeyEvent
7. TextEvent
Write a applet program to the JDBC – ODBC drivers program for the above Applet
program.
232
THE END
233