Upload
aditya-kumar
View
212
Download
0
Embed Size (px)
Citation preview
8/20/2019 javanotes(1)
1/208
1
Chapter 1
Introduction to java
Java is language for the development of Enterprise applications, and it was developed at Sun
Microsystems as a platform-independent language primarily aimed at controlling appliances such as
video game consoles VCRs, bread toasters .
“Sun” , later modified the language to take advantage of World Wide Web. Java is an object-oriented
language, and very similar to C++.
Java Features
1. PlatformIndependent
The concept of Write-once-run-anywhere is one of the important key feature of java languagethat makes java as the most powerful language.
2. Simple
Programs are easy to write and debug because java does not use the pointers explicitly. It is
much harder to write the java programs that can crash the system.
3. ObjectOriented
java is a fully Object Oriented language because, object is at the outer most level of data
structure in java. No stand alone methods, constants, and variables are there in java. Everything
in java is object even the primitive data types can also be converted into objects.
4. Robust
Java has the strong memory allocation and automatic garbage collection mechanism. It provides
the powerful exception handling and type checking mechanism as compare to otherprogramming languages. Compiler checks the program whether there any error and interpreter
checks any run time error and makes the system secure from crash. All of the above features
makes the java language robust.
5.
Distributed
Internet programmers can call functions on HTTP , FTP protocols and can get access to the files
from any remote machine rather than writing codes on their local system.
6.
Portable
The feature Write-once-run-anywhere makes the java language portable provided that the
system must have interpreter for the JVM.
7. Secure
Java does not use memory pointers explicitly. All the programs in java are run under an area
known as the sand box. Security manager determines the accessibility options of a class like
reading and writing a file to the local disk. Java uses the public key encryption system to allow
the java applications to transmit over the internet in the secure encrypted form. The bytecode
Verifier checks the classes after loading.
http://www.roseindia.net/java/http://www.roseindia.net/java/java-introduction/java-features.shtmlhttp://www.roseindia.net/java/java-introduction/java-features.shtmlhttp://www.roseindia.net/java/java-introduction/java-features.shtmlhttp://www.roseindia.net/java/java-introduction/java-features.shtmlhttp://www.roseindia.net/java/java-introduction/java-features.shtmlhttp://www.roseindia.net/java/java-introduction/java-features.shtmlhttp://www.roseindia.net/java/java-introduction/java-features.shtmlhttp://www.roseindia.net/java/java-introduction/java-features.shtmlhttp://www.roseindia.net/java/java-introduction/java-features.shtmlhttp://www.roseindia.net/java/java-introduction/java-features.shtmlhttp://www.roseindia.net/java/
8/20/2019 javanotes(1)
2/208
2
8. Performance
Java uses native code usage, and lightweight process called threads. In the beginning
interpretation of bytecode resulted in slow performance but the advanced versions of JVM
uses just in time compilation technique that improves the performance.
9. Multithreaded
Multithreading programming is a very interesting concept in Java.
10.
Interpreted
One of the advantage of Java as an interpreted language is its error debugging quality. Due to
this any error occurring in the program gets traced.
11. Architecture Neutral
Java was designed to support applications on network. The Java compiler generates byte code
instructions, to be easily interpreted on any machine and to be easily translated into native
machine code on the fly.
What is Java Virtual Machine?
Languages like C and Pascal converts the source code into machine code for one specific type of
machine and the machine language vary from system to system . But Java compiler produce code for avirtual machine . JVM converts the byte code into machine code for the computer one wants to run.
The JVM is a part of JRE that is required by every operating system.
Each operating system and CPU architecture requires a JRE. JRE consists of a set of base classes i.e. Java
API as well as a JVM. JVM is java interpreter as it converts the byte code into machine code for the
computer one wants to run.
JRE consists of a number of classes based on JavaAPI and JVM, and without JRE, it is impossible to run
Java.
How to write First Java program
public class FirstProgram
{
public static void main(String arr[] )
{
System.out.println(" Hello Java World");
}}
http://www.roseindia.net/java/java-introduction/java-features.shtmlhttp://www.roseindia.net/java/java-virtual-machine.shtmlhttp://www.roseindia.net/java/java-virtual-machine.shtmlhttp://www.roseindia.net/java/java-virtual-machine.shtmlhttp://www.roseindia.net/java/java-virtual-machine.shtmlhttp://www.roseindia.net/java/java-virtual-machine.shtmlhttp://www.roseindia.net/java/java-virtual-machine.shtmlhttp://www.roseindia.net/java/java-virtual-machine.shtmlhttp://www.roseindia.net/java/java-virtual-machine.shtmlhttp://www.roseindia.net/java/java-virtual-machine.shtmlhttp://www.roseindia.net/java/java-introduction/java-features.shtml
8/20/2019 javanotes(1)
3/208
3
Save the file with same name as the public class just adding the extension “.java” e.g.
FirstProgram.java.
Now compile as:
c:\ javac FirstProgram.java
This creates a class file in bytecode form as FirstProgam.class
How to execute this code:
c:\ java MyFirstProgram
OUTPUT :: Hello Java World
Different Editions of Java Technology
a)
Java SE - Java SE or Java Standard Edition provides tools and API's that you can use to createdesktop applications, applets, server applications. These programs developed using Java SE can be
run on almost every popular operating system.
b) JEE - Java Enterprise Edition helps in web application service, component model and enterprise
class service oriented architecture(SOA).
c) JME - Java Micro Edition or JME is an accumulation of Java APIs that are used for the development
of software for devices like mobile phones, PDAs, TV set-top boxes, game programming.
Demonstartion Programs
Example 1 : Demo of a Simple java program
public class FirstProg
{
public static void main(String args[])
{
System.out.println( “welcome to the java SE 6”);
}
}
Example 2 : Demo of if statement through a java program
public class DemoIf
{
public static void main(String args[])
{
int a = 10, b = 15, m;
http://www.roseindia.net/java/new-to-java.shtmlhttp://www.roseindia.net/java/new-to-java.shtml
8/20/2019 javanotes(1)
4/208
4
if (a > b) m = a; else m = b;
System.out.println( “max number = “m);
}
}
Example 3 : Demo of while.. loop through a java program
public class DemoWhile
{
public static void main(String args[])
{
int n = 257, s =0, d;
while (n !=0)
{
d = n % 10; s = s +d ; n = n / 10;
}
System.out.println( “sum of digits = “s);
}
}
Example 4 : Demo of for.. loop
public class DemoFor
{
public static void main(String args[])
{
int n = 30, i;
for (i = 1; i
8/20/2019 javanotes(1)
5/208
5
Structure of Arrays
Array is the most widely used data structure in java. It can contain multiple values of the same
type. Moreover, arrays are always of fixed length i.e. the length of an array cannot be increased
or decreased. The Array class implicitly extends java.lang.Object so an array is an instance of
Object.Suppose an array contains "n" integers. The first element of this array will be indexed with the
"0" value and the last integer will be referenced by "n-1" indexed value.
Presume an array that contains 12 elements as shown in the figure. Each element is holding a
distinct value. Here the first element is refrenced by a[0] i.e. the first index value.
The figure below shows the structure of an Array more precisely.
Array Declaration
To represent the variable as an Array, we use [] notation. These two brackets are used to hold
the array of a variable.
int[] array_name; //declares an array of
integers
String[] names;
int[][] matrix; //this is an array of arrays
It is essential to assign memory to an array when we declare it. Memory is assigned to set the
size of the declared array. for example:
int[] array_name = new int[5];
Here is an example that creates an array that has 5 elements.
public class Array
{
public static void main(String[] args){
int[] a = new int[5];
}
}
8/20/2019 javanotes(1)
6/208
6
Array Initialization
After declaring an array variable, memory is allocated to it. The "new" operator is used for the
allocation of memory to the array object. The correct way to use the "new" operator is
String names[];
names = new String[10];
Here, the new operator is followed by the type of variable and the number of elements to beallocated. In this example [] operator has been used to place the number of elements to be
allocated.
Lets see a simple example of an array,
public class Sum
{
public static void main(String[] args)
{
int[] x = new int [101];
for (int i = 0; i
8/20/2019 javanotes(1)
7/208
7
Example 6 : Demo of 1 D array - Sorting of n integers
public class DemoSort
{
public static void main( String args[] )
{int a[ ] ={ 10,08,30,15,27,17,12}, i, j, n,temp;
n = a.length;
for ( i = 0 ; i < n-1 ; i ++)
for (j= i+1; j < n; j++)
if ( a[ i ] >a[ j ])
{
temp = a[ i ]; a[ i ] = a[ j ]; a[ j ]= temp;
}
for ( i=0; i < n; i++)
System.out.println( “ “ a* i +);
}
}
Example 7 : Demo of user defined iterative functions
public class DemoFunction
{
public static void main(String args[])
{
int n = 5, i, fm;
fm = fact (m);System.out.println(“result = “ fm);
}
static int fact( int n)
{
int fn = 1, i;
for (i = 2; i
8/20/2019 javanotes(1)
8/208
8
Example 8 : Demo of Recursive functions
public class DemoRecfun
{
public static void main(String args[]){
int n = 5, i, fm;
fm = fact (m);
System.out.println(“result = “ fm);
}
static int fact( int n)
{
if ( n < 0) return 1;
else
return n * fact ( n – 1);
}
}
8/20/2019 javanotes(1)
9/208
9
Chapter 2
Object Oriented Features of Java
OOP stands for Object Oriented Programming. There are four main pillars of an Object Oriented
Programming Language :
Inheritance: Inheritance provide the facility to derive one class by another using simple syntax. You
can say that it is a process of creating new class and use the behavior of the existing class by
extending them for reuse the existing code and adding the additional features as you need.
Encapsulation: Encapsulation is the ability to bundle the property and method of the object and also
operate them. It is the mechanism of combining the information and providing the abstraction as
well.
Polymorphism: Polymorphism is the way that provide the different functionality by the functions
having the same name based on the signatures of the methods. There are two type of
polymorphism first is run-time polymorphism and second is compile-time polymorphism.
Dynamic binding: It is the way that provide the maximum functionality to a program for a specific
type at runtime. There are two type of binding first is dynamic binding and second is static binding.
Class: A class provide a feature to defines the properties and behavior (variables and methods) as an
ADT , that can be used by all its objects. It is a blue print for the creation of objects.
Object: Class itself does nothing but the real functionality is achieved through their objects. Object is an
instance of the class. It takes the properties (members) and uses the behavior (methods) defined in the
class.
The Encapsulation, Inheritance and Polymorphism are main pillars of OOPs. These have been
described below :
Encapsulation:
Encapsulation is the process of binding together the methods and data variables as a single entity. It
keeps both the data and functionality code safe from the outside world. It hides the data within the
class and makes it available only through the methods. Java provides different accessibility scopes
(public, protected, private ,default) to hide the data from outside.
Here we provide a example in which we create a class "Check" which has a variable "amount" to store
the current amount. Now to manipulate this variable we create a methods and to set the value of
amount we create setAmount() method and to get the value of amount we create getAmount() method
8/20/2019 javanotes(1)
10/208
10
Here is the code for "Mainclass" class :
class Check
{private int amount=0;
public int getAmount()
{
return amount;
}
public void setAmount(int amt)
{
amount=amt;
}
}
public class Mainclass{
public static void main(String[] args)
{
int amt=0;
Check obj = new Check();
obj.setAmount(200);
amt = obj.getAmount();
System.out.println("Your current amount is :"+amt);
}
}
Here the data variable "amount" and methods setAmount() and getAmount() are enclosed together
with in a single entity called the "Check" class. These two methods are used to manipulate this variable
i.e. set and get the current value of amount.
Example 9 : Demo of object oriented programming
class DemoCalc
{
int a , b;
public DemoCalc()
{
a = 5; b = 10;
}
public int sum ()
8/20/2019 javanotes(1)
11/208
11
{
int x;
x = a + b;
return x;
}
}
public class TestDemoCalc
{
public static void main(String args[])
{
DemoCalc m = new DemoCalc();
int z;
z = m.sum();
System.out.println(“result = “ z);
}
}
Constructor
Constructor is the method whoose name is same as that of the class. But there are many difference
between the method (function) and the Constructor. It has no return type.
It is used for initialization purpose. A class can have any number of constructors. It is then called
constructor overloading.
Example 10 : Demo of Constructor Overloading
class DemoOver
{
int a , b;
/* default constructor */
public DemoOver()
{
a = 5; b = 10;
}
/* constructor with parameter */public DemoOver( int k1, ink k2)
{
a = k1; b = k2;
}
public int sum ()
8/20/2019 javanotes(1)
12/208
12
{
int x;
x = a + b;
return x;
}
}
public class TestDemoOver
{
public static void main(String args[])
{
DemoOver m1 = new DemoOver();
DemoOver m2 = new DemoOver(20,25);
int z1, z2;
z1 = m1.sum(); z2 = m2.sum();
System.out.println(“result1 = “ z1 “result2 “z2);
}
}
this key word : It is used to resolve the ambiguity between a formal parameter and a
datamember.
Example 11 : Demo of keyword this
class Demothis
{int a , b;
/* constructor with parameter */
public Demothis( int a, ink b)
{
this.a = a; this.b = b;
}
public int sum ()
{
int x;x = a + b;
return x;
}
}
public class TestDemothis
{
8/20/2019 javanotes(1)
13/208
13
public static void main(String args[])
{
Demothis m1 = new Demothis(20,25);
int z1;
z1 = m1.sum();
System.out.println(“result = “ z1 );}
}
Instance variables: They are the datamembers in a class and get a copy of memory for each
object instance. With one object instance if they are modified , the other instances are not
effected.
Example 12 : Demo of instance variable
class DemoInvar
{
int a,b;
public DemoInvar( )
{
a=5; b=7;
}
public void update ()
{
a++;b++;
}
public void disp()
{
System.out.println ( “a= “a “b=”b);
}
}
public class TestDemoInvar
{
public static void main(String args[])
{
DemoInvar m1 = new DemoInvar();
DemoInvar m2 = new DemoInvar ();
8/20/2019 javanotes(1)
14/208
14
m1.update();
m1.disp();
m2.disp();
}
}
Static variables: They are the data members in a class defined with a keyword static. Suchmembers are also called class members , . and get a single copy of memory per JVM, for all
object instances. With one object instance if they are modified , the other instances are also
effected as they are shared .
Example 13 : Demo of class variable
class DemoClvar
{
static int a ;
int b;
public DemoClvar( )
{
a = 5; b = 7;
}
public void update( )
{
a ++; b++;
}
public void disp( )
{
System.out.println ( “a= “a “b=”b);
}
}
public class TestDemoClvar
{
public static void main(String args[])
{ DemoClvar m1 = new DemoClvar();
DemoClvar m2 = new DemoClvar ();
m1.update( );
m1.disp( );
m2.disp( );
}
8/20/2019 javanotes(1)
15/208
15
}
Class methods : Such methods belong the class but not to the objects. They are called with
class name.
Example 14 : Demo of class method
class DemoClmd
{
public static wishcode01 ()
{
System.out.println( “ Happy New Year”);
}
public static wishcode02 ()
{
System.out.println(“Happy returns");
}
}
public class TestDemoClmd
{
public static void main(String args[])
{
DemoClmd.wishcode01( );
DemoClmd.wishcode02( );
}}
8/20/2019 javanotes(1)
16/208
16
Example 15 : Demo of class method
class DemoMathop
{
static float multiply(float x, float y)
{return x*y;
}
static float divide(float x, float y)
{
return x/y;
}
}
public class TestDemoMathop
{
public static void main(String args[])
{
float a = DemoMathop.multiply(2.0,5,0);
float x = DemoMathop.divide(a,2.0);
System.out.println("x=" + x);
}
}
Example 16 : Demo of method invocation by other methods of the same class( Nested methods)
class DemoNest
{
int a,b;
public DemoNest( )
{
a=15; b=7;
}
public int large()
{
int m;
m= ( a>b)? a : b;
return m;
}
8/20/2019 javanotes(1)
17/208
17
public void disp()
{
int x = large(); /* method call */
System.out.println ( “max= “ x);
}
}
public class TestDemoNest
{
public static void main(String args[])
{
DemoNest m1 = new DemoNest();
m1.disp();
}
}
System.out.println() ::
The "java.lang" package is built into every program. A package is a libaries of classes.
The java.lang package has a System Class, which includes a static nested class called "out" and
this out class, has a method by name println().
Why method main has " public , static" access specifiers ::
It is called from outside.
The main() is a class method
It is invoked by the interpretor with its class name.
8/20/2019 javanotes(1)
18/208
18
Chapter 3
String Handling
Strings are handled as objects in java. Java support two classes to handle strings
1 String 2 StringBuffer
String objects hold text which can't be changed. A String class object is immutable because
the time taken by JVM to reallocate memory and add data is more than creating a new
object. A StringBuffer on the otherhand, is mutable. It can change and grow in size The
default constructor allocates 16 char size to a StringBuffer
String Methods
Let s1, s2 are the source and destination strings. Then some methods are
s2 = s1.toLowerCase()
s2 = s1.replace('x', 'y')
s2 = s1.trim()
s1.equals(s2) , s1.isEmpty()
s1.equalsIgnoreCase(s2)
S1.length
s1.charAt(n)
s1.subString(n) , s1.subString(m,n)
s1.indexOf("x")
s1.toString()
s1.compareTo(s2)
s2 = s1.concat(s3)
s2 = s1.replace('x','y') (It create a new string object s2)
8/20/2019 javanotes(1)
19/208
19
StringBuffer methods
s1.charAt(n)
s1.append(s2), s1.replace(m,n,s2)
s1.setCharAt(n,'x')
s1.insert(n,s2)
s1.setLength(n) , s1.length(), s1.reverse()
The following programs demonstrate String handling in java.
Example 17 : Demo of methods in String class
public class TestStread
{
public static void main( String args[])
{
String s1 = "hello";
String s2 = new String(); s2 = "from"
String s3 = new string("Java");
String s4 = s1 + s2 + s3;
String s5 = s4.concat(" world ");
String s6 = "";
System.out.println(s5);System.out.println(s5.toUpperCase());
system.out.println("is empty? " + s6.isEmpty());
}
}
Example 18 : Demo of methods in String class
public class TestSsort
{
public static void main( String args[]){
String s[] = { "arun", "rao" , "sridhar", "jones"};
int i,j,n;
String temp = null;
n = s.length;
8/20/2019 javanotes(1)
20/208
20
for ( i=0; i< n-1; i++)
for (j=i+1; j 0 )
{
temp = s[i]; s[i] = s[j];s[j] = temp;
}
for ( i =0; i< n; i++)
System.out.println(s[i]);
}
}
Example 19 : Demo of methods in String buffer class
public class TestBuff
{
public static void main( String args[])
{
StringBuffer s1 = new StringBuffer("hello");
StringBuffer s2 = new StringBuffer();
s2.insert(0," from");
s2.append(" java"); s1.append(s2);
System.out.println(s1);
s1.replace(6,10,"to");
System.out.println(s1);
s1.delete(6,8);
System.out.println(s1);
System.out.println("alloted len" + s1.capacity());
s1.setLength(100);
system.out.println("new capacity"+ s1.length());
}
}
Example 20 : Demo of methods in StringBuffers
public class TestSbuff
{
public static void main( String args[])
{
8/20/2019 javanotes(1)
21/208
21
StringBuffer sb= new StringBuffer("Java is tough");
System.out.println(sb);
int n = sb.length(); int p;
for ( i=0; i< n; i++)
{p = i + 1;
System.out.print("char at pos" +p+"=" + sb.charAt(i));
}
String a = new String(sb.toString());
p = a.indexOf("tough");
sb.insert(p,"Not ");
System.out.println(sb);
sb.append(" to learn");
System.out.println(sb);
}
}
StringBuilder class ::
StringBuffer , can be used by multiple threads. It is recommended when synchronization is
required. Its methods are synchronized. A StringBuilder has no synchronized methods. So it
works faster and , When we are doing number of string operations in a single thread we
gain tremendous performance than StringBuffer.
Example 21 :: Demo of StringBuilder
public class TestApp
{
public static void main(String args[])
{
String s = concate("java"," ","is"," ","simple");
System.out.println(s);
}
static String concate(String... k){
StringBuilder sd = new StringBuilder( );
int n = k.length; int i;
for ( i= 0; i< n ; i++)
sd.append(k[i]);
8/20/2019 javanotes(1)
22/208
22
return sd.toString( );
}
}
StringTokenizer.
Example 22:
import java.util.StringTokenizer;
class STDemo {
static String in ="title=Java: The Complete Reference;" +
"author=Naughton and Schildt;" +
"publisher=Osborne/McGraw-Hill;" +
"copyright=1999";
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer(in, "=;");while(st.hasMoreTokens()) {
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "\\t" + val);
}
}
}
Wrappers
Java provide wrapper classes in order to use primitive data types as objects, Every
primitive type has a class defined
primitive wrapper
8/20/2019 javanotes(1)
23/208
23
int Integer
float Float
char Character
There are methods defined to return the values of an object
Example 23 : Demo of wrapper class
public class TestWrp1
{
public static void main( String args[])
{
Integer i = new Integer(25);
Character c = new Character('H');
int J = i.intValue();
char k = c.charValue();
System.out.println(j + " " +i);
System.out.println(k+ " " + c);
}
}
Let a,b are primitive types, m,n are objects , and S is string object
Conversion of primitive types to primitive objects
Integer m = new Integer(a);
Float n = new Float(b);
Conversion of primitive objects to primitive types
int a = m.intValue();
float b = n.floatValue();
Conversion of primitive types to string objects
String s = Integer.toString(a);
String s = Float.toString(b);
Conversion of string objects to primitive types
int a = Integer.parseInt(s);float b = Float.parseFloat(s);
Example 24 : Demo of wrapper class
public class Adder
{
public static void main( String args[])
8/20/2019 javanotes(1)
24/208
24
{
int a, b, m;
a= Integer.parseInt(args[0]);
b= Integer.parseInt(args[1]);
m = a+b;
System.out.println("result " + m);}
}
Autoboxing, unboxing of primitive types
Example 25 : Demo of autoboxing, unboxing
public class TestBoxUnbox
{
public static void main( String args[])
{
Integer ib1,ib2,ib3;
ib1 = 25; // autoboxing - encapsulating a value
int i1 = ib1; // unboxing - extracting the value
System.out.println(ib1 + " " +i1);
ib2 = 35;
ib2 = ib2 + 1; // unbox and rebox
System.out.println("value" + ib2) ;
ib3 = Abox.getval(55); // Autobox
System.out.println(" value returned" + ib3);
}
}
class Abox
{
static int getval( Integer ib)
{
return ib; // unbox the return vaule}
}
for - each loop ::
for (type varaible : collection)
8/20/2019 javanotes(1)
25/208
25
statement;
Example 26 : Demo of for each
public class DemoApp
{public static void main( String args[])
{
for ( String s: args)
System.out.println(s);
}
}
Example 27 : Demo of for-each
public class DemoApp
{
enum Country { india, china, japan, canada};
public static void main( String args[])
{
for ( Country c: Country.values())
System.out.println("it Is" + c);
}
}
variable number of arguemnts ::
8/20/2019 javanotes(1)
26/208
26
Example 28 : Demo of variable numer of parameters
public class DemoApp
{
static void mthvar(int... i){
int n = i.length;
System.out.println("number of para"+ n);
System.out.println("contents are");
for ( int k : i)
System.out.println("it Is" + k);
}
public static void main( String args[])
{
mthvar();
mthvar(25,35);
mthvar(10,20,30,40);
}
}
Example 29 : Demo of for-each
public class DemoApp
{public static void main( String args[])
{
int a[] = { 10,20,30,40,50};
int max = 0;
for ( int k: a)
if ( k > max) max = k;
System.out.println("maximum" + max);
}}
8/20/2019 javanotes(1)
27/208
27
Chapter 4
Inheritance & Polymorphism in java
Inheritance allows a class (subclass) to acquire the properties and behavior of another class (superclass).In java, a class can inherit only one class (superclass) at a time but a class can have any number of
subclasses. It helps to reuse, customize and enhance the existing code. So it helps to write a code
accurately and reduce the development time. Java uses extends keyword to extend a class.
Here is the code of the example :
class A
{
public void fun1(int x)
{
System.out.println("in A is :" + x); }
}
class B extends A
{
public void fun2(int x,int y)
{
fun1(6); // prints "int in A"
System.out.println("in B is :" + x " and "+y);
}
}
public class Testinherit
{
public static void main(String[] args)
{
B obj= new B();
obj.fun2(2);
}
}
In the above example, class B extends class A and so acquires properties and behavior of class A. So we
can call method of A in class B.
Thus inheritance is aechanism used to create new class by extending the definition of
another class. This process of extending one class to create new class is called subclassing.
8/20/2019 javanotes(1)
28/208
28
Types::
Single inheritance Multiple Inheritance
Multilevel Inheritance Hirarchial Inheritance
Hybrid Inheritance
/* Demo of inheritance */
class DemoCalc
{
int a,b;
public DemoCalc()
{
a = 5; b = 10;
}
public int sum ()
{
int x;
x = a + b;
return x;
}
}
public class TestDemoCalc
{
public static void main(String args[])
{
DemoCalc m = new DemoCalc();int z;
z = m.sum();
System.out.println(“result = “ z);
}
}
Example 30 : Demo of inheritance
class ChDemoCalc extends DemoCalc
{public int diff()
{
int x;
x = a-b;
return x;
}
8/20/2019 javanotes(1)
29/208
29
}
public class TestChDemoCalc
{
public static void main(String args[])
{
ChDemoCalc m = new ChDemoCalc();int z1,z2;
z1 = m.sum();
z2 = m.diff();
System.out.println( “sum=“ z1 "diff=" z2 );
}
}
Constructor under inheritance
When a child class object is instantiated the constructor of the base class is called first ,
then followed by the derived class constructor.
Example 31 : Demo of constructor under inheritance
class A
{
A( )
{
System.out.println("In constructor of A");
}
}
class B extends A{
B( )
{
System.out.println("In constructor of B");
}
}
public class TestApp
{
public static void main(String args[])
{B b1 = new B();
}
}
output :: In construtor of A
In construtor of B
8/20/2019 javanotes(1)
30/208
30
Example 32 : constructor with param under inheritance - 1
class A
{
A( ){
System.out.println("In constructor of A");
}
}
class B extends A
{
B(String s )
{
System.out.println("In string constructor of B");
System.out.println(s);
}
}
public class TestConInhe
{
public static void main(String args[])
{
B b1 = new B("Java is simple");
}
}
output :: In construtor of A
In string construtor of B
java is simple
8/20/2019 javanotes(1)
31/208
31
Example 33 : constructor with param under inheritance - 2
class A
{
A( ){
System.out.println("In constructor of A");
}
A(String s )
{
System.out.println("In string constructor of A");
System.out.println("In A" + s);
}
}
class B extends A
{
B(String s )
{
super(s);
System.out.println("In string constructor of B");
System.out.println("In B" + s);
}
}
public class TestApp
{
public static void main(String args[])
{
B b1 = new B("Java is simple");
}
}
output :: In string construtor of A
In A java is simpleIn string construtor of B
In B java is simple
super( ) :: It can be used to call super class methods/constructor
8/20/2019 javanotes(1)
32/208
32
Multilevel inheritance::
Example 34 : Constructor under Multilevel inheritance
class A
{A( )
{
System.out.println("In constructor of A");
}
}
class B extends A
{
B( )
{
System.out.println("In constructor of B");
}
}
class C extends B
{
C( )
{
System.out.println("In constructor of C");
}
}
public class TestApp{
public static void main(String args[])
{
C c1 = new C();
}
}
output :: In construtor of A
In construtor of B
In contructor of C
Polymorphism
Polymorphism allows one interface to be used for a set of actions i.e. one name may refer to different
functionality. Polymorphism allows a object to accept different requests of a client (it then properly
8/20/2019 javanotes(1)
33/208
33
interprets the request like choosing appropriate method) and responds according to the current state
of the runtime system, all without bothering the user.
There are two types of polymorphism :
1. Compile-time polymorphism
2. Runtime Polymorphism
In compiletime Polymorphism, method to be invoked is determined at the compile time. Compile time
polymorphism is supported through the method overloading concept in java.
Method overloading means having multiple methods with same name but with different signature
(number, type and order of parameters).
Here is the code of the example :
class A{
public void fun1(int x){
System.out.println("The value of class A is : " + x);
}
public void fun1(int x,int y){
System.out.println("The value of class B is : " + x + " and " + y);
}
}
public class polyone{
public static void main(String[] args){
A obj=new A();
// Here compiler decides that fun1(int) is to be called and "int" will be printed.
obj.fun1(2);// Here compiler decides that fun1(int,int)is to be called and "int and int" will be printed.
obj.fun1(2,3);
}
}
In rumtime polymorphism, the method to be invoked is determined at the run time. The example of run
time polymorphism is method overriding. When a subclass contains a method with the same name and
signature as in the super class then it is called as method overriding.
class A{
public void fun1(int x){ System.out.println("int in Class A is : "+ x);
}
}
class B extends A{
public void fun1(int x){
System.out.println("int in Class B is : "+ x);
8/20/2019 javanotes(1)
34/208
34
}
}
public class polytwo{
public static void main(String[] args){
A obj;
obj= new A(); // line 1
obj.fun1(2); // line 2 (prints "int in Class A is : 2")
obj=new B(); // line 3
obj.fun1(5); // line 4 (prints ""int in Class B is : 5")
}
}
Method Overriding ::
It is used when a subclass has to replace a method of its superclass. Whenever such a
method is invoked, java looks for a method of that signature, in the class definition of the
current object. If such a method is not found then it looks for a matching signature in the
superclass.
Example 35 :: Demo of method overriding
class Animal
{
public void breath( )
{System.out.println(" Breathing...");
}
}
class Fish extends Animal
{
public void breath( )
{
System.out.println("Bubbling...");
}
}
public class TestRide
{
public static void main(String args[])
{
Fish f = new Fish();
8/20/2019 javanotes(1)
35/208
35
f.breath();
}
}
output :: bubbling...
super keyword
The super is java keyword. As the name suggest super is used to access the members of the super class.
It is used for two purposes in java.
The first use of keyword super is to access the hidden data variables of the super class hidden by the
sub class.
e.g. Suppose class A is the super class that has two instance variables as int a and float b. class B is the
subclass that also contains its own data members named a and b. then we can access the super class(class A) variables a and b inside the subclass class B just by calling the following command.
super.member;
Here member can either be an instance variable or a method. This form of super most useful to handle
situations where the local members of a subclass hides the members of a super class having the same
name. The following example clarify all the confusions.
class A{
int a;
float b; void Show(){
System.out.println("b in super class: " + b);
}
}
class B extends A
{
int a;
float b;
B( int p, float q)
{
a = p;
super.b = q;
}
void Show()
{
super.Show();
8/20/2019 javanotes(1)
36/208
36
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}
public static void main(String[] args)
{
B subobj = new B(1, 5); subobj.Show();
}
}
Use of super to call super class constructor: The second use of the keyword super in java is to call super
class constructor in the subclass. This functionality can be achieved just by using the following
command.
super(param-list);
Here parameter list is the list of the parameter requires by the constructor in the super class. super must
be the first statement executed inside a super class constructor. If we want to call the default
constructor then we pass the empty parameter list.
Example 36 : method overriding - how to access original method
class Animal
{
public void breath( )
{
System.out.println(" Breathing...");}
}
class Fish extends Animal
{
public void breath( )
{
System.out.println("Bubbling...");
}
public void newbreath( )
{
super.breath();
}
}
public class TestRide
8/20/2019 javanotes(1)
37/208
37
{
public static void main(String args[])
{
Fish f = new Fish();
f.newbreath();
f.breath();}
}
output :: breathing...
bubbling...
Dynamic method dispatch ( Run time polymorphism)
Any subclass object reference can be given to a super class variable. It is to suport runtime
polymorphism. It lets us write code that works with many different types of objects, and
decide on the actual object type at runtime.
Example 37 : Runtime polymorphism
class A
{
public void disp( )
{
System.out.println("printing A");
}
}
class B extends A
{public void disp( )
{
System.out.println("printing B");
}
}
class C extends B
{
public void disp( )
{System.out.println("printing C");
}
}
public class TestApp
{
public static void main(String args[])
8/20/2019 javanotes(1)
38/208
38
{
A a1 = new A(); B b1 = new B();
C c1 = new C();
A oref;
oref = a1; oref.disp();
oref = b1; oref.disp();
oref = c1; oref.disp();
}
}
output :: printing A
printing B
printing C
Abstract class
A class is abstract if one or more methods in it are defined by the abstract key word. A
method is abstract when it has only declaration but no expansion in the base class.No objects
can be instantiated from such a class. When writing classes , we run across cases where we
can provide general code and it is upto the developer to customize it in a subclass. To make
sure he customizes it, we make the method abstract. Such a class is also made abstract.
8/20/2019 javanotes(1)
39/208
39
Example 38 : Demo of abstract class -- 1
abstract class A
{
abstract public void disp( );
}
class B extends A
{
public void disp( )
{
system.out.println("java is simple");
}
}
public class TestApp
{
public static void main(String args[])
{
B b1 = new B( );
b1.disp( );
}
}
Example 39 : Demo of abstract class -- 2
abstract class A{
abstract String getData( );
public void disp( )
{
System.out.println( getData( ) );
}
}
class B extends A
{
String getData( ){
String s = "java is simple";
return(s);
}
}
public class TestApp
8/20/2019 javanotes(1)
40/208
40
{
public static void main(String args[])
{
B b1 = new B( );
b1.disp( );
}}
Note : constructors, private, static methods can NOT be abstract.
Final modifier ::
To stop overriding
To stop Inheritance
creating constants
To stop overriding ::
class Animal
{
final void breath( )
{
System.out.println(" Breathing...");
}
}
class Fish extends Animal
{
public void breath( ) ......???? ( not allowed ){
System.out.println("Bubbling...");
}
}
To stop inheritance ::
final class Animal
{
public void breath( )
{System.out.println(" Breathing...");
}
}
class Fish extends Animal .....????! ( no .. not allowed )
{
public void breath( )
8/20/2019 javanotes(1)
41/208
41
{
System.out.println("Bubbling...");
}
}
To create constants::
final int a = 25;
a++; .....????! not allowed
a = 50; .....????! not allowed
is-a relation :: standard inheritance refers to is-a relation
class A
{
void disp( )
{
System.out.println("from A");
}
}
class B extends A // B is-a A
{
B( )
{
disp( );
}}
public class TestApp
{
public static void main(String args[])
{
B b1 = new B();
}
}
has-a relation :: It is a state when one object holds other object instances.
class A
{
void disp( )
8/20/2019 javanotes(1)
42/208
42
{
System.out.println("from A");
}
}
class B
{A a1; // B has-a A
B( )
{
a1 = new A( );
a1.disp( ) ; //The disp of A is avilable to obj B
}
}
public class TestApp
{
public static void main(String args[])
{
B b1 = new B();
}
}
java Object class ::
Every class in java is derived automatically from java.lang.Object class. All classes in java
are subclasses
Every object thus inherits certain methods. some of them
boolean equals(ob) :: used to check whether an object ob equals to this one
protected void finalize() :: called by garbage collector
when it is about to dispose object
Class getClass() :: It gives the run time class of the object
int hashCode() :: It gives a hashcode value of the object.
Example 40 :: Demo of Object class
class A
8/20/2019 javanotes(1)
43/208
43
{
public void disp( )
{
System.out.println("printing A");
}
}class B extends A
{
public void disp( )
{
System.out.println("printing B");
}
}
class C extends B
{
public void disp( )
{
System.out.println("printing C");
}
}
public class TestApp
{
public static void main(String args[])
{
A a1 = new A(); B b1 = new B();C c1 = new C();
A oref;
oref = a1; oref.disp();
System.out.println( "ref is " + oref.getClass() );
oref = b1; oref.disp();
System.out.println( "ref is " + oref.getClass() );
oref = c1; oref.disp();System.out.println( "ref is " + oref.getClass() );
}
}
output :: printing A
8/20/2019 javanotes(1)
44/208
44
ref is class A
printing B
ref is class B
printing Cref is class C
Garbage collection and memory management
Java has a built in process called garbage collector. It occurs automatically , although we
can not predict when it will happen. Java itself dispose of the memory that no longer has
reference to it. However to make it happen we can set references to null
Example 41 :: Demo of garbage collection
class A
{
void disp( )
{
System.out.println("from A");
}
}
public class TestApp
{
public static void main(String args[]){
int a[ ] = { 10,20,30 };
A b1 = new A(); int l ;
b1.disp();
l = a.length;
System.out.println ( "l=" + l );
b1 = null; a = null; // making them null
}}
Example 42 :: Demo of garbage collection & finalize() method
class Tester
{
8/20/2019 javanotes(1)
45/208
45
public int k;
Tester( int i )
{
k = i;
}
}
class A
{
int m1;
Tester t;
A( )
{
m1 = 5;
t = new Tester(2500);
}
void disp( )
{
System.out.println("from A");
}
protected void finalize()
{t = null; // inner object to null
}
}
public class TestApp
{
public static void main(String args[])
{
A b1 = new A();
b1.disp();b1 = null;
}
}
interfaces :
8/20/2019 javanotes(1)
46/208
46
They provide templates of behaviour, that other classes can implement. They define the
design and classes that implement the interface must provide the implementation of the
design.
In Abstract classes some methods may have definition, and leaving few undefined. Ininterfaces no method can be defined.
The data members in Abstract class can be variables or constants but they are only
constants in an interface. A class can extend only one abstarct class. But a class may
implement multiple interfaces, and thus provide an indirect way to multiple inheritance.
class Printer
{
public void print()
{
// set the params
// print data .....
}
}
interface Copier
{
public void copyDocument( Document d);
}
interface Fax
{
public void transmitDocument(Document d);
}
class MultiFunctionPrinter extends Printer implements Copier, Fax
{
// the content ...
}
Note : A method inside an interface can not be declared private or protected. They can
carry public abstract modifiers only. The members must be public, static final making them
constants.
8/20/2019 javanotes(1)
47/208
47
interface Examp
{
public static final int a = 3;
int b = 5; // effectively public static final
public abstract void calc( );void change( ); // effectively public and abstract
}
Extending an interface :
Like classes interface can inherit from other interfaces. The sub interface acquires all the
method definitions and constants of the super interfaces.
interface Newxerox extends Copier, Fax
{
....
}
Marker Interface
In java language programming, interfaces with no methods are known as marker interfaces. Marker
interfaces are Serializable, Clonable, SingleThreadModel, Event listener. Marker Interfaces are
implemented by the classes or their super classes in order to add some functionality.
e.g. Suppose you want to persist (save) the state of an object then you have to implement theSerializable interface otherwise the compiler will throw an error. To make more clearly understand the
concept of marker interface you should go through one more example.
Suppose the interface Clonable is neither implemented by a class named Myclass nor it's any super
class, then a call to the method clone() on Myclass's object will give an error. This means, to add this
functionality one should implement the Clonable interface. While the Clonable is an empty interface but
it provides an important functionality.
Example 43 : Demo of Interfaces
import java.io.*;
interface StudentInter
{
void getData( ) throws IOException;
void showData();
int calcTot();
http://www.roseindia.net/java/master-java/interface.shtmlhttp://www.roseindia.net/java/master-java/interface.shtml
8/20/2019 javanotes(1)
48/208
48
float calcPercent();
void menu();
}
class Student implements StudentInter
{int rno, m1,m2;
string name;
public void getData( ) throws IOException
{
DataInputStream d = new DataInputstream( System.in );
System.out.print( "Enter Rollno :" );
rno = Integer.parseInt( d.readLine( ) );
System.out.print( "Enter Name :" );
name = d.readLine( );
System.out.println( "Enter Sub 1 Mark :" );
m1 = Integer.parseInt( d.readLine( ) );
System.out.println("Enter Sub 2 Mark :" );
m2 = Integer.parseInt( d.readLine( ) );
}
public void showData( )
{
System.out.println ( "Rollno = " + rno);
System.out.println ( "Name = " + name);System.out.println ( "mark1 = " + m1);
System.out.println ( "mark2 = " + m2);
}
public int calcTot( )
{
return ( m1 + m2);
}
public float calcPercent( ){
int t = m1+ m2;
return ( t / 2 );
}
public void menu( )
8/20/2019 javanotes(1)
49/208
49
{
System.out.println ( "Enter 1 to get total");
System.out.println ( "Enter 2 to get percent");
}
}
public class TestStudent
{
public static void main( String args[ ] )
{
Student s = new Student( );
s.getData();
s.showData();
int tot;
float per;
s.menu( ); // to display menu
DataInputStream d = new DataInputstream( System.in );
System.out.print( "Enter choice : " );
int n = Integer.parseInt( d.readLine( ) );
switch( n )
{
case 1: tot = s.calcTot();
System.out.println("total =" + tot);break;
case 2: per = s.calcPercent();
System.out.println("percent=" + per);
break;
default: System.out.println( "incorrect choice" );
}
}
}
Partially implementing an interface
Classes that partially implement an interface must be abstract as they are only expanding
few methods.
8/20/2019 javanotes(1)
50/208
50
Example 43 :
interface A
{
void dispone();
void disptwo();}
abstract class B implements A
{
void disptwo()
{
system.out.println("expanded from b);
}
}
class C extends B
{
void dispone( )
{
System.out.println("expanded from c");
}
}
public class TestApp
{
public static void main( string args[])
{
C k1 = new C();k1.dispone();
k1.disptwo();
}
}
Inner classes ::
They are non static nested classes. They nest the definition of one class inside another.
They are usefull while handling events such as user closing a window etc.
Example 44 :Demo of inner classes
class A
{
class B
8/20/2019 javanotes(1)
51/208
51
{
public void disp( )
{
system.out.print("inside B ..");
}
}
B b1;
A( )
{
b1 = new B( );
b1.disp( );
}
}
public class TestApp
{
public static void main(String args[])
{
A a1 = new A();
}
}
when we instantiate Object a1 of class A, it instantiates internal object b1 of class B.
ProcessBuilder class ::
An Operating system process can be created using this class, and it manage all the process
attributes. It is not at all synchronized.
Example 45 :: Demo of ProcessBuilder class
import java.io.*;
public class TestApp
{public static void main(String args) throws IOException
{
ProcessBuilder pb1;
pb1 = new ProcessBuilder("notepad.exe","first.java");
pb1.start( );
}
8/20/2019 javanotes(1)
52/208
52
}
8/20/2019 javanotes(1)
53/208
53
Chapter 5
Exception Handling
Exception is a runtime error , that may cause abnormal termination of the program
during its execution. When an error occurs within a java method , the method creates an
exception object and hands it off ( Throwing) to the runtime system. This exception object
contain information about exception, its type, state of the program when it occured.
The runtime system searches for appropriate block of code to handle the exception.
If there is no appropriate handler, with in that block the serach progresses up through
the call stack, until an appropriate handler is found. If no such handler is found, the runtime
system stops and the program terminates.
public class Divide
{
public static void main(String args[])
{
System.out.println("prog starts here..");
int a,b,c;
a = Integer.parseInt(args[0]);
b = integer.parseInt(args[1]);
c = a/b;System.out.println("c="+ c);
System.out.println("program ends here..");
}
}
Running with 4 cases as below would give a picture :
case 1 : java Divide 4 2
case 2 : java Divide 4
case 3 : java Divide a 2
case 4 : java Divide 4 0
To prevent interuption of the programs flow from exceptions such as the ones shown
above, handlers are used to catch such exceptions and handle them appropriately through
cleanup or message notification.
8/20/2019 javanotes(1)
54/208
54
There are three types of Exceptions:
1. Checked Exceptions - These are the exceptions which occur during the compile time of the
program. The compiler checks at the compile time that whether the program contains handlers
for checked exceptions or not. These exceptions do not extend RuntimeException class and
must be handled to avoid a compile-time error by the programmer. These exceptionalconditions should be anticipated and recovered by an application. Furthermore Checked
exceptions are required to be caught.
ClassNotFoundException
NoSuchMethodException
InterruptedException
Unchecked Exceptions - Unchecked exceptions are the exceptions which occur during the
runtime of the program. Unchecked exceptions are internal to the application and extend the java.lang.RuntimeException that is inherited from java.lang.Exception class. These exceptions
cannot be anticipated and recovered like programming bugs, such as logic errors or improper
use of an API. These type of exceptions are also called Runtime exceptions that are usually
caused by data errors, like arithmetic overflow, divide by zero etc.
Here is the list of unchecked exceptions.
ArrayIndexOutOfBoundsException
ArithmeticException
NullPointerException
2.Error - An Error indicates serious problems that a reasonable application should not try to catch.
Most such errors are abnormal conditions. Hence we conclude that Errors and runtime exceptions
are together called as unchecked exceptions.
http://www.roseindia.net/java/exceptions/exception.shtmlhttp://www.roseindia.net/java/exceptions/exception.shtmlhttp://www.roseindia.net/java/exceptions/exception.shtmlhttp://www.roseindia.net/java/exceptions/exception.shtml
8/20/2019 javanotes(1)
55/208
55
The exception classes can be explained as well seeing the hierarchy structure:
The java.lang package defines several classes and exceptions. Some of these classes are not checked
while some other classes are checked.
EXCEPTIONS DESCRIPTION CHECKED UNCHECKED
ArithmeticExceptionArithmetic errors such as
a divide by zero- YES
ArrayIndexOutOfBoundsExceptionArrays index is not within
array.length- YES
ClassNotFoundException Related Class not found YES -
IOExceptionInputOuput field not
foundYES -
IllegalArgumentExceptionIllegal argument when
calling a method- YES
InterruptedExceptionOne thread has been
interrupted by another
thread
YES -
NoSuchMethodException Nonexistent method YES -
NullPointerExceptionInvalid use of null
reference- YES
NumberFormatExceptionInvalid string for
conversion to number- YES
As you have come to know that exceptions are Objects that means an object is thrown when you throwan exception. Moreover only those objects could be thrown whose classes are derived from Throwable.
It is interesting to note here that the objects of your own design could also be thrown provided that they
should be the subclass of some member of the Throwable family. Also the throwable classes which are
defined by you must extend Exception class.
8/20/2019 javanotes(1)
56/208
56
Handling Exceptions in java
It is done using five key words try, catch, throw, throws, finally
try{
// statements that may throw exception
}
catch( Exceptiontype-1 e)
{
// statements to handle
}
catch( Exceptiontype-2 e)
{
// statements to handle
}
finally
{
// clean up code or exit code(optional)
}
The code in the finally block always gets executed regardless of what happens with in the
try block. It is used to close files, data base connections , Sockets etc.
When exception occurs the method may instantiate an exception object and hand it to the
run time system to deal with it.
The exception object carry the following
1. Type of exception - its class
2. Where it occured - stack trace
3. Context information - message and state
The arguement type in the catch clause is from throwable class or one of its subclasses.
Once an exception is thrown , the block from where it is thown expires and control can not
return back to the throw point.
Java uses a termination model of handling exception rather than resumption model.
8/20/2019 javanotes(1)
57/208
57
Throwable class ::
It is the super class in the hierarchy, under java.lang.Object. An exception object is
an instance of throwable class or any of its sub class.
The Throwable class provides a set of methods apart from various constructors
Throwable() :
Throwable(String message) :
getMessage() : retuns the message from the object or null
printStackTrace() : print the stack trace
A stack Trace is a list of methods excecuted in sequence that lead to the exception.
Example 46 ::
public class Divide
{
public static void main(String args[])
{
System.out.println("prog starts here..");
int a,b,c;
try
{
a = Integer.parseInt(args[0]);b = integer.parseInt(args[1]);
c = a/b;
System.out.println("c="+ c);
}
catch ( NumberFormatException e)
{
system.out.println("Invalid argumets");
}
catch ( ArithmeticException e){
system.out.println("Second Arg can not be zero");
}
catch ( ArayIndexOutOfBoundsException e)
{
8/20/2019 javanotes(1)
58/208
58
system.out.println("pass proper args");
}
System.out.println("program ends here..");
}
}
Order of Catch Blocks ::
The order of catch blocks are important when there are multiple catch blocks. The
exception subclasss must come before any of its super class. Otherwise the subclass
exception never gets executed.
Example 47 : incorrect ordering of Exception
public class Divide
{
public static void main(String args[])
{
System.out.println("prog starts here..");
int a,b,c;
try
{
a = Integer.parseInt(args[0]);
b = integer.parseInt(args[1]);
c = a/b;System.out.println("c="+ c);
}
catch ( Exception e)
{
System.out.println("It is " + e");
}
catch ( ArithmeticException e)
{
System.out.println("Second Arg can not be zero");}
System.out.println("program ends here..");
}
}
Hence it is improtant to handle right exception in the right context.
8/20/2019 javanotes(1)
59/208
59
Nested try statements ::
Each time a try in entered , the context of the Exception is pushed on to the stack. If an
inner try does not have a catch for an exception, the stack is unwound and catch belonging to
next try is inspected for a match.
Example 48 : Demo nested try
public class Divide
{
public static void main(String args[])
{
System.out.println("prog starts here..");
int a,b,c;
try
{
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
try
{
c = a/b;
System.out.println("c="+ c);
}
catch ( ArithmeticException e)
{
System.out.println("Sec.Arg cannot be zero");
}
}
catch ( NumberFotmatException e)
{
System.out.println("Invalid argumets");}
catch ( ArayIndexOutOfBoundsException e)
{
System.out.println("pass proper args");
8/20/2019 javanotes(1)
60/208
60
}
System.out.println("program ends here..");
}
}
Redirecting Exceptions using "throws" ::
When an exception can occur in a method, then it is supposed to be handled, or atleast
explicitely warn the potential callers about its possibility. This is done using a throws clause
in the method declaration so that it can be passed to a different method in the call stack.
void Divide( ) throws Exception-A, Exception-B
{
}
Example 49:: demo of throws
public class Testthrows
{
public static void main(String args[])
{
int i; int n=args.length;
try
{
for( i=0;i
8/20/2019 javanotes(1)
61/208
61
Exceptions are thrown by run time. But they can even be thrown by using a throw
statement.
throw < Exception Object >
The Exception object is an object of class Throwable or any of its subclass. In a specific
case where an instance of Exception object is to be thrown, it takes the form as
throw new < Exception Object >
Example 50 :: demo of Throwtest
public class Testthrow
{
public static void main(String args[]) throws Exception
{
int i1 = 15;
int i2 = 20;
if (i1 > i2)
throw new Exception("First numb can not be more");
else
System.out.print("ok");
}
}
Throwing custom (user defined) Exception ::
Usefull to handle business specific error conditions.For Ex, while withdrawal from bank, an
Exception MinBal may be created. Such Exceptions are placed as a subclass of Exception under
Throwable class. They can be created using any method as below
1. Throwable Uexcep = new Throwable( );
2. Throwable Uexcep = new Throwable("message");
3. class Uexcep extends Exception{
public Uexcep()
{
...
}
public Uexcep(String s)
8/20/2019 javanotes(1)
62/208
62
{
...
}
}
It is thrown by using keyword throw. It is also possible to override the methods such as
getmessage(), toString() etc.
Example 51 : demo of custom exceptions
import java.io.*;
class AgeException extends Exception
{
int age;
AgeException(String mesg)
{
super(mesg);
}
AgeException( )
{
super( );
}
}
class youngAgeException extends AgeException
{
youngAgeException(int a1, String mesg)
{super("you are too young for" + mesg);
age = a1;
}
youngAgeException( )
{
super( "too young");
}
}
class invalidAgeException extends AgeException{
invalidAgeExecption(String mesg)
{
super(mesg);
}
invalidAgeException(int a1 )
8/20/2019 javanotes(1)
63/208
63
{
super( "Invalidformat");
age = a1;
}
}
public Testcustom
{
public static void main(String args[])
{
int sAges = { 21,12,18,-5,45};
int i, n=sAges.length;
try
{
for( i=0; i
8/20/2019 javanotes(1)
64/208
64
An exception that is caught can once again be rethrown and can be handled again. The try
block just above the rethrown statement will catch this object.
It is used to propagate an exception.It has no special syntax.
Example 52 : Demo of rethrowing exceptions
public class Rethrowtest
{
public static void main(String args[])
{
System.out.println("prog starts here..");
int a,b,c;
try
{
a = Integer.parseInt(args[0]);
b = integer.parseInt(args[1]);
calc(a,b);
}
catch ( ArithmeticException e)
{
System.out.println("Handled in main");
System.out.println("...Invalid argumets !");
}
catch ( NumberFormatException e)
{
System.out.println("Invalid argumets");
}
catch ( ArayIndexOutOfBoundsException e)
{
System.out.println("pass proper args");
}
System.out.println("program ends here..");
}
static void calc(int a1, int b1)
8/20/2019 javanotes(1)
65/208
65
{
try
{
int c1 = a1/b1;
System.out.println("c1="+ c1);
}
catch ( ArithmeticException e)
{
System.out.println("rethrowing now..");
throw e;
}
}
}
8/20/2019 javanotes(1)
66/208
66
To Print a Stack Trace Message
Jjava provides a method getMessage() method that is used with an object of the Exception class to
print errors to debug the process. Instead of this this method we can get more information about the
error process if we use print a stack trace from the exception using the printStackTrace() method that is
the method of the Throwable class and prints the stack trace to the console and provides the line
numbers of statements that called the methods in the current stack.
try {
// ......
}
catch (IOException e) {
// ...........
System.out.print("GotException:"+ e.printStackTrace( ) ;
}
ASSERTIONS ( DESIGN BY CONTRACT ) ::
They can be used to test the assumptions made by the programmer and create software
according to user requirements
Assertions are three types
1. pre condition : Application must satisfy before calling an external component
2. post condition : Application must satisfy this after the execution of the external component
3. invariant : Application must always satisfy this condition
Exceptions test abnormal conditions where as Assertions test the conditions assumed by the
programmer.
Example 53 : Demo Assertions
public class Tester
{
public static void main(String args[]){
Tester d = new Tester( );
d.check(5,0);
}
void check(int a, int b)
http://www.roseindia.net/java/exceptions/printstacktrace.shtmlhttp://www.roseindia.net/java/exceptions/printstacktrace.shtml
8/20/2019 javanotes(1)
67/208
67
{
assert b!=0: "the value b can not be zero";
double c = a/b;
System.out.println("c="+c);
}
}
compilation : javac -source1.4 Tester.java
running : java -ea Tester
Java.Util Package
Java Utility package is one of the most commonly used packages in the java program. The Utility
Package of Java consist of the following components:
collections framework
legacy collection classes
event model
date and time facilities
internationalization
miscellaneous utility classes such as string tokenizer, random-number generator and bit
array
Here are some of the description of the utility classes of this package:
Data Structure Classes
Data Structure Classes are very useful classes for implementing standard computer science data
structures: including BitSet, Dictionary, Hashtable, Stack and Vector. The Enumeration interface
of java.util package is used to count through a set of values.
Date syst
The Date class is used to manipulate calendar dates in a system-independent fashion.
StringTokenizer
This StringTokenizer class is used to convert a String of text into its tokens.
http://www.roseindia.net/java/example/java/util/java-util-package.shtmlhttp://www.roseindia.net/java/example/java/util/java-util-package.shtmlhttp://www.roseindia.net/java/example/java/util/java-util-package.shtmlhttp://www.roseindia.net/java/example/java/util/java-util-package.shtmlhttp://www.roseindia.net/java/example/java/util/java-util-package.shtmlhttp://www.roseindia.net/java/example/java/util/java-util-package.shtml
8/20/2019 javanotes(1)
68/208
68
Properties
The properties table contains key/value pairs where both the key and the value are Strings and
the class is used by the System class to implement System properties.
Observer and Observable
Classes that implement the Observer interface can "watch" Observable objects for statechanges. When an Observable object changes it notifies all of its Observers of the change.
Random-Number Generator
The Random Number Generator class is used to generate the random-numbers.
Enumeration
The Enumeration interface defines a generic programming interface for iterating through a set
of valu
Example 54 :: Demo of a stack class
// Demonstrate the Stack class.
import java.util.*;
class StackDemo {
static void showpush(Stack st, int a) {
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack st) {
System.out.print("pop -> ");Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}
public static void main(String args[])
{
Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
8/20/2019 javanotes(1)
69/208
69
System.out.println("empty stack");
}
}
}
Example 55 :: Demo of a Date class
// Show date and time using only Date methods.
import java.util.Date;
public class DateDemo
{
public static void main(String args[])
{
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.println(date);// Display number of milliseconds since midnight, January 1,
//1970 GMT
long msec = date.getTime();
System.out.println("Milliseconds since Jan. 1, 1970 GMT = " +
msec);
}
}
Chapter 6
Collections
8/20/2019 javanotes(1)
70/208
70
Java provides the Collections Framework . In the Collection Framework , a collection represents the group
of the objects. And a collection framework is the unified architecture that represent and manipulate
collections. The collection framework provides a standard common programming interface to many of
the most common abstraction without burdening the programmer with many procedures and
interfaces. It provides a system for organizing and handling collections. This framework is based on:
Interfaces that categorize common collection types.
Classes which proves implementations of the Interfaces.
Algorithms which proves data and behaviors need when using collections i.e. search, sort,
iterate etc.
Following is the hierarchical representation for the relationship of all four interfaces of the collection
framework which illustrates the whole implementation of the framework.
During the designing of a software (application) it need to be remember the following relationship of the
four basic interfaces of the framework are as follows:
The Collection interface which is the collection of objects. That permits the duplication of the
value or objects. Set is the interface of the collections framework which extends the Collection but forbids
duplicates.
An another interface is the List which also extends the Collection. It allows the duplicates objects
on different position because it introduces the positional indexing.
And Map is also a interface of the collection framework which extends neither Set nor
Collection.
Some interfaces and classes of the collection framework are as follows:
INTERFACES CLASSES
Collection Interface
Iterator Interface
HashSet Class
TreeSet Class
http://www.roseindia.net/java/example/java/util/collections_framework.shtmlhttp://www.roseindia.net/java/example/java/util/collections_framework.shtmlhttp://www.roseindia.net/java/example/java/util/collections_framework.shtmlhttp://www.roseindia.net/java/example/java/util/collections_framework.shtmlhttp://www.roseindia.net/java/example/java/util/collections_framework.shtmlhttp://www.roseindia.net/java/example/java/util/collections_framework.shtmlhttp://www.roseindia.net/java/example/java/util/collections_framework.shtmlhttp://www.roseindia.net/java/example/java/util/collections_framework.shtml
8/20/2019 javanotes(1)
71/208
71
Set Interface
List Interface
ListIterator Interface
Map Interface
SortedSet Interface
SortedMap Interface
ArrayList Class
LinkedList Class
HashMap Class
TreeMap Class
Vector Class
Stack Class
Advantage of the Collections Framework :
The collections framework offers developers the following benefits:
It increases the readability of your collections by providing a standard set of interfaces which
has to be used by many programmers in different applications.
It makes your code more flexible. You can make the code flexible by using many interfaces and
classes of the collection framework.
It offers many specific implementations of the interfaces. It allows you to choose the collectionthat is most fitting and which offers the highest performance for your purposes.
This collection is a framework supported in java.util package. They are used to group
elements in various ways. The framework has a set of interfaces, and some implementations
to manipulate collections. Collection framework has many interfaces such as collection, Map,
Iterator
Collection classes ::
There are standard collection classes that implement collection interface.
AbstractCollection : implement Collection interface.
It is used to organize a collection which can not be modified.
AbstractList : Extends AbstractCollection, and implement the List interface. It can access
data randomly using an index value.
AbstractQueue : Extends AbstractCollection and impl parts of the queue interface.
AbstractSequentialList : Extends AbstractList into sequential
LinkedList : Extends AbstractSequentialList where each element knows where is the next
ArrayList : Implements dynamic resizable array, extends AbstractList interface.
http://www.roseindia.net/java/example/java/util/collections_framework.shtmlhttp://www.roseindia.net/java/example/java/util/collections_framework.shtmlhttp://www.roseindia.net/java/example/java/util/collections_framework.shtmlhttp://www.roseindia.net/java/example/java/util/collections_framework.shtml
8/20/2019 javanotes(1)
72/208
72
ArrayDeque : Implements dynamic deque, by extending AbstractList and,
impl the Deque Interface
AbstractSet : Extends AbstractCollection and imple the Set interface
HashSet : Extends AbstractSet and imple the Set interface. It is used tocreate a collection and store it in a hash table. Every collection has
a unique hash code. The type of storing is called hashing. Elements may
be stored in any order and it does not gurantee order.
TreeSet : Extends AbstractSet to implement a set stored in tree form. The
elements are stored in a tree structure
Map classes : AbstractMap : Implement the Map interface
HashMap : It extends the AbstractMap using a hash
TreeMap : It extends AbstractMap using a tree
Apart from these , we see Arrays, Vector, Stack, Hashtable, Dictionary, properties, and
other classes which are not technically members of this collection framework.
Example 56 : Demo of array class
import java.util.*;
class arrays
{
public static void main(String args[])
{
int a[] = new int[10];
8/20/2019 javanotes(1)
73/208
73
for(int i = 9; i > 0; i--)
array[i] = -i;
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");System.out.println();
Arrays.sort(a);
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
System.out.print("Found -5 at position " +
Arrays.binarySearch(a, -5));
}
}
Example 57 : Demo of Vector class
A Vector class is similar to ArrayList except that Vector class is synchronized. Multiple
threads can not access it simultaneously. It implement the dynamic array. It predates
collection framework. It has been rewritten to be compatible with collection framework
import java.util.*;class Testvector
{
public static void main(String args[])
{
Vector v = new Vector(5);
System.out.println("Capacity: " + v.capacity());
v.addElement(new Integer(10));
v.addElement(new Integer(11));
v.addElement(new Integer(22));
v.addElement(new Integer(33));
v.addElement(new Integer(44));
v.addElement(new Double(3.14));
v.addElement(new Float(3.14));
8/20/2019 javanotes(1)
74/208
74
System.out.println("Capacity: " + v.capacity());
System.out.println("Size: " + v.size());
System.out.println("First item:"+(Integer)v.firstElement());
System.out.println("Last item:" + (Float) v.lastElement());
if(v.contains(new Integer(33)))
System.out.println("Found 3.");
Iterator e = v.iterator();
while (e.hasNext())
{
s = (String)v.next();
System.out.print(s);
}
}
}
output :
capacity : 5
capacity : 10
size : 7
First item 0
Last item 3.14
Found a 3
10 11 22 33 44 3.14 3.14
Example 58 : Demo of ArrayList ( Dynamic and can grow )
It holds only the objects, and it can grow or shrink at run time.
import java.util.*;
class arraylist
{
public static void main(String args[]){
ArrayList al = new ArrayList();
al.add("Red");
al.add("Blue");
al.add("Yellow");
8/20/2019 javanotes(1)
75/208
75
al.add(1, "White");
System.out.println("Using the add method");
System.out.println(al);
al.remove("White");
System.out.println(al);
String l = al.get(1);
System.out.println(l);
System.out.println("Using the Iterator interface");
String s;
Iterator e = al.iterator();
while (e.hasNext())
{
s = (String)e.next();
System.out.print(s);
}
}
}
8/20/2019 javanotes(1)
76/208
76
Example 59 : Demo of linkedlist
import java.util.*;
class linkedlist
{
public static void main(String args[]){
LinkedList ls = new LinkedList();
ls.add("Blue");
ls.add("Green");
ls.add("Yellow");
ls.add("Orange");
ls.addFirst("Red");
ls.addLast("Black");
ls.add(1, "Grey");
System.out.println(ls);
ls.remove("Black");
System.out.println(ls);
ls.removeLast();
System.out.println(ls);
System.out.println("Updating linked list items");
ls.set(0, "java");
ls.set(1, "C");
ls.set(2, "C++");
ls.set(3, "Oracle");
ls.set(4, "ASP.net");
System.out.println(ls);
}
}
8/20/2019 javanotes(1)
77/208
77
Example 60 : Demo of HashSet class
It is set of unique elements, and it uses a hash for storing data. As it uses hash methods such
as add, remove, size etc and they take same amount of time. No gurantee of order of storage.
import java.util.*;class hashset
{
public static void main(String args[])
{
HashSet h1 = new HashSet();
h1.add("Red");
h1.add("Blue");
h1.add("Green");
System.out.println(h1);
int s = h1.size() ;
System.out.println(s);
if( h1.contains("Red"))
System.out.print("Red present" );
}
}
Example 61 : Demo of looping over all elements in a list
( Iterator )
import java.util.*;
class iterator
{
public static void main(String args[])
{
LinkedList l = new LinkedList();
l.add("Item 0");
l.add("Item 1");
l.add("Item 2");
Iterator it = l.iterator();
8/20/2019 javanotes(1)
78/208
78
while(it.hasNext())
{
System.out.print(it.next());
}
}
}
Example 55: Demo of ListIterator
It can Loop over in both the directions
import java.util.*;
class listiterator
{
public static void main(String args[])
{
LinkedList li = new LinkedList();
li.add("Item 0");
li.add("Item 1");
li.add("Item 2");
li.add("Item 3");
ListIterator lite = li.listIterator();
while(lite.hasNext()){
lite.set("This is " + lite.next());
/* set() is used to replace the element which is
returned by next() or previous() by the current */
}
while(lite.hasPrevious())
{
System.out.println(lite.previous());
}}
}
Example 62 : Demo of HashMap
8/20/2019 javanotes(1)
79/208
79
Hash Maps allow the data to be stored as key/value pairs where key,value are objects. Map
can be indexed with strings instead of numbers. On such Maps it is possible to access elements
using strings or search them using string value.
import java.util.*;
class hashmap{
public static void main(String args[])
{
HashMap hm = new HashMap();
hm.put("Item 0", "Value 0");// to add key,value pair to map
hm.put("Item 1", "Value 1");
hm.put("Item 2", "Value 2");
hm.put("Item 3", "Value 3");
Set s = hm.entrySet();// get corresponding set
Iterator it = s.iterator();
while(it.hasNext())
{
Map.Entry mp = (Map.Entry) it.next();
System.out.println(mp.getKey() + "/" + mp.getValue());
// it prints the key, value pairs
}
System.out.print(hm.get("Item 0"));//search for corresponding value
}
}
8/20/2019 javanotes(1)
80/208
80
Example 63 : Demo of Hashtable class
It imple the interfaces such as Map,Clonable,Serializable. It is used to store values, in the form
of map key with a value. The "key" should implement the hashcode, and equals method to
store and retrieve values in a hashtable. It was how maps were implemented before collection
framework.
import java.util.*;
class Testhashtable
{
public static void main(String args[])
{
Hashtable ht = new Hashtable();
ht.put("B1", "Billgates");
ht.put("C2", "Chouhan");
ht.put("P3", "Pushkal");
ht.put("A4", "Anuj Singh");
Enumeration e = ht.keys();
while(e.hasMoreElements())
{
String s = (String) e.nextElement();
System.out.println("key " + s + "/" + "Val" + ht.get(s));
}
}}
output : key C2 / val Chouhan
key A4 / val Anuj
...e t c...
8/20/2019 javanotes(1)
81/208
81
Example 64 : Demo of Hashtable class
import java.util.*;
class Testhashtable
{
public static void main(String args[])
{Hashtable ht = new Hashtable(4);
ht.put("Billgates", Integer(55));
ht.put("Chouhan",Integer( 60));
ht.put("Pushkal", Integer(52));
ht.put("Anuj", I