Java Notes
Java Notes
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.
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
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’
1. int
Java Programming by Ms.K.S.Jadhav
2. char
3. float
4. Boolean
Byte 1
Short 2
Long 8
Int 4
Float 4
Double 8
Char 2
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 ).
P.name=”PQR”;
System.out.println(“Second roll”+P.roll + “Second name”+P.name);
}
}
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
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:-
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);
}
}
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
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;
}
depth of a : 10
depth of b : 23
depth of c : 84
Use of final keyword: This keyword is used to avoid the modification of variable or
method.
Syntax:
1. To making variable as a constant
int i=10;
it avoid variable from further modification/ to make it constant
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.
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.
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.
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();
}
Single
Multilevel
Multiple(To implement multiple inheritance, we must define any one class as
an interface)
Java Programming by Ms.K.S.Jadhav
Hierarchical
}
class B extends A
Class B
{
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
{
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
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
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.
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();
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();
}
}
{
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
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.
}
}
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
}
}
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. 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:
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
}
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
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);
3. toString(): This method always return String value for its invoking
value. Syntax: String toString();
E.g.: String s=b1.toString();
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);
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
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);
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:
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
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);
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
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(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
Methods:
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
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);
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
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.
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
Creating StringBuffer
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.
Several methods of classes String and StringBuffer are same but as per
the functionality, StringBuffer has been added with some special methods.
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:
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( )
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:
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:
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’);
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:
Example:
Java Programming by Ms.K.S.Jadhav
int x = 52;
float f = 13.4f;
insert( )
This method is used to insert one string, character or object into another string.
Forms of this method are:
Here the ‘index’ specifies the index position at which point the string will be
inserted into the invoking StringBuffer object.
Example:
reverse( )
Syntax:
StringBuffer reverse()
Java Programming by Ms.K.S.Jadhav
StringBuffer s = new
be “wolleY”
Syntax:
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
“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:
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.
1) int capacityIncrement;
2) int elementCount;
3) Object[] elementData;
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.
Object firstElement( )
It returns the first element in the vector.
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.
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.
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.
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.
Class A Interface B
Java Programming by Ms.K.S.Jadhav
Class C
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
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();
}
}
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
}
}
1. Create package
2. Importing package.
Java Programming by Ms.K.S.Jadhav
Creating package:
2. Create package.
E.g.: \bin>cd College
\bin\College>edit Demo.java
4. Compile package:
E.g.: ..\bin\College>javac Demo.java
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;
{
Demo d=new Demo();
}
}
3. C:\\jdk1.6\bin>javac Java1.java
4. C:\\jdk1.6\bin>javac Java1
Hello
College
Academic
Student Cell
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
java.lang
Throwable
Exception
Error
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.
2. User-defined exception.
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
finally
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]);
}
}
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:
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.
Note: Thread itself is not a program because it cannot run by its own but run within a
program.
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
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 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.
}
Java Programming by Ms.K.S.Jadhav
}
Following program demonstrates use of Thread object to generate
even-odd series
}
}
class test
{
public static void main(String args[])
{
E e=new E();
O o=new O();
e.start();
o.start();
}
}
}
class test
{
public static void main(String args[])
{
fact s=new fact(20);
fibo f=new fibo(21);
s.start();
f.start();
}
}
}
E.g.: synchronized void show()
{
System.out.println("HI");
}
Now, the show method is available to utilize by more than single
object.
{
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.
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
suspend(): This method is defined to suspend the thread for long period.
Such suspended Thread are executed only when resume method is called.
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();
1. Thread(String +Name)
2. Thread()
3. Thread(Runnable obj)
4. Thread(Runnable obj,String +Name)
1. MAX_PRIORITY i.e. 10
2. MIN_PRIORITY i.e. 1
3. NORM_PRIORITY i.e. 5
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.
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());
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.
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
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
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:
Subclasses of Writer-
1) Output Writer
1.1 FileWriter
2) Buffered Writer
3) ByteArray Writer
4) CharArray Writer
Methods of Writer:
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
Panel Window
Applet Dialog
FileDialog Frame
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
Initialization
Start/Restart
Stop
Destruction
Fig : Applet Life cycle.
<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>
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
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
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
{ //Event Listener
TextField t1,t2;
Label l1,l2;
Button b1,b2;
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