73
Constructors: The constructor is a specialised method used to initialising the objects.Note that the same of the constructor and name of the class must be the same. 1: Write a Java Program to define a class, describe its constructor, overload the Constructors and instantiate its object class Rectangle1 { int height; int width; Rectangle1() { System.out.println("Simple constructor values are intialised....."); height=10; width=20; } Rectangle1(int h,int w) { System.out.println("Parameterised constructor values are initialised"); height=h; width=w; } void area() { System.out.println("Now the function is called"); int result=height*width; System.out.println("The area is "+result); } } class Program1 { public static void main(String args[]) { Rectangle1 obj=new Rectangle1(); obj.area(); Rectangle1 obj1=new Rectangle1(3,5); obj1.area(); } } ----------------------OUTPUT-------------------- C:\>cd jdk1.2 C:\jdk1.2>cd bin

Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Embed Size (px)

Citation preview

Page 1: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Constructors: The constructor is a specialised method used to initialising the objects.Note that

the same of the constructor and name of the class must be the same.

1: Write a Java Program to define a class, describe its constructor, overload the

Constructors and instantiate its object

class Rectangle1

{

int height;

int width;

Rectangle1()

{

System.out.println("Simple constructor values are intialised.....");

height=10;

width=20;

}

Rectangle1(int h,int w)

{

System.out.println("Parameterised constructor values are initialised");

height=h;

width=w;

}

void area()

{

System.out.println("Now the function is called");

int result=height*width;

System.out.println("The area is "+result);

}

}

class Program1

{

public static void main(String args[])

{

Rectangle1 obj=new Rectangle1();

obj.area();

Rectangle1 obj1=new Rectangle1(3,5);

obj1.area();

}

}

----------------------OUTPUT--------------------

C:\>cd jdk1.2

C:\jdk1.2>cd bin

Page 2: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

C:\jdk1.2\bin>javac Program1.java

C:\jdk1.2\bin>java Program1

------------------------------------------------------

Simple constructor values are intialised.....

Now the function is called

The area is 200

Parameterised constructor values are initialized

Now the function is called

The area is 15

------------------------------------------------------

Copy Constructor:

There is no copy constructor in java. But, we can copy the values of one object to

another like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

o By constructor

o By assigning the values of one object into another

o By clone() method of Object class

class Student6{

int id;

String name;

Student6(int i,String n){

id = i;

name = n;

}

Student6(Student6 s){

id = s.id;

name =s.name;

}

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){

Page 3: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Student6 s1 = new Student6(111,"Karan");

Student6 s2 = new Student6(s1);

s1.display();

s2.display();

}

}

javac Student6.java

java Student6

111 Karan

111 Karan

this keyword: this can be used to refer current class instance variable.

class Student{

int rollno;

String name;

float fee;

Student(int rollno,String name,float fee){

this.rollno=rollno;

this.name=name;

this.fee=fee;

}

void display(){System.out.println(rollno+" "+name+" "+fee);}

}

class TestThis2{

public static void main(String args[]){

Student s1=new Student(111,"ankit",5000f);

Student s2=new Student(112,"sumit",6000f);

s1.display();

s2.display();

}} output

111 ankit 5000

112 sumit 6000

Page 4: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Java Garbage Collection

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically.

In other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection

o It makes java memory efficient because garbage collector removes the

unreferenced objects from heap memory.

o It is automatically done by the garbage collector(a part of JVM) so we don't

need to make extra efforts.

finalize() method

The finalize() method is invoked each time before the object is garbage collected. This

method can be used to perform cleanup processing. This method is defined in Object class as:

1. protected void finalize(){}

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing.

The gc() is found in System and Runtime classes.

1. public static void gc(){}

Simple Example of garbage collection in java

1. public class TestGarbage1{

2. public void finalize(){System.out.println("object is garbage collected");}

3. public static void main(String args[]){

4. TestGarbage1 s1=new TestGarbage1();

5. TestGarbage1 s2=new TestGarbage1();

6. s1=null;

7. s2=null;

8. System.gc();

Page 5: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

9. }

10. }

Overloading methods

Write a Java Program to define a class, define instance methods and overload them and

use them for dynamic method invocation.

public class Overloading

{

public static void main(String args[])

{

System.out.println("Sum of two Integer");

Sum(10,20);

System.out.println("Sum of two double numbers");

Sum(10.5,20.4);

System.out.println("Sum of three integers");

Sum(10,20,30);

}

public static void Sum(int n1,int n2)

{

int ans;

ans=n1+n2;

System.out.println(ans);

}

public static void Sum(double n1,double n2)

{

double ans;

ans=n1+n2;

System.out.println(ans);

}

public static void Sum(int n1,int n2,int n3)

{

int ans;

ans=n1+n2+n3;

System.out.println(ans);

}

}

Page 6: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

----------------------OUTPUT--------------------

C:\>cd jdk1.2

C:\jdk1.2>cd bin

C:\jdk1.2\bin>javac Overloading.java

C:\jdk1.2\bin>java Overloading

------------------------------------------------------

Sum of two Integer

30

Sum of two double numbers

30.9

Sum of three integers

60

------------------------------------------------------

Call by Value and Call by Reference in Java

There is only call by value in java, not call by reference. If we call a method passing a

value, it is known as call by value. The changes being done in the called method, is

not affected in the calling method.

Example of call by value in java

In case of call by value original value is not changed. Let's take a simple example:

class Operation{

int data=50;

void change(int data){

data=data+100;//changes will be in the local variable only

}

public static void main(String args[]){

Operation op=new Operation();

System.out.println("before change "+op.data);

op.change(500);

System.out.println("after change "+op.data);

}

}

Output:before change 50

after change 50

Page 7: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Call by reference

In case of call by reference original value is changed if we made changes in the called

method. If we pass object in place of any primitive value, original value will be changed. In

this example we are passing object as a value. Let's take a simple example:

Object as parameter:

class Operation2{

int data=50;

void change(Operation2 op){

op.data=op.data+100;//changes will be in the instance variable

}

public static void main(String args[]){

Operation2 op=new Operation2();

System.out.println("before change "+op.data);

op.change(op);//passing object

System.out.println("after change "+op.data);

}

}

Output:before change 50

after change 150

Returning Objects

We can return an object from a method.The data type such method is a class type.

public class objRetDemo

{

int a ;

ObjRetDemo(int val)

{

A=val;

Page 8: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

}

ObjRetDemo fun()

{

ObjRetDemo temp=new ObjRetDemo(a+5);//created a new object

return temp;//returning the object from this method.

}

}

class ObjRet

{

public static void main(String args[])

{

ObjRetDemo obj2=new ObjRetDemo(20);

ObjRetDemo obj1;

Obj1=obj2.fun();

System.out.println(“The returned value is=”+obj1.a);

}

}

Access Control

Inheritance in Java

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Page 9: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

The idea behind inheritance in java is that you can create new classes that are built upon

existing classes. When you inherit from an existing class, you can reuse methods and

fields of parent class, and you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).

o For Code Reusability.

Syntax of Java Inheritance

class Subclass-name extends Superclass-name

{

//methods and fields

}

The extends keyword indicates that you are making a new class that derives from

an existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called parent or super class

and the new class is called child or subclass.

Java Inheritance Example

Page 10: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

As displayed in the above figure, Programmer is the subclass and Employee is the superclass.

Relationship between two classes is Programmer IS-A Employee.It means that Programmer

is a type of Employee.

class Employee{

float salary=40000;

}

class Programmer extends Employee{

int bonus=10000;

public static void main(String args[]){

Programmer p=new Programmer();

System.out.println("Programmer salary is:"+p.salary);

System.out.println("Bonus of Programmer is:"+p.bonus);

}

}

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel

and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface

only. We will learn about interfaces later.

Page 11: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

class A

{

int a;

void set_a(int i)

{

a=i;

}

void show_a()

{

System.out.println("The value of a is"+a);

}

}

class B extends A

{

int b;

void set_b(int i)

{

b=i;

}

void show_b()

{

System.out.println("The value of a is"+b);

Page 12: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

}

void mul()

{

int c;

c=a*b;

System.out.println("The value of c"+c);

}

}

class Program4

{

public static void main(String args[])

{

A obj_A=new A();

B obj_B=new B();

obj_B.set_a(10);

obj_B.set_b(30);

obj_B.show_a();

obj_B.show_b();

obj_B.mul();

}

}

Multilevel inheritance

Write a Java Program to implement multilevel inheritance by Applying various access

controls to its data members and methods.

class A

{

int a;

void set_a(int i)

{

a=i;

}

void show_a()

{

System.out.println("The valueof a is:"+a);

}

Page 13: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

}

class B extends A

{

int b;

void set_b(int i)

{

b=i;

}

void show_b()

{

System.out.println("The valur of b is:"+b);

}

}

class C extends B

{

int c;

void set_c(int i)

{

c=i;

}

void show_c()

{

System.out.println("The valur of c is:"+c);

}

void mul()

{

int ans;

ans=a*b*c;

System.out.println("The ans is:"+ans);

}

}

class Mlt

{

public static void main(String args[])

{

A obj_A=new A();

B obj_B=new B();

C obj_C=new C();

obj_C.set_a(2);

obj_C.set_b(3);

obj_C.set_c(4);

obj_C.show_a();

obj_C.show_b();

obj_C.show_c();

obj_C.mul();

}

}

Page 14: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

..........................................OUTPUT...................................................

C:\jdk1.2\bin>javac Mlt.java

C:\jdk1.2\bin>java Mlt

The valueof a is:2

The valur of b is:3

The valur of c is:4

The ans is:24

Introducing access controls in java

how to specify access specifiers: public: private: protect

Access control:

Encapsulation links data with the code that manipulates it. However,encapsulation provides

another important attribute: access control.Java‟s access specifiers are public, private, and

protected. Java also defines a default access level.protected applies only when inheritance is

involved. When a member of a class is modified by the public specifier, then that member

can be accessed by any other code.

When a member of a class is specified asprivate, then that member can only be accessed by

other members of its class.

Acess specifiers

public:

A class, method, constructor, interface etc declared public can be accessed from any other

class. Therefore fields, methods, blocks declared inside a public class can be accessed from

any class belonging to the Java

Universe.

Page 15: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

private:

Methods, Variables and Constructors that are declared private can only be accessed within

the declared class itself. Private access modifier is the most restrictive access level. Class and

interfaces cannot be private.Variables that are declared private can be accessed outside the

class if public getter methods are present in the class.

protect:

Variables, methods and constructors which are declared protected in a superclass can be

accessed only by the subclasses in other package or any class within the package of the

protected members' class.The protected access modifier cannot be applied to class and

interfaces.

Default:

Default access modifier means we do not explicitly declare an access modifier for a class,

field, method, etc. A variable or method declared without any access control modifier is

available to any other class in the same package. The fields in an interface are implicitly

public static final and the methods in an interface are by default public.

Example for access control

/* This program demonstrates the difference between public and private.*/

class Test

{

int a; // default access

public int b; // public access

private int c; // private access

// methods to access c

Page 16: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

void setc(int i) // set c's value

{

c = i;

}

int getc() // get c's value

{

return c;

}

}

class AccessTest

{

public static void main(String args[])

{

Test ob = new Test();

// These are OK, a and b may be accessed directly

ob.a = 10;

ob.b = 20;

// This is not OK and will cause an error

// ob.c = 100; // Error!

// You must access c through its methods

ob.setc(100); // OK

System.out.println("a, b, and c: " + ob.a + " " +ob.b + " " + ob.getc());

}

}

Java static method

i)A static method belongs to the class rather than object of a class.

ii)A static method can be invoked without the need for creating an instance of a class.

Page 17: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

iii)static method can access static data member and can change the value of it.

The static keyword in java is used for memory management mainly. We can apply java static

keyword with variables, methods, blocks and nested class. The static keyword belongs to the

class than instance of the class.

The static can be:

variable (also known as class variable)

method (also known as class method)

block

nested class

1) Java static variable

If you declare any variable as static, it is known static variable.

The static variable can be used to refer the common property of all objects (that is not unique

for each object) e.g. company name of employees,college name of students etc.

The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Program of counter without static variable

In this example, we have created an instance variable named count which is incremented in

the constructor. Since instance variable gets the memory at the time of object creation, each

object will have the copy of the instance variable, if it is incremented, it won't reflect to other

objects. So each objects will have the value 1 in the count variable.

class Counter{

int count=0;//will get memory when instance is created

Page 18: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Counter(){

count++;

System.out.println(count);

}

public static void main(String args[]){

Counter c1=new Counter();

Counter c2=new Counter();

Counter c3=new Counter();

}

}

Output:1

1

1

Program of counter by static variable

As we have mentioned above, static variable will get the memory only once, if any object

changes the value of the static variable, it will retain its value.

class Counter2{

static int count=0;//will get memory only once and retain its value

Counter2(){

count++;

Page 19: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

System.out.println(count);

}

public static void main(String args[]){

Counter2 c1=new Counter2();

Counter2 c2=new Counter2();

Counter2 c3=new Counter2();

}

}

Output:1

2

3

Final Keyword In Java

The final keyword in java is used to restrict the user. The java final keyword can be used in

many context. Final can be:

i)variable

ii)method

iii)class

The final keyword can be applied with the variables, a final variable that have no value it is

called blank final variable or uninitialized final variable. It can be initialized in the

constructor only. The blank final variable can be static also which will be initialized in the

static block only. We will have detailed learning of these. Let's first learn the basics of final

keyword.

final keyword in java

Page 20: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It will be

constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It

can't be changed because final variable once assigned a value can never be changed.

class Bike9{

final int speedlimit=90;//final variable

void run(){

speedlimit=400;

}

public static void main(String args[]){

Bike9 obj=new Bike9();

obj.run();

}

}//end of class

Output:Compile Time Error

Nested and inner classes

Nested Classes. In Java, just like methods, variables of a class too can have another class as

its member. Writing a class within another is allowed in Java. The class written within is

called the nested class, and the class that holds the inner class is called the outer class.

Page 21: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Example of Inner class

class Outer

{

public void display()

{

Inner in=new Inner();

in.show();

}

class Inner

{

public void show()

{

System.out.println("Inside inner");

}

}

}

Page 22: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

class Test

{

public static void main(String[] args)

{

Outer ot=new Outer();

ot.display();

}

}

Output :

Inside inner

2) import java.lang.*;

public class Program5

{

int a=10;

class inside

{

int a=20;

public void display()

{

System.out.println("a="+this.a);

}

}

public void display()

{

new inside().display();

}

public static void main(String args[ ])

{

new Program5().display();

}

}

----------------------OUTPUT--------------------

C:\>cd jdk1.2

C:\jdk1.2>cd bin

C:\jdk1.2\bin>javac Program5.java

C:\jdk1.2\bin>java Program5

------------------------------------------------------

Page 23: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

a=20

------------------------------------------------------

Command line argument in Java The command line argument is the argument passed to a program at the time when you run it.

To access the command-line argument inside a java program is quite easy, they are stored as

string in String array passed to the args parameter of main() method.

The java command-line argument is an argument i.e. passed at the time of running the

java program.

The arguments passed from the console can be received in the java program and it can be used as an input.

So, it provides a convenient way to check the behavior of the program for the different

values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.

Example

class cmd

{

public static void main(String[] args)

{

for(int i=0;i< args.length;i++)

{

System.out.println(args[i]);

}

}

}

Page 24: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Variable Length Arguments(varargs ): Beginning with JDK 5, Java has included a feature

that simplifies the creation of methods that need to take a variable number of arguments. This

feature is called as varargs (short for variable-length arguments).

A method that takes a variable number of arguments is called a variable-arity method, or

simply a varargs method.

class JavaProgram

{

/* vaTest() now uses a vararg */

static void vaTest(int ... v)

{

System.out.print("Number of arguments = " + v.length + ", Contents = ");

for(int x : v)

{

System.out.print(x + " ");

}

Page 25: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

System.out.println();

}

public static void main(String args[])

{

/* notice how vaTest() can be called with

* a variable number of arguments

*/

vaTest(10); // 1 argument

vaTest(1, 2, 3); // 3 arguments

vaTest(); // no arguments

}

}

Page 26: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Member access and Inheritance

A subclass includes all of the members of its super class but it cannot access those members

of the super class that have been declared as private. Attempt to access a private variable

would cause compilation error as it causes access violation. The variables declared as private,

is only accessible by other members of its own class. Subclass have no access to it.

E.g.:

import java.io.*;

class Stud

{

String name;

int age;

double rollno;

Stud()

{

name="null";

age=-1;

rollno=-1;

}

Stud(String na, int a,double r)

name=na;

age=a

rollno=r;

}

void Disp()

Page 27: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

{

System.out.println("Name:"+name);

System.out.println("Age:"+age);

System.out.println("Rollno:"+rollno);

}

}

class Studmark extends Stud

{

double mark;

Studmark(String name1,int age1,int rollno1,double mark1)

{

name=name1;

age=age1;

rollno=rollno1;

mark=mark1;

}

}

class Student

{

public static void main(String[] args)

{

Studmark s1=new Studmark("A",10,101,562);

Studmark s2=new Studmark("B",12,103,580);

System.out.println("First object");

s1.Disp();

System.out.println("Mark of s1"+s1.mark);

System.out.println("second object");

Page 28: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

s2.Disp();

System.out.println("Mark of s2"+s2.mark);

}

}

Output:

First object

Name:A

Age:10

Rollno:101.0

Mark of s1:562.0

Second object

Name:B

Age:12

Rollno:103.0

Mark of s2:580.0

Note:

A major advantage of inheritance is that once you have created a super class that defines the

attributes common to a set of objects, it can be used to create any number of more specific

subclasses.

Page 29: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Super Classes

Using super:

Consider two classes A & B

import java.io.*;

class A

{ double width,height,depth;

A()

{

width=-1;

height=-1;

depth=-1;

}

A(double w,double h,double d)

{

width=w;

height=h;

depth=d;

}

}

class B extends A

{

double weight;

B(double w,double h,double d,double m)

{

Page 30: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

width=w;

height=h;

depth=d;

weight=m;

}

void Disp()

{

System.out.println("widthis"+width);

System.out.println("height is"+height);

System.out.println("depth is"+depth);

System.out.println("weight is"+weight);

}

}

public class Main

{ public static void mai

n(String[] args)

{

B b=new B(10,20,30,40);

b.Disp();

}

}

Output:

widthis10.0

height is20.0

depth is30.0

weight is40.0

Page 31: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Here the constructor for B explicitly initializes the width, height, depth fields of B.

There will be times when the super class should keep the details of its implementation to

itself (i.e. to keep the data members private).Here, no way exists for a subclass to directly

access or initialize these variables on its own.

The solution for this problem is provided by using keyword „super‟. Whenever a subclass

needs to refer to its immediate super class, it can do so by using the super keyword. „super‟

has 2 general form:

Using „super‟ to call super class constructors

A subclass can call a constructor method defined by its super class by use of the following

form of „super‟. Syntax is:

The above example can be modified as:

class B extends A

{

B(double w,double h,double d,double m)

{

super(w,h,d);

width=m;

}

}

super() with parameter w,h,d causes the A() to be called, which initializes width,height,and

depth using these values. Class B no longer initializes these values itself.It only needs to

initialize the value unique to it. This helps to leave A to make its values private. Since

Page 32: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

constructors can be overloaded, super() can be called using any form defined by the super

class. The constructor executed will be the one that matches the arguments.

Multilevel Hierarchy

Given 3 classes A,B & C. C can be a subclass of B which is a subclass of A.

Here, each subclass inherits all of its traits founds in all the super classes. That is, C inherits

all aspects of B & A.

E.g.:Consider,

class A

{

private double i;

private double j;

private double k;

A(double a,double b,double c)

{

i=a;

j=b;

k=c;

}

double Sum()

{

return i+j+k;

}

}

Page 33: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

class B extends A

{

double l;

B(double a,double b,double c,double d)

{

super(a,b,c);

l=d;

}

}

class C extends B

{

double m;

C(double a,double b,double c,double d,double e )

{

super(a,b,c,d);

m=e;

}

}

public class Main

{

public static void main(String[] args)

{

C bc=new C(10,20,30,40,50);

double sum;

sum=bc.Sum();

System.out.println("Sum of bc:"+sum);

System.out.println("l:"+bc.l);

Page 34: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

System.out.println("m:"+bc.m);

}

}

Output:

Sum of bc:60.0

l:40.0

m:50.0

Due to inheritance C can use the previously defined class of B & A, adding only the extra

information it needs for its own specific application.

Here, code reusability is applied.

It is also clear that „super‟ always refer to the constructor in the closest super class.

Calling of Constructors

In class hierarchy, the constructors are called in order of derivation i.e. from super class to

subclass. As super() is the first statement executed in a subclass‟ constructor, this order is the

same whether or not super() is used.

When super() is not used, the default or non parameter constructor of each super class will be

executed.

E.g.:

import java.io.*;

class A

{

A()

{

Page 35: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

System.out.println("In A");

}

}

class B extends A

{

B()

{

System.out.println("In B");

}

}

class C extends B

{

C()

{

System.out.println("In C");

}

}

public class Main

{

public static void main(String[] args)

{

C c=new C();

}

}

Output:

In A

In B

In C

Page 36: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Method Overriding

When a method in a subclass has the same name and type as a method in its super class, then

the method in subclass is said to “override“ the method in the super class. When an

overridden method is called from within a subclass, it refers to the method defined by the

subclass. The version of the method in the super class will be hidden.

Eg:

import java.io.*;

class A

{

int i,j;

A(int a,int b)

{

i=a;

j=b;

}

void Display()

{

System.out.println("i&j"+i+""+j);

}

}

class B extends A

{

int k;

B(int a,int b,int c)

{

super(a,b);

k=c;

}

void Display()

{

System.out.println("k:"+k);

}

}

public class Main

{

public static void main(String[] args)

{

B b=new B(15,25,35);

b.Display();

}

Page 37: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

}

Output:

k:35

here, when display() is invoked by b, display() in B is used as display() in B overrides the one

declared in A. To access the display() in A, ‟super‟ keyword can be used.

E.g.:

import java.io.*;

class A

{

int i,j;

A(int a,int b)

{

i=a;

j=b;

}

void Display()

{

System.out.println("i:"+i);

System.out.println("j:"+j);

}

}

class B extends A

{

int k;

B(int a,int b,int c)

{

super(a,b);

k=c;

}

void Display()

{

super.Display();

System.out.println("k:"+k);

}

}

public class Main

{

public static void main(String[] args)

{

B b=new B(15,25,35);

Page 38: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

b.Display();

}

}

Output:

i:15

j:25

k:35

Note: Method overriding does not occur when methods are overloaded!

Reason for Overriding:

Overridden methods allow Java to support run time polymorphism as it allows a general class

to specify methods that will be common to all of its derivatives, while allowing subclasses to

define the specific implementation of some or all of those methods. By combining inheritance

with overridden methods, a superclass can define the general form of the methods that will be

used by all of its subclasses.

E.g.:

import java.io.*;

class A

{

void dis()

{

System.out.println("Hi iam dis method ofA class!!!!!!!!!");

}

}

class B extends A

{

void dis()

{

System.out.println("Hai iam dis method of B class");

}

}

public class Main

{

public static void main(String[] args)

{

B b=new B();

b.dis();

}

}

Page 39: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Output:

Hai iam dis method of B class

Dynamic Method Dispatch

Method overriding forms the basis for one of Java‟s most important powerful concepts i.e.

Dynamic method dispatch. It is the mechanism which helps to resolve the call to an

overridden method at run time, rather than compile time. It is one of the ways how Java

implements polymorphism. Overridden method is called through a super class reference, the

version of the method to execute is based upon the type of the object being referred to at the

time the call occurs.i.e the type of the object being referred to determine which version of the

overridden method will be executed.

Eg:

import java.io.*;

class A

{

void Disp()

{

System.out.println("Inside A");

}

}

class B extends A

{

void Disp()

{

System.out.println("Inside B");

}

}

class C extends A

{

void Disp()

{

System.out.println("Inside c");

}

}

public class Main

{

public static void main(String[] args)

{

A aa=new A();

Page 40: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

B bb=new B();

C cc=new C();

A r;

r=aa;

r.Disp();

r=bb;

r.Disp();

r=cc;

r.Disp();

}

}

Output:

Inside A

Inside B

Inside c

Here, A is the super class with 2 subclasses B & C, overriding disp(). „r‟ is the reference

variable which is used to invoke disp().

Abstract classes An abstract class is a class that is declared abstract —it may or may not include abstract

methods. Abstract classes cannot be instantiated, but they can be subclassed. When an

abstract class is subclassed, the subclass usually provides implementations for all of the

abstract methods in its parent class.

They are used in a situation where a class is to be defined that declares the structure of a

given application without providing a complete implementation of every method. This super

class only defines a generalized form that will be shared by all of its subclasses, so that the

subclass can define these functions according to their requirement. In some cases, we need to

ensure that a subclass indeed overrides all necessary methods.

Eg: To find the area of a polygon.

The class without a method to compute the area of the specified polygon is of no use!

By specifying a method as „abstract‟, it means that the methods has to be overridden by the

subclasses & hence are known as „responsibility of subclasses‟.

General form:

abstract ret_type Fn_name(param_list);

Page 41: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Any class that contains 1 or more abstract methods must be declared as abstract.

No abstract constructors/abstract methods can be defined.

Abstract classes cannot have objects.

A subclass must always define the abstract methods of its superclass or else must be declared

as „abstract‟ .

Eg:

import java.io.*;

abstract class AB

{

abstract void Disp();

void Hello()

{

System.out.println("Hello!!!");

}

}

class B extends AB

{

void Disp()

{

System.out.println("Hello my dear friends!!!");

}

}

public class Main

{

public static void main(String[] args)

{

B bb=new B();

bb.Disp();

bb.Hello();

}

}

Output:

Hello my dear friends!!!

Hello!!!

Page 42: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Abstract class in Java

A class that is declared with abstract keyword, is known as abstract class in java. It can have

abstract and non-abstract methods (method with body).

Before learning java abstract class, let's understand the abstraction in java first.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality

to the user.

Another way, it shows only important things to the user and hides the internal details for

example sending sms, you just type the text and send the message. You don't know the

internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Abstract class in Java

A class that is declared as abstract is known as abstract class. It needs to be extended and its

method implemented. It cannot be instantiated.

Example abstract class

abstract class A{}

abstract method

A method that is declared as abstract and does not have implementation is known as abstract

method.

Example abstract method

abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method

In this example, Bike the abstract class that contains only one abstract method run. It

implementation is provided by the Honda class.

abstract class Bike{

abstract void run();

}

class Honda4 extends Bike{

void run(){System.out.println("running safely..");}

Page 43: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

public static void main(String args[]){

Bike obj = new Honda4();

obj.run();

}

}

running safely..

Object class in Java The java.lang.Object class is the root of the class hierarchy. Every class has Object as a

superclass. All objects, including arrays, implement the methods of this class.

The Object class is the parent class of all the classes in java by default. In other words, it is

the topmost class of java.

The Object class is beneficial if you want to refer any object whose type you don't know.

Notice that parent class reference variable can refer the child class object, know as upcasting.

Let's take an example, there is getObject() method that returns an object but it can be of any

type like Employee,Student etc, we can use Object class reference to refer that object. For

example:

Object obj=getObject();//we don't know what object will be returned from this method

The Object class provides some common behaviors to all the objects such as object can be

compared, object can be cloned, object can be notified etc.

Method Description

public final Class getClass() returns the Class class object of this object.

Page 44: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

The Class class can further be used to get

the metadata of this class.

public int hashCode() returns the hashcode number for this

object.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws

CloneNotSupportedException

creates and returns the exact copy (clone)

of this object.

public String toString() returns the string representation of this

object.

public final void notify() wakes up single thread, waiting on this

object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this

object's monitor.

public final void wait(long timeout)throws

InterruptedException

causes the current thread to wait for the

specified milliseconds, until another thread

notifies (invokes notify() or notifyAll()

method).

public final void wait(long timeout,int

nanos)throws InterruptedException

causes the current thread to wait for the

specified milliseconds and nanoseconds,

until another thread notifies (invokes

notify() or notifyAll() method).

public final void wait()throws

InterruptedException

causes the current thread to wait, until

another thread notifies (invokes notify() or

notifyAll() method).

protected void finalize()throws Throwable is invoked by the garbage collector before

object is being garbage collected.

Packages

Packages are collection of classes that are used to keep the class name space.

The package is both naming and visibility control mechanism.

You can define classes inside a package that are not accessible by code outside the package.

Every classes are contained by packages .

Any class declared within the file will be belongs to specified package.

Page 45: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Two classes in two different packages can have the same name.

Defining packages:

Syntax : package pkg1;

Here pkg1 is the name of the package.

Package statement defines the name space in which classes are stored.More than one file can

include the same package statement.

The general form is given below.

Package [pkg1.[pkg2[.pkg3]]];

For example:package java.Util.Date;

The package can not be renamed , without renaming the directory in which the classes are

stored.

Member Access:

Java provides many levels of protection to allow fine-grained control over the visibility of

variables and methods within the classes , subclasses and packages.Java has four types of

access specifiers namely :

Private

Default

Protected

Public

If the members are private , then data is only accessed within the class , but It is not accessed

outside the class.

If the members are default , the data is accessed within classes and accessed within the same

package , whether the class is inherited or not.

If the members are protected , the data is accessed within the class and accessed within the

package , whether the class is inherited or not , but outside the package only when the class is

inherited.

If the members are public , the data is freely accessed within the package and outside the

package with or without inheritance.

Page 46: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

In Java,if the methods and variables are declared without any access specifier then , it is no

access by default .Methods and variables are accessed to all the classes within the same

package.

Members Private Default Protected Public

Same class Yes Yes Yes Yes

Within the same package class & is inherited. No Yes Yes Yes

Within the same package class & is not inherited No Yes Yes Yes

Outside the package class & is inherited. No No Yes Yes

Outside the package class & is not inherited No No No Yes

Importing Packages:

Java includes the import statement to bring certain classes or entire packages into

visibility.„import‟ is a keyword in java that is used to access the class files of the user-defined

package and pre-defined package.

Syntax :import pkg1[.pkg2].classname.*;

NOTE:

All of the standard java classes included with java are stored in a package called java.

The basic language files are stored in a package inside of the java package called java.lang.

Sample Program:

Package creation:

package pkg;

public class sample1

{

String name;

int age;

public sample1(String n,int a)

{

name =n;

age=a;

}

public void disp1()

{

System.out.println("Name is "+name+" age is "+age);

}

}

Page 47: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Importing Package

The above package pkg can be used in our program as follows:

import pkg.*;

class Example

{

public static void main(String s[])

{

sample1 s1= new sample1("Anu",18);

s1.disp1();

}

}

OUTPUT :

Name is Anu age is 18

Interface in java with example programs It has static constants and abstract methods. The interface in java is a mechanism to achieve

abstraction. There can be only abstract methods in the java interface not method body. It is

used to achieve abstraction and multiple inheritance in Java.

interfaces, which are used for achieving full abstraction.Interface looks like class but it is not

a class. An interface can have methods and variables just like the class but the methods

declared in interface are by default abstract (only method signature, no body). Also, the

variables declared in an interface are public, static & final by default.

Since methods in interfaces do not have body, they have to be implemented by the class

before you can access them. The class that implements interface must implement all the

methods of that interface. Also, java programming language does not support multiple

inheritance, using interfaces we can achieve this as a class can implement more than one

interfaces, however it cannot extend more than one classes.

Understanding relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends

another interface but a class implements an interface.

Page 48: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Declaration

Interfaces are declared by specifying a keyword “interface”. E.g.:

interface MyInterface

{

/* All the methods are public abstract by default

* Note down that these methods are not having body

*/

public void method1();

public void method2();

}

Interface Implementation

This is how a class implements an interface. It has to provide the body of all the methods that

are declared in interface.

Note: class implements interface but an interface extends another interface.

interface MyInterface

{

public void method1();

public void method2();

}

class XYZ implements MyInterface

{

public void method1()

{

System.out.println("implementation of method1");

}

Page 49: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

public void method2()

{

System.out.println("implementation of method2");

}

public static void main(String arg[])

{

MyInterface obj = new XYZ();

obj. method1();

}

}

Output:

implementation of method1

Applet Example

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

/*

<applet code="colordemo" height=300 width=300>

</applet>

*/

public class colordemo extends Applet implements ActionListener

{

Button bcolor1,bcolor2,bcolor3,bcolor4;

Label bcolor;

String str;

public void init()

{

bcolor = new Label("Select any of the following button to change the

background colour");

bcolor1 = new Button("Red");

bcolor2 = new Button("Blue");

bcolor3 = new Button("Yellow");

bcolor4 = new Button("Black");

add(bcolor1);

add(bcolor2);

add(bcolor3);

add(bcolor4);

bcolor1.addActionListener(this);

Page 50: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

bcolor2.addActionListener(this);

bcolor3.addActionListener(this);

bcolor4.addActionListener(this);

}

public void actionPerformed(ActionEvent ae)

{

str = ae.getActionCommand();

repaint();

}

public void paint(Graphics g)

{

if(str.equals("Red"))

setBackground(Color.red);

else if(str.equals("Blue"))

setBackground(Color.blue);

else if(str.equals("Yellow"))

setBackground(Color.yellow);

else if(str.equals("Black"))

setBackground(Color.black);

}

}

Page 51: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Displaying messages is of two ways in Applet. One way is displaying anywhere in the applet

window and the other way is displaying in the status bar with showStatus() method.

The bottom of the applet window is known as status bar. In a Browser or MS-Word, the

bottom panel is known as status bar where in the line number where the cursor exists, current

page number and total number of pages etc. are displayed.

Status bar comes at the bottom of the browser and is used by the browser to display the status

of the document opened. The applet can use this status bar to display strings (messages).

How to display in status bar?

To display the two ways, the Graphics class comes drawString() method and Applet class

comes with showStatus() method. Let us see what API says about these methods.

void drawString(String str, int x, int y): Draws the text given by the specified string, using

this graphics context‟s current font and color. The baseline of the leftmost character is at

position (x, y) in this graphics context‟s coordinate system.

void showStatus(String msg): Requests that the argument string be displayed in the "status

window". Many browsers and applet viewers provide such a window, where the application

can inform users of its current state.

/*<applet code="ShowStatusDemo.class" width="300" height="200">

</applet>*/

import java.applet.Applet;

import java.awt.Graphics;

public class ShowStatusDemo extends Applet

{

public void paint(Graphics g)

{

g.drawString("Hello World", 50, 75); // using drawString() to display in applet window

showStatus("Greetings"); // using showStatus() to display in status bar

}

}

Page 52: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Passing Parameters to Applets

import java.applet.*;

import java.awt.*;

/*

<APPLET CODE=”ParamDemo” width=”300” height=”100”>

<PARAM name=”Message” value=”SACHIN”>

</APPLET>

*/

public class ParamDemo extends Applet

{

public void paint(Graphics g)

{

String msg=this.getParameter(“Message”);

If(msg==null)

msg=”FRIENDS”;

msg=”WELCOME”+msg;

g.drawString(msg,50,25);

}

}

Fundamentals

The exception handling in java is one of the powerful mechanism to handle the runtime errors

so that normal flow of the application can be maintained.

In this page, we will learn about java exception, its type and the difference between checked

and unchecked exceptions.

What is exception

Dictionary Meaning: Exception is an abnormal condition.

In java, exception is an event that disrupts the normal flow of the program. It is an object

which is thrown at runtime.

What is exception handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO,

SQL, Remote etc.

Page 53: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.

Exception normally disrupts the normal flow of the application that is why we use exception

handling. Let's take a scenario:

statement 1;

statement 2;

statement 3;

statement 4;

statement 5;//exception occurs

statement 6;

statement 7;

statement 8;

statement 9;

statement 10;

Suppose there is 10 statements in your program and there occurs an exception at statement 5,

rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform

exception handling, rest of the statement will be executed. That is why we use exception

handling in java.

Hierarchy of Java Exception classes

Page 54: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

hierarchy of exception handling

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is considered

as unchecked exception. The sun microsystem says there are three types of exceptions:

Checked Exception

Unchecked Exception

Error

Difference between checked and unchecked exceptions

1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as

checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at

compile-time.

2) Unchecked Exception

Page 55: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

The classes that extend RuntimeException are known as unchecked exceptions e.g.

ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios where exceptions may occur

There are given some scenarios where unchecked exceptions can occur. They are as follows:

1) Scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException

2) Scenario where NullPointerException occurs

If we have null value in any variable, performing any operation by the variable occurs an

NullPointerException.

String s=null;

System.out.println(s.length());//NullPointerException

3) Scenario where NumberFormatException occurs

The wrong formatting of any value, may occur NumberFormatException. Suppose I have a

string variable that have characters, converting this variable into digit will occur

NumberFormatException.

String s="abc";

int i=Integer.parseInt(s);//NumberFormatException

4) Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result

ArrayIndexOutOfBoundsException as shown below:

int a[]=new int[5];

a[10]=50; //ArrayIndexOutOfBoundsException

Java Exception Handling Keywords

There are 5 keywords used in java exception handling.

Page 56: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

try

catch

finally

throw

throws

Java try-catch

Java try block

Java try block is used to enclose the code that might throw an exception. It must be used

within the method.

Java try block must be followed by either catch or finally block.

Syntax of java try-catch

try{

//code that may throw exception

}catch(Exception_class_Name ref){}

Syntax of try-finally block

try{

//code that may throw exception

}finally{}

Java catch block

Java catch block is used to handle the Exception. It must be used after the try block only.

You can use multiple catch block with a single try.

Problem without exception handling

Let's try to understand the problem if we don't use try-catch block.

public class Testtrycatch1{

public static void main(String args[]){

int data=50/0;//may throw exception

Page 57: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

System.out.println("rest of the code...");

}

}

Test it Now

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero

As displayed in the above example, rest of the code is not executed (in such case, rest of the

code... statement is not printed).

There can be 100 lines of code after exception. So all the code after exception will not be

executed.

Solution by exception handling

Let's see the solution of above problem by java try-catch block.

public class Testtrycatch2{

public static void main(String args[]){

try{

int data=50/0;

}catch(ArithmeticException e){System.out.println(e);}

System.out.println("rest of the code...");

}

}

Test it Now

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero

rest of the code...

Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...

statement is printed.

Internal working of java try-catch block

Page 58: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

The JVM firstly checks whether the exception is handled or not. If exception is not handled,

JVM provides a default exception handler that performs the following tasks:

Prints out exception description.

Prints the stack trace (Hierarchy of methods where the exception occurred).

Causes the program to terminate.

But if exception is handled by the application programmer, normal flow of the application is

maintained i.e. rest of the code is executed.

Java catch multiple exceptions

Java Multi catch block

If you have to perform different tasks at the occurrence of different Exceptions, use java

multi catch block.

Let's see a simple example of java multi-catch block.

public class TestMultipleCatchBlock{

public static void main(String args[]){

try{

int a[]=new int[5];

Page 59: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

a[5]=30/0;

}

catch(ArithmeticException e){System.out.println("task1 is completed");}

catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}

catch(Exception e){System.out.println("common task completed");}

System.out.println("rest of the code...");

}

}

Test it Now

Output:task1 completed

rest of the code...

Rule: At a time only one Exception is occured and at a time only one catch block is executed.

Rule: All catch blocks must be ordered from most specific to most general i.e. catch for

ArithmeticException must come before catch for Exception .

Java Nested try block

The try block within a try block is known as nested try block in java.

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire

block itself may cause another error. In such cases, exception handlers have to be nested.

Syntax:

....

try

{

statement 1;

statement 2;

try

{

statement 1;

statement 2;

}

catch(Exception e)

{

}

}

catch(Exception e)

Page 60: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

{

}

....

Java nested try example

Let's see a simple example of java nested try block.

class Excep6{

public static void main(String args[]){

try{

try{

System.out.println("going to divide");

int b =39/0;

}catch(ArithmeticException e){System.out.println(e);}

try{

int a[]=new int[5];

a[5]=4;

}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}

System.out.println("other statement);

}catch(Exception e){System.out.println("handeled");}

System.out.println("normal flow..");

}

}

Java finally block

Java finally block is a block that is used to execute important code such as closing

connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.

Page 61: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Case 2

Let's see the java finally example where exception occurs and not handled.

class TestFinallyBlock1{

public static void main(String args[]){

try{

int data=25/0;

System.out.println(data);

}

catch(NullPointerException e){System.out.println(e);}

finally{System.out.println("finally block is always executed");}

System.out.println("rest of the code...");

}

}

Test it Now

Output:finally block is always executed

Page 62: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Exception in thread main java.lang.ArithmeticException:/ by zero

Case 3

Let's see the java finally example where exception occurs and handled.

public class TestFinallyBlock2{

public static void main(String args[]){

try{

int data=25/0;

System.out.println(data);

}

catch(ArithmeticException e){System.out.println(e);}

finally{System.out.println("finally block is always executed");}

System.out.println("rest of the code...");

}

}

Test it Now

Output:Exception in thread main java.lang.ArithmeticException:/ by zero

finally block is always executed

rest of the code...

Rule: For each try block there can be zero or more catch blocks, but only one finally block.

Note: The finally block will not be executed if program exits(either by calling System.exit()

or by causing a fatal error that causes the process to abort).

Java throw keyword

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw keyword. The throw

keyword is mainly used to throw custom exception. We will see custom exceptions later.

The syntax of java throw keyword is given below.

throw exception;

Let's see the example of throw IOException.

throw new IOException("sorry device error);

java throw keyword example

Page 63: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

In this example, we have created the validate method that takes integer value as a parameter.

If the age is less than 18, we are throwing the ArithmeticException otherwise print a message

welcome to vote.

public class TestThrow1{

static void validate(int age){

if(age<18)

throw new ArithmeticException("not valid");

else

System.out.println("welcome to vote");

}

public static void main(String args[]){

validate(13);

System.out.println("rest of the code...");

}

}

Test it Now

Output:

Exception in thread main java.lang.ArithmeticException:not valid

Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the

programmer that there may occur an exception so it is better for the programmer to provide

the exception handling code so that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any

unchecked exception such as NullPointerException, it is programmers fault that he is not

performing check up before the code being used.

Syntax of java throws

return_type method_name() throws exception_class_name{

//method code

}

Which exception should be declared

Ans) checked exception only, because:

unchecked Exception: under your control so correct your code.

Page 64: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

error: beyond your control e.g. you are unable to do anything if there occurs

VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.

Java throws example

Let's see the example of java throws clause which describes that checked exceptions can be

propagated by throws keyword.

import java.io.IOException;

class Testthrows1{

void m()throws IOException{

throw new IOException("device error");//checked exception

}

void n()throws IOException{

m();

}

void p(){

try{

n();

}catch(Exception e){System.out.println("exception handled");}

}

public static void main(String args[]){

Testthrows1 obj=new Testthrows1();

obj.p();

System.out.println("normal flow...");

}

}

Test it Now

Output:

exception handled

normal flow...

Page 65: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Difference between throw and throws in Java

No. Throw throws

1) Java throw keyword is used to explicitly

throw an exception.

Java throws keyword is used

to declare an exception.

2) Checked exception cannot be propagated

using throw only.

Checked exception can be

propagated with throws.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the

method signature.

5) You cannot throw multiple exceptions. You can declare multiple

exceptions e.g.

public void method()throws

IOException,SQLException.

Difference between final, finally and finalize

There are many differences between final, finally and finalize. A list of differences between

final, finally and finalize are given below:

No. final finally finalize

1) Final is used to apply restrictions on class,

method and variable. Final class can't be

inherited, final method can't be overridden and

final variable value can't be changed.

Finally is used to place

important code, it will be

executed whether exception

is handled or not.

Finalize is used

to perform

clean up

processing just

before object is

garbage

collected.

2) Final is a keyword. Finally is a block. Finalize is a

method.

Java Built In Exceptions List

In addition to exceptions in java.lang, Java defines several more that relate to its other

standard packages.

Java Unchecked Exceptions

Page 66: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Java's Unchecked RuntimeException Subclasses defined in java.lang:

Exception Meaning

ArithmeticException Arithmetic error, such as divide-by-zero

ArrayIndexOutOfBoundsException Array index is out-of-bounds

ArrayStoreException Assignment to an array element of an incompatible type

ClassCastException Invalid cast

EnumConstantNotPresentException An attempt is made to use an undefined enumeration value

IllegalArgumentException Illegal argument used to invoke a method

IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread

IllegalStateException Environment or application is in incorrect state

IllegalThreadStateException Requested operation not compatible with current thread state

IndexOutOfBoundsException Some type of index is out-of-bounds

NegativeArraySizeException Array created with a negative size

NullPointerException Invalid use of a null reference

NumberFormatException Invalid conversion of a string to a numeric format

SecurityException Attempt to violate security

StringIndexOutOfBounds Attempt to index outside the bounds of a string

TypeNotPresentException Type not found

Page 67: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

UnsupportedOperationException An unsupported operation was encountered

Java Checked Exceptions

Java's Checked Exceptions Defined in java.lang:

Exception Meaning

ClassNotFoundException Class not found

CloneNotSupportedException Attempt to clone an object that doesn't implement

the Cloneable interface

IllegalAccessException Access to a class is denied

InstantiationException Attempt to create an object of an abstract class or interface

InterruptedException One thread has been interrupted by another thread

NoSuchFieldException A requested field does not exist

NoSuchMethodException A requested method doesn't exist

ReflectiveOperationException Superclass of reflection-related exceptions

Page 68: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Streams: Stream is basically a channel on which the data flow from sender to receiver.

An input object that reads the stream of data from a file is called input stream and output

object that writes the stream of data to a file is called output stream.

Byte Stream

Input Stream Hierarchy The input stream classes is not a single class but a bunch of classes doing the same job of opening the file in read mode, but they cater to different needs of the programmer. All the classes exist in java.io package and following hierarchy gives the list of classes.

Page 69: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

As you can observe, the hierarchy contains 12 input stream classes. All the classes can be divided into two categories – high-level streams and low-level streams. All the subclasses of FilterInputStream are known as high-level streams (there exists 4) and all the remaining are known as low-level streams (there are 8). One stream can be linked to another to have higher functionality, but subject to some rules explained later. OutputStream Hierarchy Similar to input stream hierarchy, there exists output stream hierarchy also dealing with all output stream classes.

Byte Stream: i)The byte Stream is used for inputting and outputting the bytes.

ii)There are two super classes used in byte stream and are :InputStream and OutputStream.

iii)A byte is 8 bit number type can represent values from -127 to 127.

iv)It never supports Unicode characters.

Reading Console Input:

BufferedReader object_name=new BufferedReader(new InputStreamReader(System.in));

Reading Character:

import java.io.*;

class Readchar

{

public static void main(String args[]) throws IOException{

Page 70: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

BufferredReader obj=new BufferedReader(new InputStreamReader(System.in));

int count=0;

char ch;

System.out.println(“\n Enter five characters”);

while(count<5)

{

ch=(char)obj.read();

System.out.println(ch);

Count++;

}

}

Reading Strings

import java.io.*;

class ReadString

{

public static void main(String args[]) throws IOException{

BufferredReader obj=new BufferedReader(new InputStreamReader(System.in));

String s;

S=obj.readLine();

While(Is.equals(“end”)

{

System.out.println(s);

s=obj.readLine();

}

}

}

Writing console output

Java PrintWriter Example

Let's see the simple example of writing the data on a console and in a text file testout.txt

using Java PrintWriter class.

package com.javatpoint;

import java.io.File;

import java.io.PrintWriter;

public class PrintWriterExample {

public static void main(String[] args) throws Exception {

Page 71: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

//Data to write on Console using PrintWriter

PrintWriter writer = new PrintWriter(System.out);

writer.write("Javatpoint provides tutorials of all technology.");

writer.flush();

writer.close();

//Data to write in File using PrintWriter

PrintWriter writer1 =null;

writer1 = new PrintWriter(new File("D:\\testout.txt"));

writer1.write("Like Java, Spring, Hibernate, Android, PHP etc.");

writer1.flush();

writer1.close();

}

}

Java FileInputStream Class

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented

data (streams of raw bytes) such as image data, audio, video etc. You can also read character-

stream data. But, for reading streams of characters, it is recommended to use FileReader

class.

Java FileInputStream class declaration

Let's see the declaration for java.io.FileInputStream class:

public class FileInputStream extends InputStream

Java FileInputStream example 1: read single character

import java.io.FileInputStream;

public class DataStreamExample {

public static void main(String args[]){

try{

FileInputStream fin=new FileInputStream("D:\\testout.txt");

int i=fin.read();

System.out.print((char)i);

fin.close();

}catch(Exception e){System.out.println(e);}

}

}

Note: Before running the code, a text file named as "testout.txt" is required to be created. In

this file, we are having following content:

Page 72: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

Welcome to javatpoint.

After executing the above program, you will get a single character from the file which is 87

(in byte form). To see the text, you need to convert it into character.

Output:

W

Java BufferedOutputStream Class

Java BufferedOutputStream class is used for buffering an output stream. It internally uses

buffer to store data. It adds more efficiency than to write data directly into a stream. So, it

makes the performance fast.

For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the

syntax for adding the buffer in an OutputStream:

OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO

Package\\testout.txt"));

Java BufferedOutputStream class declaration

Let's see the declaration for Java.io.BufferedOutputStream class:

public class BufferedOutputStream extends FilterOutputStream

Example of BufferedOutputStream class:

In this example, we are writing the textual information in the BufferedOutputStream object

which is connected to the FileOutputStream object. The flush() flushes the data of one stream

and send it into another. It is required if you have connected the one stream with another.

package com.javatpoint;

import java.io.*;

public class BufferedOutputStreamExample{

public static void main(String args[])throws Exception{

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");

BufferedOutputStream bout=new BufferedOutputStream(fout);

String s="Welcome to javaTpoint.";

byte b[]=s.getBytes();

bout.write(b);

bout.flush();

bout.close();

Page 73: Constructors: The constructor is a specialised method used ... · PDF fileJava Garbage Collection In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming

fout.close();

System.out.println("success");

}

}

Output:

Success

testout.txt

Welcome to javaTpoint.

Console I/O using Scanner Class

Step 1.

import java.util.Scanner;

Step 2.

Scanner scanner=new Scanner(System.in);

Step 3.

System.out.println(“Enter Something”);

Step4.

String input=scanner.nextLine();

Step5.

System.out.println(“you have Enterted”+input);