0% found this document useful (0 votes)
181 views

Java Notes

The document provides an overview of Java programming concepts including: 1. Java programs are compiled into bytecode then interpreted by the JVM into machine code. This makes Java programs portable across platforms. 2. Java supports object-oriented programming with classes, inheritance, polymorphism, and encapsulation. Everything in Java is an object. 3. Key features of Java include being robust, secure, allowing multithreading, and being suitable for web applications.

Uploaded by

Janhvi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
181 views

Java Notes

The document provides an overview of Java programming concepts including: 1. Java programs are compiled into bytecode then interpreted by the JVM into machine code. This makes Java programs portable across platforms. 2. Java supports object-oriented programming with classes, inheritance, polymorphism, and encapsulation. Everything in Java is an object. 3. Key features of Java include being robust, secure, allowing multithreading, and being suitable for web applications.

Uploaded by

Janhvi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 95

Java Programming by Ms.K.S.

Jadhav

Objectives of Java Programming:


Objectives of java programming is to satisfy the need of customers distributed or located
worldwide.

Features of Java Programming:


1.
2. Program compiled and interpreted
Java program are two stage program. It adopt two approaches that are compiled and
interpreted. First it translate source code to byte code then byte code through interpreter
to machine code. This machine code execute by machine.

Stage 1] Java source code (*.java) javac *.java Byte code(*.class)


a)Compilation

Stage 2] Byte code(*.class) JVM(java *) Machine code (output)


b)Execution
According this features of java program compiled using javac tool which creates
appropriate by the code referred with *.class and then interpreted using java tool.
3. Truly object oriented programming
Almost everything in java is an object and class. All data and code place in it. Java
provide extensive set of class library that used by programmers through inheritance in
his/her program.
4. It is platform independent and portable
Java programs can be easily moved from one computer system to another,anytime .Java
program is unaffected from any change in operating system or processor. This portability
maintain by java by providing byte code and machine dependent sized data type.
5. Robust and secure
It provide many safe guards for reliable code. It has strict compile and run time checking
for data type. It provide efficient memory management by garbage collection. It also
provide exception handling mechanism which eliminates risk of system crash while
major error occur .
6. Allow multithreading to implement multitasking
Multithreading means handling multiple tasks simultaneously. It means we need not to
wait till the end of first task,while executing second one . This feature increase the
interactive performance of graphical applications.
7. Web Application language
Java resonate as web application language because it support -
1) applet that convert application so to execute it under web browser (using applet tags/by
HTML file) . 2) secured and 3) Platform independent.
8. High performance
Due to intermediate code and architecture java reduce overheads during run time from
machine. Use of multithreading also increase over all speed of java program.
9. Dynamically extended:
Java Programming by Ms.K.S.Jadhav

Java is capable of dynamically linking in new class library , method and objects. Useful
native methods are link dynamically at run time to java code.

Class and Objects


Class Feature: It use as a basic building block to implement other object oriented
concepts .In java, everything (data and code) wrapped inside the class.

General Structure of Java Program:

import pckage; //optional


class class_name [extends superclass][implements interfaces]
{
access_specifier data_member;
access_specifier returntype function_name(datatype argument1,datatype argument2,…)
access_specifier data_member;
public static void main(String args[])
{
..
}
}
Java programs starts with class keyword after that we provide the name of class in
this we use different access specifier which defines the scope of variable java com. Java
support 4 type of access specifier

1. private
2. protected
3. public
4. no access specifier(Default)

Access specifier/Scope Within class Outside class Within appln Outside appln

Private yes no no no

Protected yes yes no no

Default yes yes yes no

Public yes yes yes yes

Q. Write a simple java program to find addition of variable.


Java Programming by Ms.K.S.Jadhav

Ans:
class add
{
int a,b,c;
public static void main(String args[])
{ a=
5;
b=2;
c=a+b;
System.out.println(c);
}
}
Here, main function is defined with some keywords like public static. This will
indicate main function globally shared some application.
Whereas, static keyword indicate that main function will execute without object.
Inside the main parameter declared as String type array where String is a class who’s
array is used to receive the value passed from command prompt when we executes given
java application. Here, System.out.println method is used to display output of our
program. System is a class in which println method is defined which access through out
of object.

Operator:

1. Arithmetic
2. Logical
3. Relational
4. Assignment
5. Conditional
6. Shift
7. Bitwise

Shift: Shift operators are used by java programmer to shift list or most significant bit or
value.
For E.g., if variable is initialized by 12. int a=12 , then by using left shift operator as
shown below,
a>>>2
Display output a=3 because binary value of 12=1100 which is shifted by operator and
become as 0011 ‘3’

Data types: In java programmer, used 4 types of data types.

1. int
Java Programming by Ms.K.S.Jadhav

2. char
3. float
4. Boolean

Data type size

Byte 1
Short 2
Long 8
Int 4
Float 4
Double 8
Char 2

E.g., float a=3.14f;

When we want to use no value with decimal value, then we give char f.

Creating object in java: In java we create object for respective class with the help of
new operator (dynamic operator) with help of default constructor. As shown below
E.g. Stud s=new Stud ();
Now 's' is an object of class Stud. In java every object create by using new and default
constructor (if programmer not define java define it by as default method ).

Q. Following program demonstrates create object and reference from declared


Ans:
class A
{
int roll;
char name[10];
}
class main
{
public static void main(String args[])
{
A a=new A(); //Object creation
a.roll=123;
r.name=”XYZ”;
System.out.println(a.rol + a.name);
X P; //Reference of class X
P=new A();
P.roll=736;
Java Programming by Ms.K.S.Jadhav

P.name=”PQR”;
System.out.println(“Second roll”+P.roll + “Second name”+P.name);
}
}

Q.WAP to find factorial of a given


number Ans: class Fact
{
int f=1,i=1;
}
class Main
{
public static void main(String args[])
{
Fact fact=new Fact();
for (int i=1;i<=5;i++)
{
int s=fact.f * i.;
}
System.out.println(s);
}
}

Q.WAP in java to find area of


circle Ans: class Area
{
int r=5;
}
class A
{
public static void main(String args[])
{
Area a=new Area();
double area=3.14 * a.r * a.r;
System.out.println(area);
}
}

Command line program: Java programmers are able to design applicaton that are
operate form command line because java supports argument on main method. This
argument receive value from command line and store them as a String type which later
programmer convert in his/her required format(by using wrapper class)
Java Programming by Ms.K.S.Jadhav

Following program demonstrates the command line programming for argument.

E.g.: class A
{
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);//Integer is wrapper
class int b=Integer.parseInt(args[1]);
int c=a+b;
System.out.println(c);
}
}

Creating array in java: We are using array to declare set of variable or element or
set of homogeneous elements following is syntax:-

datatype array_name[]=new datatype[size of array];

E.g.: int a[]=new int[5];

Following program demonstrates the use of java program

E.g.: class Arr


{
public static void main(String args[])
{
char str[]=new char[10];
str=”PQR”;
System.out.println(str);
}
}

Object as an Argument: In java, programmer use objects to access an


information or class as well as it will use for communication between methods as
argument. Java programmers are able to return object of its calling side.

Following program demonstrates use of object as

argument E.g.:class X
{
int a;
Java Programming by Ms.K.S.Jadhav

X()
{ a=
0;
}
X(int x)
{
a=x;
}
X(X obj)
{
a=obj.a;
}
}
class PQR
{
public static void main(String args[])
{
X obj=new X();
X obj1=new X(3);
X obj2=new X(obj1);
System.out.println(“ “+obj1.a);
System.out.println(“ “+obj2.a);
}
}

Q.WAP to find substraction of given value using object as an


argument Ans:class X
{
int a,b,c;
void set(int x)
{
a=x;
}
void get(X obj2)
{
c=obj2.b-a;
}
X()
{ b=
0;
}
}
Java Programming by Ms.K.S.Jadhav

class Demo
{
public static void main(String args[])
{
X ob=new X();
ob.set(3);
X OB=new X(6);
X BC=new X();
BC.get(OB);
}
}

Object as a return type: Java programmers are also able to return a value which is
in actual class type.
Following program demonstrate the use of object as an return type

E.g.: class Demo


{
int a,b,c;
Demo()
{ a=
5;
c=0;
}
Demo show(Demo d)
{
return (d.c-a);
}
}
class First
{
public static void main(String args[])
{
Demo p=new Demo(10);
Demo d=new Demo();
Demo y;
y=new Demo(p);
System.out.println(y);
}
}
Java Programming by Ms.K.S.Jadhav
Constructor in Java:
It can be boring to initialize all of the variables in a class each time an instance is
created. Even when we add convenience functions like input( ), it would be simpler and
more concise to have all of the setup done at the time the object is first created. Because
the requirement for initialization is so common, Java allows objects to initialize
themselves when they are created. This automatic initialization is performed through the
use of a constructor.
A constructor initializes an object immediately upon creation. It has the same name
as the class in which it resides and it is syntactically similar to a method. Once defined,
the constructor is automatically called immediately after the object is created, before the
new operator completes. Constructors look a little strange because they have no return
type, not even void. This is because the implicit return type of a class’ constructor is the
class type itself. It is the constructor’s job to initialize the internal state of an object so
that the code creating an instance will have a fully initialized, usable object instantly.
Let’s examine the constructor included for the class ‘Country’.

class Country
{ long population;
int noOfStates;
float currancyRate;

Country(long x, int y)
{
population = x;
noOfStates = y;
}

void display()
{ System.out.println(“Population:”+population);
System.out.println(“No of states:”+noOfStates);
}
}

The constructor given here is having two parameters i.e. long x and int y. When
we create the object of class, the constructor can be called like,
Country japan = new Country(4582452, 15);
The instance variables, ‘population’ and ‘noOfStates’ for object ‘japan’ will be
initialized with the values given in the creation of object. So there is no need to initialize
these variables for particular object. If we print the value of ‘japan.population’ it will
print 4582452. The constructor which contains parameters is called as parameterized
constructor else it is a default constructor. A default constructor is called upon the
creation of object.
Java Programming by Ms.K.S.Jadhav

Constructor overloading:
The concept of overloading refers to the use of same name for different purposes. In
simple language, a class can have more than one constructor but with different
parameters. This is known as constructor overloading. Program illustrates this concept.

// Overloaded constructors

class Box
{
int height;
int depth;
int length;
Box()
{
height = depth = length = 10;
}
Box(int x,int y)
{
height = x;
depth = y;
}

Box(int x, int y, int z)


{
height = x;
depth = y;
length = z;
}
}
class BoxClass
{
public static void main(String args[])
{
Box a = new Box(); //statement1
System.out.println("depth of a : "+a.depth);
Box b = new Box(12,23); //statement2
System.out.println("depth of b : "+b.depth);
Box c = new Box(99,84,36); //statement3
System.out.println("depth of c : "+c.depth);
}
}
Output:
Java Programming by Ms.K.S.Jadhav

depth of a : 10
depth of b : 23
depth of c : 84

Illustration of constructor overloading


In program above, the class Box contains three different variables i.e. height, depth
and length. It also has three different constructors. First of them is default constructor
and another two are parameterized constructors. Second constructor contains two
parameters and third contains three. When the object ‘a’ is created in statement1, default
constructor is called in which all the instance variables are initialized to value 10. Thus,
a.depth is outputted as 10. Second constructor only initializes two instance variables i.e.
height and depth with the given values in sequence. Third constructor initializes all the
three instance variables upon creation of object. Remember we can call any constructor
for any object in the program. A class can contain any number of constructors but they
must differ in type and number of parameters. If we declare two constructors with same
number and type of parameters the compiler will flash the error that ‘constructor is
already defined in the class’.

Use of final keyword: This keyword is used to avoid the modification of variable or
method.
Syntax:
1. To making variable as a constant

syntax: final datatype

variable_name=Value E.g.: final

int i=10;
it avoid variable from further modification/ to make it constant

2. To making method as final

syntax:final returntype method_name (Parameter list)


{
Body;
}
3. To avoid class from
inharitance syntax: final class
classname
{
}
eg: final class X{
}
Java Programming by Ms.K.S.Jadhav
class Y extends X // Error/cannot inherit
{
Java Programming by Ms.K.S.Jadhav

Use of this keyword: It is used to avoid the confusion regarding the name of formal
parameter when it is similar class actual parameter. This keyword always used on the
left side assign by value which indicate the local variable.

E.g.. class Demo


{
int a;
void add(int a)
{
this.a=a;
System.out.println(this.a);
}
}
class PQ
{
public static void main(String args[])
{
Demo m=new Demo();
m.add(3);
}
}
The ‘this’ can also be used to call the method of its own class by following the syntax:
this.methodname();
eg: this.show();

Use of static keyword: Static keyword used in different ways

✓ This keyword is used in class


✓ It is used with method
✓ It used to declare static blocks

When we use of static keyword with variable inside the class, it creates one copy of
that variable which is shared by all the objects. Following program demonstrate the
use of static keyword for variable declaration.

E.g.: class Demo


{
static int a;
void disp()
{
Java Programming by Ms.K.S.Jadhav

System.out.println(“Use of static: This is non static function”);


}
public static void main(String args[])
{
Demo d=new Demo();
d.disp();
System.out.println(“Static value”+Demo.a);
}
static
{ a=10
0;
}
}

Q.WAP to count the number of object create in class by using static


keyword Ans: class Demo
{
static int c=0;
Demo()
{ c+
+;
}
static void show()
{
System.out.println(c);
}
}
class PQR
{
public static void main(String args[])
{
Demo d=new Demo();
Demo e= new Demo();
Demo f=new Demo();
Demo s=new Demo();
Demo.show();
}
}

finalize() method: Whenever we exit from java program, we know there is garbage
collection mechanism available which release space occupied by object. In some
situation, if it is not convenient to directly release the object from memory, because it
Java Programming by Ms.K.S.Jadhav

require some resources or currently busy from their task if delete some memory. It make
collision for resource allocation some time system gate collapse .To avoid that, finalize
method is used before garbage collection. This method is provided by java.lang.Object
package. It is default package, hence it not used for java program.
Following program demonstrate the use of finalize method.

E.g. class Demo


{
int a,b,c;
Demo()
{ a=10
;
b=20;
c=100;
}
protected void finalize()
{
System.out.println(“Resources are free”);
}
}
class R
{
public static void main(String args[])
{
Demo a=new Demo();
}
}

Nested and Inner class: This is used to implement class composition where one
class is defined in another class. The definition of inner class is restricted boundary and
existence.
Following program demonstrate the use of inner class in java.

E.g.. class A
{

returntype method()
{

class B
Java Programming by Ms.K.S.Jadhav

}
}
B b=new B();
}

E.g.. class calcu


{
int a=10;
void test()
{
System.out.println(a);
class Y
{
int k=20;
void show()
{
System.out.println(k);
System.out.println(q);
}
Y A=new Y();
A.show();
System.out.println(k);
System.out.println(a);
}
public static void main(String args[])
{
calcu c=new calcu();
c.text();
}
}

Inheritance: It is another concept of java programmer which extend the mean of


previously defines code. In java, we used extends keyword to implement inheritance.
Java supports several types of inheritance are as below

 Single
 Multilevel
 Multiple(To implement multiple inheritance, we must define any one class as
an interface)
Java Programming by Ms.K.S.Jadhav

 Hierarchical

Single Inheritance: We create single sub class from single super


class. Syntax: class A Class A
{

}
class B extends A
Class B
{

Q..WAP to find addition of 3 variable and average using single


inheritance Ans: class A
{
int a=10;
void show A()
{
System.out.println(a);
}
class B extends A
{
int b=10;
int c;
void add()
{
c=a+b+c;
}
void avg()
{
int avg=d/3;
}
public static void main(String args[])
{
B X=new B();
X.showA();
}
}
Java Programming by Ms.K.S.Jadhav

Multilevel Inheritance: - We inherit single class to create sub class from which
again we are able to inherit another sub class where classes are declared on each other,
type is called multilevel inheritance.

class A Class A
{

}
class B extends A Class B
{

}
class C extends B Class C
{

Hierarchical Inheritance: - When we need to share one class into number of subclasses
it means we want to implement Hierarchical inheritance

class A
{ Class A

}
class B extends A
{ Class B Class C

}
class C extends A
{

Multiple Inheritance: - To implement multiple inheritance in java we required class


and interface to create single subclass. Interface use by java to avoid data redundancy.
Java Programming by Ms.K.S.Jadhav

Interface: -It is similar to abstract class. The only difference between abstract and
interface is that, the data member of these class are final and all method are just declared
which are later define by its user class.
To implement multiple inheritance, these interfaces are used, similar to class.
Variable of interface are final and method of interface are always abstract.
Note: When we define any abstract method in class, we must use abstract keyword at the start of
class as well as the place where abstract method is started to declare.
Where interface we are going to define , then there is no need to define and
declare this method as abstract. Following program demonstrate the use of interface

E.g: interface A
Class A Interface B
{
int a=50;
void show();
}
class B implements A
{
void show()
{ Class C
System.out.println(“This is abstract interface method”);
}
}
class X
{
public static void main(String args[])
{
B b1=new B();
b1.show();
}
}
if a class that implements interfaces, not define methods of interfaces it
become an abstract class

Difference between class and interface:


CLASS INTERFACE
Java Programming by Ms.K.S.Jadhav

Begin with keyword class. 1.Begin with keyword interface 2.Data members are always consta
We implements interfaces on another class to define its method
Data members may be constant
By using interface, we are able to achieve multiple inheritance
We extends one class on another class

Two class are not used to implement multiple inheritance

Similarities between class and interface:


CLASS INTERFACE

1. Both are used to encapsulate data


members and methods

2. Both are used to implements multiple


inheritance

3. We can create reference of both

4. Both are supporting inheritance

super Keyword: We are always create the object of latest subclass to access the
information and methods of all above super class and subclass but if super class consist
any constructor, then it cannot be accessed by the object of subclass.
Following program demonstrates use of constructor in inheritance
E.g.: class A
{
int a,b;
A()
{ a=10,b=2
0;
}
void show()
Java Programming by Ms.K.S.Jadhav

{
System.out.println(a+b);
}
}
class B extends A
{
int k;
B()
{ k=10
0;
}
void show()
{
System.out.println(k);
}
}
class C
{
public static void main(String args[])
{
}
}
In above program, when statement b.show() is executed, it will generate error
because the variable declared are not initialized. In the program, these variables are
initialized to constructor and as we know, constructor will execute when object of
respective class is created. In inheritance, we always create object for latest subclass and
not for super class. Hence, the constructed method defining are super classes.

Use of super keyword: Super keyword is used by java programmer in inheritance to


access the method and variable of super classes in its subclass. To use super keyword,
Following are some restriction which we must obey at time of implementation.
1. Super keyword always use in subclass
2. To use super, there must be inheritance
3. Super keyword always used in subclass constructor
4. In subclass construct, at first line super keyword must be used.
Following program demonstrate use of super keyword to access constructor of
super class in subclass.

E.g.. class A
{
int a,b;
A()
Java Programming by Ms.K.S.Jadhav

{ a=10,b=2
0;
}
void show()
{
System.out.println(a+b);
}
}
class B extends A
{
int k;
B()
{
super();
k=100;
System.out.println(a+b+k);
}
}
class M
{
public static void main(String args[])
{
B obj=new B();
obj.show();
}
}

In java, we use super keyword to access the base class constructor as shown in
previous program.
Eg: super();
Secondly, super keyword also used like this keyword here it always point to the
variable of super class.
Eg: super.a=10;
In third way, super keyword is also used to access the methods define in base
class or super class of subclass.
Eg: super.show();

Rules to use super keyword:

When we want to use, there must be inheritance exist. Super keyword is always used in
subclass at very first line of using method
Following program demonstrate use of super keyword as this.
Java Programming by Ms.K.S.Jadhav

E.g.. class A
{
int k;
void show()
{
System.out.println(k);
}
}
class B extends A
{
int l;
void disp()
{
System.out.println(l);
}
B(int a,int b)
{
super.k=a;
l=b;
}
}
class Demo
{
public static void main(String args[])
{
B x=new B();
x.show();
x.disp();
}
}

Q. Use the super keyword to access super class method in next subclass
Ans: class A
{
int k;
void show()
{
System.out.println(k);
}
}
class B
Java Programming by Ms.K.S.Jadhav

{
int l;
void show()
{
super();
System.out.println(l);
}
B(int a,int b)
{
super.k=a;
l=b;
}
}
class Demo
{
public static void main(String args[])
{
B x=new B(10,20);
B.show();
}
}

Polymorphism in Java/Method over-riding/Dynamic method


dispatching: To use one function name with several methods, we implement method
overloading by making some difference
1. At returntype
2. No. of arguments
3. By changing datatype of parameter
Following program demonstrate use of method over-riding in
java. class Java
{
void show()
{
System.out.print(“void show()”);
}
int show() //same function name but difference in return type
{
System.out.println(“int show()”);
return 0;
}
}
class Hello
Java Programming by Ms.K.S.Jadhav

{
public static void main(String args[])
{
Java jb=new Java();
Jb.show(); // method
overloading int a=jb.show(); // method
overloading
}
}
Following program demonstrate use of method over-riding in java and
difference between method overloading and overriding

E.g.. class Java


{
void show()
{
System.out.print(“Super”);
}
}
class Java1 extends Java
{
void show()
{
System.out.println(“Sub”);
}
}
class Hello
{
public static void main(String args[])
{
Java1 ja=new Java1();
Java jb=new Java();
Java jd; //Reference of super class
Jd=ja; //Reference initializing by the object of subclass
jd.show(); // call method of subclass
Jd=jb; //Reference initializing by the object of superclass
Jd.show(); // call method of superclass
}
}
In method over-riding, programmers always find same method name, same
number of argument i.e. in super or base class. To distinguish between call, the
programmer use reference of super class which is initialized by object of respective
classes as shown in above code.
Java Programming by Ms.K.S.Jadhav

Array of object: When we require more than 1 object, we use array of object to create
set of object. In java, first we create set of reference which is later initialize by class
constructor using loop.
Following program demonstrate use of area to access method of class by different
object.

E.g.. class ObjDemo


{
void display()
{
System.out.println(“Method access “);
}
}
class Demo
{
public static void main(String args[])
{
ObjDemo D[]=new ObjDemo[10];
for(int i=0;i<D.length;i++)
{
D[i].display();
}
}
}

Q. WAP to read and display record of 10


employee Ans. class Employee
{
String name;
int id;
Employee(String nm.,int rl)
{
name=nm;
id=rl;
}
void display()
{
System.out.println(“Name=”+name);
System.out.println(“ID=”+id);
Java Programming by Ms.K.S.Jadhav

}
}
class test
{
public static void main(String args[])
{
Employee e[]=new Employee[3];
e[0]=new Employee(“ABC”,28);
e[1]=new Employee(“PQR”,1111);
e[2]=new Employee(“XYZ”,2113);
for(int i=0;i<e.length;i++)
e[i].display();
}
}
Q.WAP to find the average mark of 3 student when mark of three sub for each student is
given
Ans: class Avg
{
int a,b,c;
Avg(int a,int b,int c)
{
this.a=a;
this.b=b;
this.c=c;
}
void average()
{
int s=a+b+c;
double a=s/3.0;
System.out.println(“Mean is”+a);
}
}
class test
{
public static void main(String args[])
{
Avg a[]=new Avg[3];
a[0]=new Avg(42,76,85);
a[1]=new Avg(22,12,55);
a[2]=new Avg(90,91,93);
for(int i=0;i<a.length;i++)
a[i].average();
Java Programming by Ms.K.S.Jadhav

}
}

Wrapper classes: In programming language like C, C++, programmers are able to


pass the reference of variable.
E.g.: If we declare one int variable as shown below:
show (a);
Or
show(&a);
He/She is able to pass it by reference.
As we know java cannot provide address of variable. Hence, we are not able to
pass the reference value of primitive data type.
To implement above, java provide wrapper classes. These classes are also used to
cast the entered value in required way. This wrapper classes are provided by java.lang.*
package which is the default package for java programming. The Number class is the
super class of following classes . It is and abstract class which consists following classes:
1. Double
2. Float
3. Integer
4. Short
5. Long
6. Byte
The another wrapper classes are
1. Character
2. Boolean
All the above classes are wrapped in java.lang.* package where each class is of static
type.
Note: There is another Void class which consist TYPE field. It acquires null space rarely
used by java programmer.

Byte class: This class extends from Number class and implements the abstract methods
of Number class. It consist two constructor that we use to create byte class are as:
1. Byte(String value);
2. Byte(byte value);
Here, 1st constructor is used to pass a string value that we wish to initialize for byte
object. It always throw NumberFormatException.
2nd constructor is used to pass byte value which will wrapped by byte class object.
1. Byte(String value);
2. Byte(byte value);
The other methods of Byte class are as follows:

1. byteValue(): It return object as a byte type.


Java Programming by Ms.K.S.Jadhav

Eg: byte b=obj.byteValue();


2. compareTo(Byte object): This method is used to check the numerical value
of invoking object
Eg: int i= A.compairTo(B);
3. equals(Object obj): This method returns true value if invoking object is
equivalent to object of Byte type else it will return false.
boolean b = A.equals(B);

4. parseByte(String str): This method is used to convert the String value in


byte equivalent.
byte b=Byte.parseByte(“123”);
Following program demonstrate the use of Byte wrapper class

E.g.: class ByteDemo


{
public static void main(String args[])
{
double d;
boolean b11,b12;
byte b;
int a,i;
Byte b1=new Byte (10);
Byte b2=new Byte (“199”);
b11=b1.isDigit ();
Byte b3;
b12=b1.equals (b2);
try
{
b=Byte.parseByte (b2);
}
catch (NumberFormatException e)
{}
System.out.println (b11+b12+b);
}
}
}
Short Wrapper class: This class extends from Number class, implement the abstract
method that provide by Number class. This class consist two constructors.

1. Short(short num);
2. Short(String str);
Java Programming by Ms.K.S.Jadhav

Here, first constructor receives arguments as a short primitive type where second
constructor is used to create object for Short class which is initialized by specified String.
E.g.. Short s=new Short(“Xyz”);
This constructor always throws NumberFormatException. The other methods that used
by short object are as follows:

1. byteValue(): This method returns byte type of value for invoking


object, Syntax:byte byteValue();
E.g.: byte b=s1.byteValue();
Here, byteValue() method is used by Short object s1 which is convert into byte to
initialize byte type of b variable.

2. compareTo(): This method always return int value. It always compare


between two value. It always compare invoking object with argumented value. It
returns 0 if both are equal. It returns positive value when invoking object is
greater than argumented value else return negative value.
Syntax: int i=s1.compareTo(20);
E.g.. Short s1=new Short(20);
short s=20;
Note: compareTo method is also used to compare
objects. Syntax: int compareTo (Object obj);
This will compare argumented object with invoking object to check whether it is a
member of short class or not.
E.g.: Short s1=new Short ();
Short s2=new Short ();
int i=s1.compareTo (s2);
This method always throws ClassCastException.

3. DoubleValue (): This method is used with Short object to convert in


double. Syntax: double doubleValue ();
E.g.: double d=s1.doubleValue ();
Here, d variable is initialized by Short object s1 by calling doubleValue () method.

4. floatValue (): This method is used to convert the floating value of invoking
object.
E.g.: float f=s1.floatValue ();

5. equals (): This method returns true value if invoking object short is equal to
argumented object otherwise it returns false.
Syntax: Boolean equals(Short s);
E.g.: boolean b=s1.equals(s2);
Java Programming by Ms.K.S.Jadhav

6. parseShort (String s): This method always return short value equivalent to
the number contained in String specified by 3. This method is of static type.
Syntax: static short parseShort(String str);
E.g.: short s=Short.parseShort(“20”);
Here, String “20” converted is short int value to initialize variable s
In second version of this same method, we also specify the radix for number.
E.g.: short s=Short.parseShort(“20”,10);
Syntax: static short parseShort(String s,radix);
This method throws NumberFormatException

7. toString (): This method is used to return String value for invoking
object. Syntax:String toString ();
E.g.: Short s1=new Short (20);
String s=s1.toString ();

8. valueOf(): This method returns short object specified by String. It will always
throw NumberFormatException.
Syntax: short valueOf(String str)
E.g.: s2=Short.valueOf(“20”);
Following program demonstrates the use of short class

E.g.: class Demo


{
public static void main(String args[])
{
String str=”ABC”;
short s;
int i;
long l;
double d;
boolean b;
Short s1=new Short(20);
Short s2=new Short(“20”);
Short s3=new Short(40);
i=s1.intValue();
b=s1.compareTo(s3);
boolean b1=s1.equals(s3);
try
{
short ss=Short.parseShort(str);
Java Programming by Ms.K.S.Jadhav

}
catch(Exception er)
{}
System.out.println(b+b1+ss+i+s1+s3+ s2);
}
}

Integer wrapper class: This wrapper class is used to wrap Integer type variable
to create in appropriate number. It consists of two constructors:

1. Integer(int number);
2. Integer(String str) throws NumberFormatException

The other methods of Integer class are as follows:

1. byteValue (): This method is used with Integer object so to convert value
of invoking object into byte.
E.g.: byte b=b1.byteValue();
Here, b1 is an object for Integer class
Integer b1=new Integer(100);

2. compareTo(): This method is used to compare the invoking value with


object. If it is equal, then it returns 0. If invoking value is greater than object to
which it is attached, it returns positive value else returns negativevalue
Syntax: int compareTo();
E.g.: int i=b1.compareTo(10);

3. toString(): This method always return String value for its invoking
value. Syntax: String toString();
E.g.: String s=b1.toString();

4. valueOf(): This method is used to return Integer value of specified


String. Sytax: static int valueOf(String str) throws NumberFormatException
E.g.: try
{
int r=Integer.valueOf(“20”);
}
catch(NumberFormatException e)
{}
Java Programming by Ms.K.S.Jadhav

Float wrapper class: This wrapper class is used to manipulate float variable. It uses
three type of constructor to create object as shown below:

Float (float number): This constructor is used to create Float object which is
initialized by floating value by number of object.
E.g.: Float f=new Float(7.14f);

Float (double num): This constructor is used to create float object which is
initialized by double value.
E.g.: Float f=new Float(6.42);

Float (String str) throws NumberFormatException: This constructor is used


by programmer to initialize float object through suitable String.
E.g.: Float f=new Float (“123.04f”);

The other method that encapsulate in float wrapper class are as follows:

byte byteValue (): This method used with float object to convert them as byte
value Syntax: byte byteValue();
E.g.: byte b=f.byteValue();
The above statement convert value of invoking object into byte
Whenever floating object is created and properly initialized.
E.g.: Float f=new Float(123.05f);

int compareTo: This method always return Integer value. It returns 0 when value of
invoking object is equal to argumented value. If invoking value is greater, it return
positive value else negativevalue.
Syntax: int compareTo(float
f); E.g.: int i=f.compareTo(f1);
When f and f1 are floating object and initialized properly. Its next modified
version compare object type of argument with invoking float object.
Syntax: int compareTo(Object ob);
It is similar to 1st version o this method. It simply check that argumented object ob
is of class Float or not.
Note: This method always throws ClassCastException

equals: This method always return Boolean values whenever comparison between
invoking object and argumented object is performed.
Syntax: Boolean equals(Object ob);
E.g.: boolean b=f.equals(f1);
Java Programming by Ms.K.S.Jadhav

toString(): This method is used to convert floating number into


String. E.g.: String s=f.toString();
Whenever we create object f and properly initialize as shown in following
statement.
This specified value convert into String value.

Special Methods of Float class:

isNaN(): This method is used to check the given value is a number or not. Here, NAN means
not a number. This method always return boolean type of value.
Syntax: isNaN();
E.g.: boolean b=f.isNaN();
System.out.println(b);
output: true
This method also have some modified version from where we check value from floating
value,
Syntax: static boolean isNan(float
num); E.g.: Float f=123.45f;
float f1=0;
boolean b,b1;
b=Float.isNaN(f);
System.out.println(b);
b1=Float.isNaN(f);
System.out.println(b1);
output: true

isInfinite(): This method is used to check whether invoking object is initialized through
infinite value or not. If it is infinite, it return true else false.
Syntax: boolean isInfinite();
E.g.: Float f=new Float(0);
boolean
b=f.isInfinite();
System.out.println(b);

Double wrapper class: This class is used to handle double type of variable. This class is
extended by Number class. The constructor of double class are:

1. Double(double d);
2. Double(String s);

Here,second constructor throws NumberFormatException.


Double and Float class consist constant value like:

1. MAX_VALUE: This will indicate maximum positive value.


Java Programming by Ms.K.S.Jadhav

2. MIN_VALUE: This indicate minimum positive value.

3. POSITIVE_INFINITY: This will indicate positive infinity.

4. NEGATIVE_INFINITY: This will indicate negative infinity.

5. NaN: Not a Number

Character wrapper class: This class is used to wrap char type of variable.
All the methods of the char class are static by nature.
This class consists only one constructor that is used to create character
type of object which is initialized by char variable.
Syntax: Character(char ch);
Where, ch specify the character that is wrapped by Character object.
The various method that define by character class are as follows:

isDefine(): This method is used to check whether character specified by ch


variable is defined by UNICODE or not. If that char is defined by UNICODE, it
return true value else false.
Syntax: static boolean isDefine(char ch);
E.g.: char arr='A';
boolean b=Character.isDefined(arr);
Output: true
If char is used for UNICODE, it return true.

isDigit(): This method is used to check whether the specified char is digit or
not. It returns true if ch is a digit else false.
Syntax: static boolean isDigit(char ch);
E.g.: char arr='6';
boolean b=Character.isDigit();
Output: true

isLetter(): This method is used to examine that the specified ch value is


letter or not. If it is letter, it returns true else false.
Syntax: static boolean isLetter(char
ch); E.g.: char arr='7';
boolean b=Character.IsLetter(arr);
System.out.println(b);
Output: false

isLetterOrDigit():This method returns true value if specified value is a


letter or digit else it return false.
Java Programming by Ms.K.S.Jadhav

Syntax: static boolean isLetterOrDigit(char ch);


E.g.: char a='7';
boolean b=Character.isLetterOrDigit();
System.out.println(b);
Output: true

isLowerCase(): This method is used to check whether specified value is


lowercase letter or not.
Syntax: static boolean isLowerCase(char ch);
E.g.: char a='A';
boolean b=Character.isLowerCase(a);
System.out.println(b);
Output: false

isUpperCase(): It is similar to above method but used to check whether


specified char or letter is in upper letter or not.
Syntax: static boolean isUpperCase(char ch);
E.g.: char a='A';
boolean b=Character.isUpperCase(a);
System.out.println(b);
Output: true

toUpperCase(): It is similar to above method but used to convert lower


case letter into upper case letter.

Q.WAP to find the number of letter and digit in given character


array. Ans: class Demo
{
public static void main(String args[])
{
char ar[]={'A','a','7'};
int d=0,c=0;
for(int i=0;i<=arr.length;i++)
{
if(Character.isDigit(ar[i]))
d++;
else c+
+;
System.out.println("Number of digits:"+d);
System.out.println("Number of characters:"+c);
}
}

Boolean wrapper class: This wrapper class is used to manipulate Boolean data type.
This class contains 2 constructors.
Java Programming by Ms.K.S.Jadhav

Boolean(boolean value);
Boolean(String boolString);

Here,1st constructor is used by programmer to create Boolean type of object which


is initialized by true value as shown in E.g..
Whereas 2nd constructor is used to create an Boolean object which is initialized by
String as shown in 2nd example:
The other method define by Boolean class are follows.

equals(): This method is used to check that invoking object is equivalent to argumented
object . If both are equal, it return true else false.
Syntax: boolean equals(Object ob);
E.g.: boolean b=B1.equals(B2);
System.out.println(b);
Output: true
toString(): This method is used to convert argumented value into
String. Syntax: String toString();
E.g.: Boolean B1=new Boolean(true);
String s=B1.toString();
System.out.println(s);
Output: true

String class: Java provide String as a in-build class to make set of character as String
which made an easily manipulation of String object . Because of String class,
programmer are able to create its object which allow access to various method define in
String class for different String operation. E.g., we can perform following same
operation on String value.
1. We can initialize.
2. We can concatenate or join.
3. We can copy one on another.
4. We can replace any character by another on all character replace by
some character.
5. We can create sub-String.
6. We change the order of indexed for each char in String.
7. We can perform searching or sorting.
To perform all the above function, java String class provide all the
above function. These String class encapsulate in following package.
java.lang.Object.String;
This class is defined in default package as follows:
public final class String extends Object implements CharSequence,
Serializable, Compacable
Java Programming by Ms.K.S.Jadhav

Different constructor of String class are as follows:

String(): This constructor will create the instance of the String with no
character. Syntax: String();
E.g.: String s=new String();
Here, s object is initialized later by some values.
E.g.: s=”XYZ”;

String(char a): This constructor is used to initialize String object by any character
array.
E.g.: char a[]={‘R’,’A’,’M’};
String s=new String(a);
System.out.println(s);
Output: RAM
The above example demonstrates the use of 2nd constructor which make individual
character as a set of character or String. In other word, we can say that it is used to
convert character array in String.

String(char arr[], int start, int end): This constructor is used by programmer to
extract subset of char on given char array to make them as String.
E.g.: char arr[]={‘7’,’R’,’A’,’M’,’0’,’100’};
Sting s=new String(a,1,3);
System.out.println(s);
Output: RAM

String(String object): This constructor is used to initialize String object by another


object which is already initialize.
E.g.: String x=”ABC”;
String s=new String(x);
System.out.println(s);
Output: ABC
We copy the content of x object into s String object. It will demonstrate the used
to copy constructor where one object is initialize by the another object.

String(byte arr[]): This constructor is used to create a String object from a byte
array.
E.g.: byte b[]={65,66,67};
String s=new String(b);
System.out.println(s);
Output: ABC
Java Programming by Ms.K.S.Jadhav

This constructor is used to convert numeric value into their respective ASCII
characters.

String(byte ar[], int start, int end): This constructor is used to create a String
object from a byte array starting from specified offset and specified end.
E.g.: byte b[]={95,96,97,98,99};
String s=new String(b,1,3);
System.out.println(s);
Output: bcd

Literal: As we seen in above example, we always create object of String class to


hold set of character but in some situation, we can directly assign String value to its
respective object. In such situation, we can directly assign String value to its respective
object. In such situation, java automatically construct String object. Such type of
initialization is referred as String literals which is used to initialize String objects.
E.g.: String s=”XYZ”;
Here, s object is create from default constructor. String automatically initialize by
proper set of character.

Methods:

length():This method also referred as String operator. It operate to calculate the


number of character each String consist that mean is used to calculate the length of
String which is equal to the number of character into given String. This method always
return the Integer value.
E.g.: String s=”XYZ”;
int i=s.length();
System.out.println(i);
Output: 3
The above example calculate the length of invoking object X.

String concatenation: To join two String in java, we use +sign or + operator. This
operator when applied on two String value, it simply concatenate them and stored result
om 3rd String.
E.g.: String x=”PQR”;
String y=”ABC”;
String s=x+y;

String conversion: If we want to convert any data into String, it will does by toString
method.
Syntax: String toString();
Java Programming by Ms.K.S.Jadhav

E.g.: byte b={1,2,3};


Byte b=new Byte(b);
String s=b.toString();
String x=”PQR”;
In above example, 1st we convert byte object in String which will convert another
result and both result are displayed.

Character extraction method: String class provide various method which is


used to extract character from given String specified below.

charAt(): This method is used to extract single character from given String at specified
location.
Syntax: char charAt(int loc);
E.g.: String x=”PQR”;
char c=x.charAt(2);
System..out.println(c);
Output: R

getChar(): This method is used to obtain more than one character from the given
String.
Syntax: void getChar(int start, int end, target[], in
targetstart); E.g.: char ar[]=target[];
String s=”ABC”;
s.getChar(0,2,arr,0);

getBytes(): It is alternative method to get char which is used to store the bytes in array.
This method’s genral formis as follows:
Syntax: byte[] getByte();
E.g.: for(int i=0;i<=s.length;i++)
b[i].getBytes();

String comparison: This class provide various method to compare String with sub-
String.

equals(): This method returns boolean value true if Strings are equal else
false. Syntax: boolean equals();
E.g.: boolean b=s.equals(s1);

equalsIgnoreCase(): This method is similar to equal method. Only difference is that,


it ignore the case of String.
Syntax: boolean equalsIgnoreCase(Object ob);
Java Programming by Ms.K.S.Jadhav

E.g.: String s=”ABC”;


String s2=”abc”;
boolean b=s.equalsIgnoreCase(s2);
Output: true

compareTo(): This method always return Integer


value. Syntax: int compareTo(Object obj);
It return 3 type of int value.
1. 0 when comparison between String is found equal.
2. positive value when 1st String is larger.
3. negativevalue when 2nd String is larger.

E.g.: String s1=”all”;


String
s2=”ball”;
int i=s1.compareTo(s2);
System.out.println(i);
Output: -1

= =(Equals to Operator): This operator is used to compare 2 different String


object. It is differ from equals method. In sense, it check the reference value is set or not.
It check the value is same or not. Whereas, equals method check the equality between
initialize String.
Syntax: boolean Object1= = Object2;
E.g.: String s=”ABC”;
String s2=”XYZ”;
boolean b=s= =s2;
System.out.println(b);
Output: false
Here, = = operator compare two String object reference to see whether they refer
to same instance or not.

Searching method: String class provide various searching method that are useful to
find but the character in String or in char or that are useful to find out String in given
sentence. To perform this type of searching, it provide two methods:

indexOf(): This method is used to find the 1st occurrence of given character. This
method is used to find character and String in given sentecnce.
Syntax: int indexOf(char ch);
This method is used to find the index of specified character in given String. In
response, it return its index value.
E.g.: String s=”ABC”:
char ch=’C’;
Java Programming by Ms.K.S.Jadhav

int i=s.indexOf(ch);
System.out.println(i);
Output: 2

Syntax: int indexOf(String str);


This method is used by java programmer to find the indexed value of specified
String in given sentence.

E.g.: String msg=”Today is nice


day”; int
i=msg.indexOf(“nice”);
System.out.println(i);
Output: 9
In other words, we cansay that this method is also used to find substring in given
sentence. It will return starting index of specified String value.

int lastIndexOf(): This method is used by java programmer to find the last index of
specified char or String in given sentence.
Syntax: int lastIndexOf(char ch);
E.g.: String s=”XYZ”;
int n=s.lastIndexOf(“z”);
System.out.println(n);
Output: 2

String modifying methods: String class also provide same method that are used to
modify so to create another String.

substring(): This method is used to create another String object from given
String. Syntax: String substring(int startingindex);
E.g.: String msg=”This is a nice day”;
String s=msg.subString(9);
System.out.println(s);
output: nice day
In above example, substring method is create another object from existing String
where we provide the starting index of new String in given sentence. From that given
sentence, it will create another value s.

concat(): This method is used to add a String its genral format is as


follows: Syntax: String concat(String str);
E.g.: String msg=”PQR”;
String msg2=msg.concat(“STU”);
System.out.println(msg);
Output: PQRSTUV
Java Programming by Ms.K.S.Jadhav

replace(): This method is used to replace the specified character. This method use
invoking String value and return modified String.
Syntax: String replace(char oldchar, char
newchar); E.g.: String s=”ROHIT”;
String s1=s.replace(‘R’,’M’);
System.out.println(s1);
Output: Mohit

trim(): This method return copy of String for which it invoke. The only difference is
that it replace leading and trailing white space in String.
Syntax: String trim();
E.g.: String x=” HI “:
String s=x.trim();
System.out.println(s);
Output: HI

startsWith(): This method determine whether given String startswith specified String
or not. If it bE.g.in with specified String, it returns true else false.
Syntax: boolean startsWith(String
str); E.g.: boolean b;
String s=”XYZ”;
b=s.startsWith(“XY”);
System.out.println(b);
Output: true

endsWith(): This method is used to find whether String ends with specified String or
not. It returns a boolean value.
Syntax: boolean endsWith(String
str); E.g.: String s=”ROHIT”;
boolean b=s.endsWith(“HIT”);
System.out.println(b);
Output: true
There is one another modified version of class String available where he/she is
specify String index for matching.
Syntax: boolean startsWith(String str, int
index); E.g.: String a=”ROHI”;
boolean b=a.startsWith(“HIT”,2);
Output: true

Changing or modifying case within String : To modify the case of given String,
String class provide 2 different methods.
Java Programming by Ms.K.S.Jadhav

toLowerCase(): It is used to convert the case of invoking String in lowercase.

toUpperCase(): It is used to convert invoking String into uppercase.

Both methods return String. The general format:


String toLowerCase/toUpperCase();
StringBuffer class: It is similar to String class , but its object consist 16 bytes more than
Sting object . It so to avoid the problem of relocation.
Eg: StringBuffer sb =new StringBuffer();

String represents fixed-length, immutable character sequences. In contrast, StringBuffer


represents growable and writeable character sequences. It is possible to insert the
characters anywhere inside the StringBuffer. StringBuffer will automatically grow to
make room for such additions and often has more characters pre-allocated than are
actually needed, to allow room for growth.

Creating StringBuffer

StringBuffer class defines three different constructors:

StringBuffer()

StringBuffer(int size)

StringBuffer(String str)

The first form i.e. default constructor reserves room for 16 characters without
reallocation. The second form accepts an integer argument that explicitly sets the size of
the buffer with given value. The third form accepts a String argument that sets the initial
contents of the StringBuffer object and reserves room for 16 more characters without
reallocation. StringBuffer allocates room for 16 additional characters when no specific
buffer length is requested, because reallocation is a costly process in terms of time. Also,
frequent reallocations can fragment memory. By allocating room for a few extra
characters, StringBuffer reduces the number of reallocations that take place.

StringBuffer operations and methods

Several methods of classes String and StringBuffer are same but as per
the functionality, StringBuffer has been added with some special methods.

length( ) and capacity( )


Java Programming by Ms.K.S.Jadhav

The ‘length( )’ finds total number of characters that a StringBuffer is having in it.
The total allocated capacity (no. of characters) can be found using the capacity( ) method.

Syntax:

int length()

int capacity()

Example:

StringBuffer sb = new StringBuffer("Oriya");

int len = sb.length()); //len will be 5

int cap = sb.capacity()); //cap will be 21

Here the variable len will contain total number of characters i.e. 5 and cap will
contain capacity 21 i.e. actual length + additional room for 16 characters.

ensureCapacity( )

If we want to pre-allocate room for a certain number of characters after a


StringBuffer has been created, we can use ensureCapacity( ) to set the size of the buffer.
This is useful if we know in advance that we 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.

Example:

StringBuffer sb = new

StringBuffer(10);

sb.ensureCapacity(20);

setLength( )
Java Programming by Ms.K.S.Jadhav

It is used to set the length of the buffer within a StringBuffer object. Its general form
is:

void setLength(int len)

Here, len specifies the length of the buffer. This value must be nonnegative. When
we increase the size of the buffer, null characters are added to the end of the existing
buffer. If we call setLength( ) with a value less than the current value returned by
length( ), then the characters stored beyond the new length will be lost.

setCharAt( )
If we want to set the character at certain index in the StringBuffer with specified
value, this method can be used. It has following form:

void setCharAt(int index, char ch)

Here, ‘index’ is the position within StringBuffer whose value is to be set with value
‘ch’.

Example:

StringBuffer sb = new

StringBuffer(“Kolkata”); sb.setCharAt(0,‘C’);

After execution of these statements, ‘sb’ will be “Colkata”.

append( )

The append( ) method concatenates the string representation of any other type of data
to the end of the invoking StringBuffer object. It has overloaded versions for all the built-
in types and for Object. Following are a few of its forms:

StringBuffer append(String str)

StringBuffer append(int num)

StringBuffer append(Object obj)

Example:
Java Programming by Ms.K.S.Jadhav

StringBuffer sb = new StringBuffer("cricket");

int x = 52;

float f = 13.4f;

StringBuffer a = sb.append(x); //a will be cricket52

StringBuffer b = sb.append(f); //b will be cricket5213.4

insert( )
This method is used to insert one string, character or object into another string.
Forms of this method are:

StringBuffer insert(int index, String str)

StringBuffer insert(int index, char ch)

StringBuffer insert(int index, Object obj)

Here the ‘index’ specifies the index position at which point the string will be
inserted into the invoking StringBuffer object.

Example:

StringBuffer sb = new StringBuffer("I Java!");

sb.insert(2, "love ");

After this, the contents of ‘sb’ will be “I love Java!”

reverse( )

We can reverse the characters inside the StringBuffer

using reverse( ) method.

Syntax:

StringBuffer reverse()
Java Programming by Ms.K.S.Jadhav

This method returns the reversed object upon which it is called.


Example:

StringBuffer s = new

StringBuffer(“Yellow”); s.reverse(); //s will

be “wolleY”

delete( ) and deleteCharAt( )


These methods are used to delete a single character or a sequence of characters from
the StringBuffer.

Syntax:

StringBuffer delete(int startIndex, int endIndex)

StringBuffer deleteCharAt(int loc)

The delete( ) method deletes a sequence of characters from the invoking object.
Here, ‘startIndex’ specifies the index of the first character to remove, and ‘endIndex’
specifies an index one past the last character to remove. Thus, the substring deleted runs
from ‘startIndex’ to ‘endIndex’–1. The resulting StringBuffer object is returned.
ThedeleteCharAt( ) method deletes the character at the index specified by ‘loc’. It returns
the resulting StringBuffer object.

Example:

StringBuffer sb = new

StringBuffer("Chandramukhi"); sb.delete(4, 7); //sb

will be “Chanmukhi” sb.deleteCharAt(0); //sb will be

“hanmukhi”

The methods such as getChars, replace, substring, indexOf and lastIndexOf are
having the same syntax and use as that of String class except here the manipulation is
with StringBuffer only.

Java Utility package[java.util.*]: There is one another package java utility which
Java Programming by Ms.K.S.Jadhav
is useful for manipulating set of elements of similar or dissimilar elements.
This package provides classes like
 Arrays
Java Programming by Ms.K.S.Jadhav

 ArrayList
 Vector
And some useful interface like enumeration. This classes are useful to handle the
set of elements to maintain their order to find particular element or fill particular pattern.

Arrays class : To use this class, we must import java.util.* ;package at begining of
program. This class provide various methods when we work with array. Arrays is a
static type class.The methods of Arrays class are as follows:

binarySearch(): This method uses binary search technique to search. To use


this method, array must be sorted previously. This method has following syntax:
Syntax: static int binarySearch(byte arr[], byte b);
Syntax: static int binarySearch(int arr[], int b);
Syntax: static int binarySearch(char arr[], char b);
E.g.: int a[] = new int[10];
int i=Arrays.binarySearch(arr[i],2);
If searching is not found in given array, then it will return negative value or
index value. Sometimes it throws ClassCastException when it is not able to convert type
of array in required way.

equals(): This method is used to compare the two arrays. It checks the element of 1st
arrary with element of another array. If both arrays are same, it will return true otherwise
false.
Syntax: static boolean equals(Arraytype arr, Arraytype
arr2); E.g.: boolean b = Arrays.equals(int arr[], int b[]);
Here, 2 arrays are compared for equality.

fill(): This method is used to assign a value to all elements in array. In other words, we
can say that it fills an array with specified numbers or symbol.
Syntax: static void fill(byte ar[],byte value);
E.g.: Arrays.fill(arr[i], -1);
Here, arr[] is fill by -1 value. This fill method is work with all types of array. In
2nd form, programmer are able to specify the starting and end position for the filling
values in given array.
Syntax: static void fill(byte arr[], int fvalue, int evalue);
E.g.: Arrays.fill(arr[i], 2, 6, -1);
ArrayList class:

Vector class:
The package java.util contains a library of Java’s utility classes. One of them is
Vector class. It implements a dynamic array which can hold the array of any type and any
Java Programming by Ms.K.S.Jadhav

number. These objects do not have to be homogenous. Capacity of the Vector can be
increased automatically.

Creation of Vector
Vector class defines three different constructors:
1) Vector()
2) Vector(int size)
3) Vector(int size, int incr)

The first form creates a default vector, which has an initial size of 10. The second
form creates a vector whose initial capacity is specified by ‘size’ and the third form
creates a vector whose initial capacity is specified by ‘size’ and whose increment is
specified by ‘incr’. The increment specifies the number of elements to allocate each time
when new elements are added in the vector.
All vectors start with an initial capacity. After this initial capacity is reached, the next
time when we attempt to store an object in the vector,the vector automatically allocates
space for that object plus extra room for additional objects. By allocating more than just
the required memory,the vector reduces the number of allocations that must take place.
The amount of extra space allocated during each reallocation is determined by the
increment that we specify when we create the vector. If we don’t specify an increment,
the vector’s size is doubled by each allocation cycle.

The Vector class defines three protected data members are:

1) int capacityIncrement;

2) int elementCount;

3) Object[] elementData;

The increment value of vector is stored in ‘capacityIncrement’. The number of


elements currently in the vector is stored in ‘elementCount’.The array that holds the
vector’s elements is stored in ‘elementData’.

Vector operations and methods


Following are the methods defined by Vector class for its operation.

void addElement(Object element):


The object specified by element is added to the vector.

int capacity()
It returns the capacity of the vector.
Java Programming by Ms.K.S.Jadhav

Object clone()
It returns a duplicate copy of the invoking vector.

boolean contains(Object element)


It returns true if ‘element’ is contained by the vector, and returns false if it is not.

void copyInto(Object array[])


The elements contained in the invoking vector are copied into the array specified by
‘array’.

Object elementAt(int index)


It returns the element at the location specified by ‘index’.

void ensureCapacity(int size)


This method sets the minimum capacity of the vector to ‘size’.

Object firstElement( )
It returns the first element in the vector.

int indexOf(Object element)


It returns the index of the first occurrence of ‘element’. If the object is not found in
the vector, –1 is returned.

int indexOf(Object element, int start)


It returns the index of the first occurrence of ‘element’ at or after ‘start’. If the object
is not in that portion of the vector, –1 is returned.

void insertElementAt(Object element, int index)


It adds ‘element’ to the vector at the location specified by ‘index’.

boolean isEmpty()
This method returns true if the vector is empty and returns false if it contains one or
more elements.

Object lastElement()
It returns the last element in the vector.

int lastIndexOf(Object element)


It returns the index of the last occurrence of ‘element’. If the object is not in the
vector, –1 is returned.
Java Programming by Ms.K.S.Jadhav

int lastIndexOf(Object element, int start)

It returns the index of the last occurrence of ‘element’ before ‘start’.If the object is
not in that portion of the vector, –1 is returned.

void removeAllElements()
This method empties the vector. After is execution, the size of the vector is zero.

boolean removeElement(Object element)


It removes ‘element’ from the vector. If more than one instance of the specified
object exists in the vector, then it is the first one that is removed. This method returns
true if successful and false if the object is not found.

void removeElementAt(int index)


It removes the element at the location specified by ‘index’.

void setElementAt(Object element, int index)


Here, the location specified by ‘index’ is assigned ‘element’.

void setSize(int size)


It sets the number of elements in the vector to ‘size’. If the new size is less than the
old size, elements are lost. If the new size is larger than the old size, ‘null’ elements are
added.

int size()
It returns the number of elements currently in the vector.

String toString()
It returns the string equivalent of the vector.

void trimToSize()
It sets the vector’s capacity equal to the number of elements that it currently holds.
That is it makes capacity equal to size.Program below demonstrates the use of some
Vector methods and operations.

// Demonstration various Vector


methods. import java.util.Vector;
class VectorDemo
{
public static void main(String args[])
{
Vector v = new Vector(3, 2);
Java Programming by Ms.K.S.Jadhav

System.out.println("Initial size: " +


v.size()); System.out.println("Initial
capacity: " +
v.capacity());
v.addElement(new Integer(23));
v.addElement(new Float(9.6f));
v.addElement(new String("Hello"));
v.addElement(new Integer(42));
System.out.println("Capacity after 4 additions: " +
v.capacity());
v. addElement(new Double(63.2));
System.out.println("Current capacity: " +
v.capacity());
System.out.println("Current size: " +
v.size());
v.addElement(new Double(19.44));
v.addElement(new Integer(7));
System.out.println("First element: " +
(Integer)v.firstElement());
System.out.println("Last element: " +
(Integer)v.lastElement());
if(v.contains(new Integer(42)))
System.out.println("Vector contains 3.");
System.out.println("Vector : "+v.toString());
v.setSize(8);
System.out.println("Vector :
"+v.toString()); Object o = new Object();
o = v.clone();

System.out.println("New Vector: "+o);


v.removeAllElements();
if(v.isEmpty())
System.out.println("Vector is empty");
}
}
Vector methods demonstration
Output:
Initial size: 0
Initial capacity: 3
Capacity after 4 additions: 5
Current capacity: 5
Current size: 5
First element: 23
Java Programming by Ms.K.S.Jadhav

Last element: 7
Vector contains 3.
Vector : [23, 9.6, Hello, 42, 63.2, 19.44, 7]
Vector : [23, 9.6, Hello, 42, 63.2, 19.44, 7, null]
New Vector: [23, 9.6, Hello, 42, 63.2, 19.44, 7,
null] Vector is empty

For adding elements, the Object representation of the primitive data types is used.
We can not directly add the values inside the vector. This object representation is referred
as wrapper class.

Difference between Array,Arrays,ArrayList and Vector class.


Array Arrays ArrayList Vector
1) its a 1) its class 1) its class 1) its class
var.
declaration
technique
2) to perform any 2) provide inbuilt 2) provide inbuilt 2) provide inbuilt
operation we have to methods to perform methods to perform methods to perform
define methods each operations like operations like operations like
time search , sort search , sort search , sort
3) different types of 3) single type , static 3) single type 3) single type
array available class
4) array name with 4) class_name use to 4) object use to 4) object use to
location used to access data and access data access data and
access data methods methods
5) elements are not 5) elements are not 5) elements are not 5) elements are
synchronized synchronized synchronized synchronized
6) fixed size 6) use arr var. 6) dynamically grow 6) dynamically grow

Interface and packages


Interface and packages: Interface is used by java programmer to make contract in
program. When he or she find some similarity which cause ambiguity for its execution it
solve it.
Following fig.

Class A Interface B
Java Programming by Ms.K.S.Jadhav

Class C

Fig: Multiple Inheritance

Suppose A or B are two different disjoints classes consist one common method like show
then this will cause ambiguity for compiles. When we call this method by object of C
class. It is undeclared for object of C for which method program wants to execute , it is
for class A & class B to solve all this situation in java introduced interface. Interface are
similar to abstract class with two difference that are :
1 Variable for interface are by default final & all the methods of interface
must be abstract .Then such interface is implement on its sub class while
implementing its method we must take care that method of interface are
declared public.
2 If we implement interface on any sub class but in that class we cannot
define method then this class become as abstract class.
3 Java programmer cannot create object of interface instead of that he or
she is able to create reference of variable which is later initialize by any
class constructor.
4 Likewise class, we can extend one interface on another to
implement inheritance.
Interface are introduced by java designers to implement multiple inheritance.
General format of interface is as follows:
Syntax: interface interfacename[extends interface, interface…….]
{
final datatype data_member[value]
returntype method_name();
……..
…….
…….
}
Following program demonstrates use of interface to implement multiple inheritance in
java:

interface Int
{
void show();
}
class D implements Int
{
Java Programming by Ms.K.S.Jadhav

int a=10, b=20, c;


void add()
{
c=a+b;
}
public void show()
{
System.out.println(c);
}
}
class DemoInt
{
public static void main (String args[])
{
D z=new D();
z.add();
z.show(0;
}
}

Use of inheritance in interface: As state earlier, interface is similar to class


program can extends already defined interface on other interface by using keyword
extend. All the inheritance type is supported by interface.

Following program demonstrate the implementation of single inheritance on interface:

interface Add
{
void add();
}
interface Display extends Add
{
void out();
}
class Javademo implements Display
{
public static void main(Stringargs[])
{
int a=10, b=20, c;
}
public void out()
{
Java Programming by Ms.K.S.Jadhav

System.out.println(c);
}
public static void main(String args[])
{
Javademo D=new Javademo();
D.add();
D.out();
}
}

Implementing multiple inheritance :


We can extend more than one interface to define new child interface at same time as
shown in following e.g:

E.g.: interface A
{
void h();
}
interface B
{
void e();
}
interface C
{
void l();
}
interface D extend A,B,C
{
void o();
}
class De implement D
{
public void h()
{
System.out.println(“H”);
}
public void e()
{
System.out.println(“E”);
}
public void l()
{
Java Programming by Ms.K.S.Jadhav

System.out.pritln(“L”);
}
public void o()
{
System.out.println(“O”);
}
public static void main(String args[])
{
D d=new D();
d.n();
d.e();
d.o();
d.l();
}
}
Use of interface reference to call method of subclass: We can use the
reference of interface to call related classes. For that, we must initialize proper
constructor as shown in following program:
E.g.: interface A
{
void msg();
}
class Ref implements A
{
System.out.println(“Interface”);
}
public static void main(String args[])
{
A z; //Reference of interface
z=new Ref(); //Initialize to class
z.msg(); //Method if Ref class call by z reference
}
}

Package: In java, programmer is able to import previously created applications in their


new application as per the requirement. To implement this, java provides Package.
Package are very similar to DOS directory we collect the required files and
folders. To implement package, programmer must follow following steps:

1. Create package
2. Importing package.
Java Programming by Ms.K.S.Jadhav

Creating package:

1. Create root directory at command prompt.


E.g.: c:\bin>mkdir College

2. Create package.
E.g.: \bin>cd College
\bin\College>edit Demo.java

3. In editor (DOS) at very 1st line, use package keyword.


E.g.: package College;
Define class inside the package
E.g.: package College;
public class Demo
{
public Demo()
{
System.out.println(“Hello”);
}
public static void main(String args[])
{
Demo z=new Demo();
}
}

4. Compile package:
E.g.: ..\bin\College>javac Demo.java

Importing package: To import package, programmer must follow following


sequence:

1. Use import keyword at very 1st line of program. This import statement
must contain import keyword followed by user defined package as shown:
E.g.: import College.*;
or
import College.Demo;

2. Define a class where we want to use created package.


E.g.: import College.*;
class Java1
{
public static void main(String args[])
Java Programming by Ms.K.S.Jadhav

{
Demo d=new Demo();
}
}

3. C:\\jdk1.6\bin>javac Java1.java
4. C:\\jdk1.6\bin>javac Java1
Hello

Q.WAP to import package as shown:

College

Academic

Student Cell

Result Sport Extra Activity

Ans: C:\jdk1.6\bin>mkdir College


C:\jdk1.6\bin>cd College C:\jdk1.6\bin\
College>mkdir Academic C:\jdk1.6\bin\College>cd
Academic C:\jdk1.6\bin\College\Academic>mkdir
Student Cell
C:\jdk1.6\bin\College\Academic\Student Cell>edit Result.java C:\jdk1.6\bin\College\
Academic\Student Cell>edit Sports.java C:\jdk1.6\bin\College\Academic\Student
Cell>edit Extra_Activity.java

Exception and Threads:

Exception: Exception is a class provided by java programmer to handle the worst case
situation which occurs during the execution of the software. In other words, we can say
that exception is an object which displays some meaningful messages due to which
software get hang. To implement exception handling in java, compiler provide one
package java.lang.*.
It is a default package which include Exceptionclass
Java Programming by Ms.K.S.Jadhav
java.lang.Exception.*;
Java Programming by Ms.K.S.Jadhav

Following figure demonstrate the hierarchy family structure of exceptions.

java.lang

Throwable

Exception
Error

Interupt Exception RunTime Exception IO Exception

Arithmetic Exception NullPointer Exception

Fig: Family Structure of Exception

Here, as per shown in figure, Throwable is a super class of all types of error and
Exception.
Errors are treated as linking, thread or virtual machine error. Exceptions are the
situations which are caused by user. Generally, in it we include Arithmetic Exception.
When we are trying to divide value by 0, it is Arithmetic Exception.

NullPointer Exception: It means we want to delete some value from null array or
we want to add some value in array which is already full.

ArrayIndexOutOfBound Exception: This will cause when we want to access any


element out of array size.
We can define two types of Exceptions:
1. Define by system itself.
Java Programming by Ms.K.S.Jadhav

2. User-defined exception.

Define by system itself Exceptions: In this situation, we caught those exception


messages which are already defined by compiler. To implement this, we use 3 blocks
as: try, catch and finally.

try: try block is always used by java programmer to place those statement that have sub
chance of exception. They can also say that this block is group of statement that cause
some error.
E.g.: try
{
c=5/0;
}
Note: There is single try and finally block and multiple catch block.

catch: It is the method defined next to try block to catch those Exceptions thrown by try
block.
Syntax: catch(Exception object)
{
System.out.println(object);
}
E.g.: catch(Exception e)
{
System.out.println(e);
}
We can define multiple catch blocks after single key block to handle different
Exceptions.

finally block: This block is used to group those statement that must be execute at the
end of program (abnormal termination of block).
Syntax: finally
{

}
This block always defined after catch block.
Following figure demonstrates a structured figure of Exception handling.
Java Programming by Ms.K.S.Jadhav

try

catch(Excpti on e)

finally

Figure 1: That handle multiple catches is as follows:


try

catch() catch() catch()

finally
Java Programming by Ms.K.S.Jadhav

Following programming demonstrates the use of Exceptional handling


Ans: class Demo
{
public static void main(String args[])
{
try
{
int arr[]=new int[2];
Java Programming by Ms.K.S.Jadhav

arr[0]=10;
arr[1]=100;
arr[2]=1000;
arr[3]=10000;
arr[4]=100000;
}
catch(ArrayIndexOutOfBound ai)
{
System.out.println(“Message:”+ai);
}
for(int i=0;i<=2;i++)
System.out.println(arr[i]);
}
}

Example of multiple catch blocks


E.g.: class Demo
{
public static void main(String args[])
{
try
{
BufferedReader br=new
BufferedReader(new
InputStreamReader(System.in));
String s=br.readLine();
int i=Integer.parseInt(s);
String s1=br.readLine();
int j=Integer.parseInt(s1);
int a=i/j;
}
catch(ArithmeticException ae)
{
System.out.println(ae);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(a);
}
}
Java Programming by Ms.K.S.Jadhav

User defined Exception or use of throw keyword: In java, there are so many
situations for which compiler cannot provide any type of Exception class.
E.g.: If we are comparing two String and if they cannot match the java cannot handle
such situation.

E.g.: If user trying to enter negativeage while feeding data. It will cause some Exception.
For all these situation, user create its own Exception mechanism by using throw keyword.
Throw keyword is followed by user defined Exception class. Its general form is as
follows:

Syntax: throw new UserDefinedException(String msg);

E.g.: throw new NoMatchException(“String not match”);


This throw keyword always used in try block.

Following program demonstrates the user defined Exception which will cause when
given String is not match with another one.
Ans: import java.io.*;
{
class t extends Exception
{
String msg;
public t(String m)
{
msg=m;
}
public String toString()
{
return msg;
}
}
class Demo
{
public static void main(String args[])
{
String j=”Java”;
try
{
BufferedReader br=new
BufferedReader(new
InputStreamReader(System.in));
String s=br.readLine();
boolean b=j.equals(s);
Java Programming by Ms.K.S.Jadhav

if(!b)
throw new t(“No match found Exception”);
catch(t T)
{
System.out.println(“ “+T);
}
}
}
Q:WAP to generate exception when user enter negativeage, it will display Exception
message as age in not format
Ans: import java.io.*;
class NE.g.ativeAge extends Exception
{
String s;
NE.g.ativeAgeException(String m)
{
s=m;
}
public String toString()
{
return s;
}
class Demo1
{
public static void main(String args[])
{
int age;
try
{
BufferedReader br=new
BufferedReader(new
InputStreamReader(System.in));
String ss=br.readLine();
age=Integer.parseInt(ss);
if(age<0)
throw new NE.g.ativeAge(“Age is not in format”);
else
System.out.println(“No Exception”);
}
catch(NE.g.ativeAge e)
{
System.out.println(e);
}
Java Programming by Ms.K.S.Jadhav

} //End of main
} //End of class

Use of throws keyword: Sometimes in java program, some methods are caused
Exception. To handle such method, java programmer use throw keyword.
Syntax: returntype methodName(parameter list)throws ExceptionType
{

}
E.g.: void demo() throws Exception
{

}
In Exception handling, when we are going to define our own Exception class, we
can use super method to override base class constructor to handle the message which will
be passed as Exception, we use getMessage method instead of toString method.
Following program demonstrates the use of super and getMessage method to
handle the Exception.
E.g.: class t extends Exception
{
String msg;
public t(String s)
{
msg=s;
super(msg);
}
}
class Demo
{
public static void main(String args[])
{
int x=100,y=1000;
int a;
try
{
d=x/y;
if(d= =0.01)
{
t T=new t(“Arithmetic Exception”);
throw T;
Java Programming by Ms.K.S.Jadhav

}
}
catch(t e)
{
System.out.println(e.getMessage()):
}
}
}
In above example, we used getMessage() method which help to display
exceptional message passed by base class constructor. This base class constructor is
initialize by super method. This method is passed its argument to the super class of
Exception of any type we already used.
Every Exception class define by java compiler has two types of constructor.
1. Default constructor
2. Parameterized constructor

Example: 1.Exception();
2.Exception(String msg);
1. ArithmeticException();
2. ArithmeticException(String msg);
This all constructor used by java compiler while creating object of exception class.

Thread in java: The objective of introducing thread in java is to implement


multitasking and multiprogramming environment. To implement it, we use:
java.lang.Thread
Thread is similar to a program that has single flow of control. Sometime, it is also
refer as execution context or light weight process, every thread has a bE.g.inning or a
body and an end. It executes command sequentially.

Note: Thread itself is not a program because it cannot run by its own but run within a
program.

MultiThreading: It is program where a thread or process is divide into two or more


subprogram or subprocess. All these subprogram or subprocess are execute
simultaneously.

Life cycle of thread: Following figure shows the life cycle or different stages of
thread object.
Java Programming by Ms.K.S.Jadhav

New born

Stop
run runnable

yield()

Block/wait

Fig: Thread life cycle

Diffrent stages of thread


Stage 1: New born stage: When thread object is created, it is set to be in
newborn stage and it is not yet schedule to run. To create thread object, we
use Thread class or Runnable interface. Object at this stage is create as
follows:
Syntax: Thread t=new Thread();
Now, we can say t is an object which is lie in newborn stage and not
schedule for running.

Stage 2: Excecution Stage: This stage is again subdivided into two diffrent
stages that are refer as running stage and runnable stage. To switch out from
newborn stage to execution stage, we use start method. This method is used
as follows:
E.g.: thread.start();
Where thread is an object already created. Now, the object at
execution stage is submit. Or, we can say that the start method of Thread
class, we place thread object in execution stage.

2a)Runnable Stage: It means that the thread is ready for exectution and is
ready to get excecuted.
Thread object are put in runnable stage from running stage by calling
Java Programming by Ms.K.S.Jadhav

yeild method or put from newborn stage. To put from block stage, it use any
one method like resume(), notify() or notifyAt().

2b)Running Stage: Running stage means processor has taken thread for
execution or it bE.g.in executable. Every time in running stage, there is only
one thread object or process is available.

Stage 3: Blocked Stage: A thread is set to be blocked when it is


preventing from entering the runnable stage. To enter in block stage, thread
use following methods:
suspend() or wait() or sleep()

Stage 4: Dead Stage: A running thread ends its life when it has complete
its execution normally or abnormally. For dead stage, we use stop() method
as:
thread.stop();
In other words, we can say that stop method is caled by thread object
to kill a process.
Note: We cannot restart any killed thread.
There are two different ways available to create or introduce a process
in other program.

1. By using Runnable interface: To create Thread object on


Runnable interface, programer must follow following sequence.

Declare a class that implement Runnable.


Declare a Thread object as a datafield of the class.
Create Thread object.
❖ Define Run method inside class defination.
❖ For multiple thread, create objects.
All the start methods of the objects to call execution of thread.
Following example demonstrate Thread by Runnable interface.

E.g.: class T implements Runnable //Step 1


{
Thread t; //Step 2
public static void main(String args[])
{
t=new Thread(); //Step 3
t.start();
}
public void run() //Step 4
{

}
Java Programming by Ms.K.S.Jadhav

2.By extending Thread class: It is one another method which follow


following sequence.

1. Declare a class that has Thread as superclass.


2. Override run method of subclass or create multiple object to
implement multi-threading.
3. Create object of subclass or create multiple object to implement
multi threading.
4. Call start method to start execution.
Following example shows use of Thread class.

E.g.: class T extends Thread //Step 1


{
public static void main(String args[])
{
T t=new T(); //Step 3
T t1=new T();
t.start();
t1.start();
}
public void run() //Step 2
{

}
Following program demonstrates use of Thread object to generate
even-odd series

E.g.: class E extends Thread


{
public void run()
{
for(int i=0;i<=10;i++) if(i
%2==0) System.out.println(i);
}
}
class O extends Thread
{
public void run()
{
for(int i=0;i<=10;i++) if(i
%2==0) System.out.println(i);
Java Programming by Ms.K.S.Jadhav

}
}
class test
{
public static void main(String args[])
{
E e=new E();
O o=new O();
e.start();
o.start();
}
}

Q:WAP to find factorial of a given number and fibonacci series at given


number by using Thread.
Ans: class fact extends Thread
{
int f,n=1;
public fact(int x)
{
f=x;
}
public void run()
{
for(int i=0;i<=f;i++)
n=n*i;
System.out.println("Factorial is:"+n);
}
}
class fibo extends Thread
{
int b,f,f1=0,f2=1;
public fibo(int x)
{
b=x;
}
public void run()
{
for(int k=0;k<=b;k++)
{
f=f1+f2;
f1=f2;
f2=f;
System.out.println(f);
}
}
Java Programming by Ms.K.S.Jadhav

}
class test
{
public static void main(String args[])
{
fact s=new fact(20);
fibo f=new fibo(21);
s.start();
f.start();
}
}

Synchronizing multi-thread object: As we know, to implement multi-


tasking, we use multi thread, but in situation when we share common
resources, there may cause deadlock. To solve this, java compiler provide
synchronization. There are two diffrent ways to implement synchronization.

1. By synchronizing method: When multiple thread object share single


method of any class to avoid deadlock or to implement synchronization. To
create such method, we use following steps:

 Define method that share by multiple thread object.


 Use synchronize keyword before the method.
 Create multiple thread objects.
Syntax of this method is as follows:
Synchronized returntype methodName(parameter list);
{

}
E.g.: synchronized void show()
{
System.out.println("HI");
}
Now, the show method is available to utilize by more than single
object.

2. By using synchronized block: If we want to share any object in


multi- threading, we use synchronized block. To implement it, we follow:

1. Create object that we want to share.


2. Pass it to synchronized block.
3. Use same object inside block to access various resource with
respective object.
Syntax: synchronized(Obj_name)
Java Programming by Ms.K.S.Jadhav

{
obj_name.method();
}
E.g.: synchronized(x)
{
x.show();
}
In above example, we synchronize object x which will later show the
method with related class.
Following program demonstrates use of synchronized keyword to
handle one method:
E.g.: class Ex
{
Synchronized void disp(String z)
{
System.out.println("Welcome");
try
{
Thread.sleep(300);
}
catch(Exception er)
{
}
System.out.println("Welcome" +z);
}
}
class D implements Runnable
{
Ex e;
String p=" ";
Thread t;
D(Ex x,String s)
{
e=x;
p=s;
t=new Thread(this);
t.start();
}
public void run()
{
e.disp(p);
}
class thread
{
public static void main(String args[])
{
Java Programming by Ms.K.S.Jadhav

Ex x=new Ex();
D d1=new D(x,"RAM");
D d2=new D(x,"SHYAM");
}
}
In above program, we create two threads d1 and d2. Suppose process
scheduler allow 10ms for each execution, then according to our program,
there is chance of collision where after collision, d2 reach to execution
because inside display method, we force to sleep for next 30ms. So, it retain
all control for next 30ms. If, we cannot synchronize this method, then after 10
ms next object d2 also try execution in synchronization, we use synchronized
keyword before disp. In response, compiler force to wait disp method for
object d2 till d1 completes its exceution. Here, we use Runnable interface to
implement thread object which is another method of Thread class.

Methods of thread class:

start(): This method is used to indicate start of Thread object whenever


actual execution of Thread will start.
Syntax: final public void
start(); E.g.: Thread t=new Thread();
t.start();
Now, t is a Thread object start to execute.

run(): This method is defined by Thread class and act as an entry point for
Thread. This method collects 2 statements that define excecution.
Syntax: public void run()
{
statements;
.
.
.
}
E.g.: public void run()
{

sleep(): This method is used to force the current Thread object to sleep for
specified time.
Syntax: final void sleep(long l);
E.g.: Thread.sleep(330);
Here, long value indicate time for which Thread force to sleep. This
method always Throw InteruptedException.
Java Programming by Ms.K.S.Jadhav

The another version of sleep method consists two arguments.


Syntax: sleep(long l,int i);
Here, 2nd argument specify priority of Thread.

suspend(): This method is defined to suspend the thread for long period.
Such suspended Thread are executed only when resume method is called.

Syntax: final public void suspend();


E.g.: t.suspend();

resume(): This method is used to call suspended Thread which is suspended


by suspend method.
Syntax: final public void resume();

isAlive(): This method return a boolean value which is used to indicate


whether Thread is alive or not.
Syntax: final public boolean isAlive();
E.g.: boolean b=t.isAlive();

join: this method is used to force for waiting those Thread object that is called
for termination till its join object not complete its task.
Syntax: final public boolean join();
This method always throw InteruptedException.

notify(): This method is used to wakeup all the object that wait for their
execution,
Syntax: final public void notify();

stop(): This method is used to kill current


object. Syntax: final void stop();

getName() and setName(): This method are used to manipulate Thread


object.
Syntax: final public String getName
E.g.: String s=t.getName();
Syntax: final public void setName
E.g.: t.setName("Mythread");

* The constructors used by thread class are:

It use default constructor to create Thread object

The other constructors are listed as:


Java Programming by Ms.K.S.Jadhav

1. Thread(String +Name)
2. Thread()
3. Thread(Runnable obj)
4. Thread(Runnable obj,String +Name)

Thread object contains three priorities:


Thread class contains priority which are

1. MAX_PRIORITY i.e. 10
2. MIN_PRIORITY i.e. 1
3. NORM_PRIORITY i.e. 5

These three constants are also defined by Runnable interface.

File Handling in java: To store huge information and share it among user,
we use concept of file handling which implement by class File of java. This
class has sevral constructors that are used to create File object.

File(String filename): This constructor is used to create instance of class file


with specified name.

File(String dir,String filename): This constructor form specified directory


path and filename.
E.g.: File f=new File("C:/Java/jdk1.6/Demo.java");
In above example, we create demo object f which is specified by
relative directory path given before file name.
The other methods support by file class are as follows.

getName(): This method is used to return name of file through which file
object is initialized.
Syntax: String getName();
E.g.: System.out.println(f.getName());

getParent(): This method is used to return the name of parent


file. Syntax: String getParent();
E.g.: System.out.println(f.getParent());

length(): This method return a long value which indicate length of


file. Syntax: long length();
E.g.: long l=f.length();

exists(): This method is used to check existance of specified file. If it is, it


return true else false.
Java Programming by Ms.K.S.Jadhav

Syntax: boolean exists();


E.g.: boolean b=f.exists();

isFile() or isDirectory(): isFile method is used to check whether given object


is invoke any file or not whereas isDirectory method is used to check invoking
object consist any directory or not. It returns a boolean value.
E.g.: File f=new File("C:/Java");
boolean b1=f.isFile();
boolean b2=f.isDirectory();
System.out.println("File:"+b1+"Dir:"+b2);

canRead()/canWrite(): This method is used to check permission provide


to edit file for user. Both method always return boolean value.

list (): This method is used to return files and subdirectories stored in
specified directory.
Syntax: String s[] list();
E.g.: String s[];
for(int i=0;i<f.length();i++)
s[i]=f.list();
Following program demonstrates the use of file class to handle
specified file.

E.g.: import java.io.*;


class Demo
{
public static void main(String args[])
{
File f=new File("C:/program files/java/jdk1.6/bin/Demo.java");
System.out.println("Filename:"+f.getName());
if(f.exists())
{
Sytem.out.println("Absolute path:"+f.getAbsolutePath());
System.out.println("Path:"+f.getPath());
System.out.println("Can we write it:"+f.canWrite());
System.out.println("Can read:"+f.canRead());
}
if(f.isDirectory())
{
String s[];
s[]=f.list();
for(int i=0;i<s.length;i++)
System.out.println(s[i]);
}
}
Java Programming by Ms.K.S.Jadhav

catch(Exception er)
{
}
}
}
This File class is always provide by java.io.*; package. So programmer
must import java.io.* package at the begin of program. Object of this class
always throw IOException. Thats why always use exception handling
mechanism while manipulating File. This IO package consist various file as
shown below:
java.io.* ;
1. InputStream
a. FilterInputStream
a.1 BufferedInputStream
a.2 DataInputStream
a.3 LineNumberInputStream
a.4 PushBackInputStream

b. ByteArrayInputStream
c. FileInputStream
d. PipedInputStream
e. StringBufferInputStream
.
2. OutputStream
a. FilterOutputStream
a.1 BufferedOutputStream
a.2 DataOutputStream
a.3 LineNumberOutputStream
a.4 PushBackOutputStream
b.ByteArrayOutputStream
c. FileOutputStream
d.PipedOutputStream
e.StringBufferOutputStream
3. File
4.RandomAccessFile
5.FileDescriptor
6.StreamTokenizer

In above package, InputStream and OutputStream are the abstract class.


Here close() is abstract.

Use of filter in java: Java provide a facility to store huge information so to


share when required. Same time, it provide the facility to store which we
want currently. To implement this, it provide another interface FilenameFilter.
This interface encapsulate only one method i.e. accept which consist
Java Programming by Ms.K.S.Jadhav

2arguments and return boolean value.


Syntax of accept method is as:
Syntax: boolean accept(File f, String filename);
This method always define in a class on which we implement
FilenameFilter interface. This method call each time whenever it find related
file find in list. This method consist 2 argument from which 1 st one is file
reference which indicate the path whereas 2 nd is the name of file which we
want to find.
We always use list file method to select the file selected by filter.
Following program demonstrates the use of filename filter interface to find
those file that are store by Demo26.java
E.g.: import java.io.*;
{
String s=” “;
public ExOn(Strin msg)
{
s=msg;
}
boolean accept(File f, String name)
{
return name.startsWith(s);
}
}
class Demo28
{
public static void main(String args[])
{
try
{
File f=new File(“Demo26”);
if(f.exists())
{
ExOn e=new ExOn(“Demo26”);
File[] ff;
ff=f.list();
for(int i=0;i<ff.length;i++)
{
System.out.println(ff[i]);
}
}
catch(Exception er)
{
}
}
}
Java Programming by Ms.K.S.Jadhav

RandomAccessFile: Thre strength of java is that it provide alternative to


achieve same task as per requirement. Uptil now, we create file that are
sequential type. This(sequential) file are variable size. Such file limits their
use. To create file of fix size with more methods, we use RandomAccessFile.
This is a class which create object where each file is fixed in size. It also
provide facility to setpermission on access of filelike read only(“r”),write(“w”)
or both(“rw”). In this class, it provide 2 constructor that help to object of
RandomAccessFile.

1. RandomAccessFile(String filename, String permissions);


2. RandomAccessFile(File f, String permissions);

In 1st constructor, we create object of this class with filename and


necessary permission whereas 2nd constructor is used where already created
file class and when we want to set permission or restriction.
Following program demonstrates the use of RandomAccessFile where
we create RandomAccessFile with necessary permissions.
E.g.: import java.io.*;
class Random 1
{
void in()
{
RandomAccessFile r1=new
RandomAccessFile(“Stud.dat”,”rw”);
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String name=” “;
int rol;
String c=” “;
do
{
System.out.println(“Enter name and roll”);
name=br.readLine();
r1.writeUTF(name);
rol=Integer.parseInt(br.readLine());
System.out.println(“Choice”);
c=br.readLine();
}
while(c.compareTo(“Y’)==0);
}
catch(Exception er){}
}
void out()
{
try
{
Java Programming by Ms.K.S.Jadhav

RandomAccessFile r2=new RandomAccessFile(“stud.dat”,”r”);


String n=” “;
int r;
while(r2.getFilePrinter()<r2.length())
{
n=r2.readUTF();
r=r2.readInt();
System.out.println(“name=”+n+”rol=”+r);
}
}
catch(Exception er)
{
}
}
public static void main(String args[])
{
Random1 r= new Random1();
r.in();
r.out();
}
}

Stream:
Stream are refer as order sequence of data flow from source to
destination. In Java stream divide in Byte and character streams .
Pipe:
These are synchronized communication channel between thread. One
thread send data to another by writing to PipeOutputStream.The target
read information from pipe via a PipeInputStream .
Digram:
File mechanism

Pipes Streams

PipeInputStream PipeOutputStream Byte oriented Character oriented

InputStream OutputStream Reader Writer

Byte oriented streaming: For those computer use unicode character


system.
Methods of InputStream:
1) read() read data into the stream
2) skip() skips over byts in stream
3) available() return number of bytes immediately avail. In stream
Java Programming by Ms.K.S.Jadhav

4) mark() mark position in stream


5) reset() unset mark in stream
6) close() close the stream
Methods of OutputStream:
1) write() write data to the stream
2) flush() forces any buffered output to be written
3) close() close the stream

FileInputStream: This class is used by java programmer to read the data


which is in binary format given at specified location. This file have 2 type of
constructors:

1. FileInputStream(String filepath);
2. FileInputStream(File obj);
Here, 1st constructor is probably more commonly used, where we
define source of data from where we wish to read. This class generally throw
FileNotFound Exception.
Whereas, 2nd constructor is used to read data from already created file
by using File class.
Following program demonstrates use of FileInputStream class to read
its content.
E.g.: import java.io.*;
class TestFile
{
public static void main(String args[])throws Exception
{
FileInputStream f=new FileInputStream(“Demo.java”);
String s=” “;
byte b[];
while((s=f.readLine())!=NULL)
System.out.println(s);
f.close();
}
}

FileOutputStream class: This class is used to write bytes in a file. This class
provide 4 type of constructor. These are similar to FileInputStream
constructor listed as below:

1. FileOutputStream(String filepath);
2. FileOutputStream(File obj);
3. FileOutputStream(String path, boolean append);
4. FileOutputStream(File object, boolean………);

Here, 3rd and 4th constructor specify the opening mode of file i.e. if
Java Programming by Ms.K.S.Jadhav

appends set true, it append file for writing purpose in append mode i.e.it
cannot disturb old data using new one.
E.g.: FileOutputStream f= new FileOutputStream(“Demo.java”,true);
As per above E.g., we are creating one java source file by Demo.java.
FileOutputStream open this file in append mode i.e. if specified file contain
same source code, then it will not over.
Following program demonstrate use of FileOutputStream class.
E.g.: import java.io.*;
class TestFile
{
public static void main(String args[])throws Exception
{
String s=”ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
FileOutputStream f=new FileOutputStream(“Demo.java”);
byte b[]=s.getBytes();
f.write(b);
f.close();
}
}
Character oriented streaming: for those computer use other than
unicode character system.
Reader and Writer both are super classes for all character oriented
streaming classes. Both are abstract classes.
Subclasses of Reader-
1) InputStreamReader
1.1 FileReader
2) BufferedReader
3) ByteArrayReader
4) CharArrayReader
Methods of Reader:

Following program demonstrates use of FileReader class to read its content.


E.g.: import java.io.*;
class TestFile
{
public static void main(String args[])throws Exception
{
FileReader f=new
FileReader(“Demo.java”); String s=” “;
byte b[];
while((s=f.readLine())!=NULL)
System.out.println(s);
f.close();
}
}
Java Programming by Ms.K.S.Jadhav

Subclasses of Writer-
1) Output Writer
1.1 FileWriter
2) Buffered Writer
3) ByteArray Writer
4) CharArray Writer
Methods of Writer:

Following program demonstrate use of FileWriter class.


E.g.: import java.io.*;
class TestFile
{
public static void main(String args[])throws Exception
{
String s=”ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
FileWriter f=new FileWriter
(“Demo.java”); byte b[]=s.getBytes();
f.write(b);
f.close();
}
}
serialization:

Applet:
Applet is a dynamic and interactive java program run under java
enabled web browser. Where web browser is prog. Use to view web
page. Inharitance hierarchy of Applet class is as

Object

Events Font Component Graphics MenuComponent

FontMetric Cantainer Menubar MenuItem

Panel Window

Applet Dialog

FileDialog Frame

To develop applet we must import java.awt.*;and java.applet.*;


packages.
Difference between Applet and Application
Java Programming by Ms.K.S.Jadhav

Applet Application
1) To execute it use 1) To execute it use
public void paint(Graphics g) method public static void main(String s[]) method
2) It execute under web browser 2) It execute under compiler
3) It consist *.html file or applet <tage> 3) It consist only java code file
with java code
4) It execute by appletviewer tool in JRE 4) It execute by java tool in JRE
5) It may be execute in JRE 5) It must be execute in JRE
6) It execute at server side 6) It execute at server or client side
7) It can't use run any application on or of 7) It may be use to run any application on
client or of client
8) It use to develop GUI based application 8) It use to develop core application in java
in java or system s/w's
9) Applets are secured and reliable 9)Applications are not secured and reliable
to communicate to communicate
10) We must import java.awt.*; 10) Applications are not used java.awt.*;
and java.applet.*; package for and java.applet.*; package
applet
11) Applet support event 11) Application not support to event
based programming based programming

Applet Life Cycle:


Their are five stages in applet life cycle,each of which having matching
method that override to gain that stage of applet life cycle. Following
fig. Shows it.
Creation

Initialization

Start/Restart

Stop

Destruction
Fig : Applet Life cycle.

1. Initialization Stage: In this stage applet object is created and


loaded. This stage occurs only once in applet life cycle. The
Java Programming by Ms.K.S.Jadhav
init()
Java Programming by Ms.K.S.Jadhav

override for this stage.


2. Start Stage: When ever applet start by system this stage occur
by overriding of start(). Unlike init() ,start() occur several times
in applet life cycle.
3. Paint Stage: This method occurs when applet able to drawn on
screen. This stage override by paint(), it provide applet with
display.
4. Stop Stage: This stage is counterpart of start stage. For this
stage stop() overrides . We can restart any stop applet by
overriding repaint(), to display changes.
5. Destroy stage: This stage is counterpart of initialization stage.
For this stage destroy() overrides. Like initialization stage ,
destroy also occur only once in applet life cycle.

Applet Tag Structure:

<html>
<head>
<h1> Title</h1>
</head>
<body>
<applet>
<applet code/codebase = “*.class” [ALT=”filename”]
width=hspace height=vspace>
<para name=vname value=data>
< .. >
</applet>
</body>
</html>

Each html applet file divide 2 parts in it head and body

Tag <html></html>:
Indicate start and end of html file
Tag<head></head>:
Text specified here is used as title or heading for web page.
Tag <body></body>:
It indicate start of body where execution statements are collect.
Tag <applet></applet>:
Indicate start and end of applet tags
Tag <applet code/codebase = “*.class” [ALT=”filename”]
width=hspace height=vspace>:
Java Programming by Ms.K.S.Jadhav

This tag till browser which file is to be loaded to display(code=local or


codebase=remote file).if specified file not found than use alternative
file. Applet width and height determined by width and height.
Tag <para name=vname value=data>:
This tag use to pass parameter and value from html file which received
by java application by using getParameter().

Steps to Run Applet:


There are 2 way to run applet
1. Through web browser:
In this way we use html file with applet tags which later opened by any
java enabled web browser.
Eg: <html>
<applet code/codebase =”*.class” height=200 widht=200>
</applet>
</html>
Before use this file we must successfully compile java code so its class file
is created later use by this html file to load it in web browser.
2. Through appletviewer:
To run applet from command window we use appletviewer tool. Before
this with java source code we must attach applet tags. At command
prompt we use command like this
c:\\jdk1.6.0_06\bin>appletviewer Demo

Sample Program :
//Program to display welcome message on Applet.
import java.awt.*;
import java.applet.*;
public class Demo extends
Applet{ String msg;
public void init(){
msg=”welcome to java applet”;
}
public void paint(Graphics g){
g.drawString(msg,50,50);
}
}
/*<applet>
<applet code = “Demo.class” width=100 height =100>
</applet>*/

1. compile:
Java Programming by Ms.K.S.Jadhav

c:\\jdk1.6.0_06\bin>javac Demo.java

2. run when successfully compiled : c:\\


jdk1.6.0_06\bin>appletviewer Demo see
out put.

Layout Manager:
Are special objects that determin how elements of an applet are
organized in applets. Their are various layout manager avail. For
programmer for applet. FlowLayout is one of them avail. By default.
Other are BorderLayout , GridLayout , GridBageLayout , CardLayout each
of them represented by a class of the same name.
Object create as: GridLayout g= GrideLayout(3,2);

To setting Layout:
setLayout() is method use to set programmer choice Layout for applet.
Eg: setLayout(g);// set grid layout

To add AWT component to Layout:


After setting Layout add() is invoked to add components to Layout. Object
of component added as one of the parameter from several other
parameters as per selected Layout.

Handling of events using EventListener:


For java events are managed by using one or more EventListener
interfaces. It enable a component of GUI to generate user events. Only
those events are generate that are register with objects. Java has two
types of event handling model Event delegation and event model. Event
delegation model is commonly used. It consist 3 part -
1) Event–That change the flow of execution on action eg Key,Mouse event
2) Event source – Source object that provide place for event eg
Button etc
3) Event Listener – That communicate event occurrence eg
KeyListener etc.Event related classes and interfaces are import from
java.awt.event.*; package

//Program show use of Applet class ,Layout Manager,AWT components and


event.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Demo extends Applet implements ActionListner
Java Programming by Ms.K.S.Jadhav

{ //Event Listener
TextField t1,t2;
Label l1,l2;
Button b1,b2;

public void init(){


t1= new TextField(5);
t2= new TextField(5);
l1= new Label(“Enter Nu. “);
l2= new Label(“ “);
b1= new Button(“square”); // event source1
b2= new Button(“cube”); // event
source2
b1.addActionListner(this);// event registration
b2.addActionListner(this);
GridLayout g= GrideLayout(3,2);
setLayout(g);
add(l1);add(t1);
add(l2);add(t2);
add(b1);add(b2);
}
public void actionPerformed(ActionEvent ae) // event(actionPerformed) {
// event object (ae)
if(ae.getSource()==b1){
int n= Integer.parseInt(t1.getText());
n=n*n;
l2.setText(“Square of Nu. Is”);
t2.setText(Integer.toString(n));
}
else{int n= Integer.parseInt(t1.getText());
n=n*n*n;
l2.setText(“Cube of Nu. Is”);
t2.setText(Integer.toString(n));
}
}
}
/*<applet>
<applet code = “Demo.class” width=100 height =100>
</applet>
*/
Compile and Run

Graphics Components:
Java Programming by Ms.K.S.Jadhav

1) Button 7) Scrollbars
2) Label 8) Panels
3) TextField 9) Canvas
4) TextArea 10) Menubar
5) List 11) CheckBox
6) Choice

Graphics Methods:
1) drawString() to display message in applet on screen
2) drawLine() to draw Line in applet on screen
3) drawOvel() to draw ovel in applet on screen
4) drawRect() to draw Rect in applet on screen
5) fillRect() to draw and fill rectangel

You might also like