0% found this document useful (0 votes)
3 views52 pages

Java Notes 2

The document provides an in-depth overview of constructors in Java, detailing their purpose, types, and rules for usage, including examples of default and parameterized constructors. It also covers the use of the 'super' and 'this' keywords, their functionalities, and the distinction between constructor calls and keyword references. Additionally, the document discusses interfaces in Java, their declaration, advantages, and the implementation of default and static methods, along with examples of multiple inheritance through interfaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views52 pages

Java Notes 2

The document provides an in-depth overview of constructors in Java, detailing their purpose, types, and rules for usage, including examples of default and parameterized constructors. It also covers the use of the 'super' and 'this' keywords, their functionalities, and the distinction between constructor calls and keyword references. Additionally, the document discusses interfaces in Java, their declaration, advantages, and the implementation of default and static methods, along with examples of multiple inheritance through interfaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Constructors:

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created.
At the time of calling constructor, memory for the object is allocated in the memory. It is a special type of method
which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
once we creates an object compulsory we should perform initialization then only the object is in a position to respond
properly.
whenever we are creating an object some peace of the code will be executed automatically to perform initialization of
the object this piece of the code is nothing but constructor. Hence the main purpose of constructor is to perform
initialization of an object.
Example:
class Student{
String name;
int rollno;

public Student(String name, int rollno){


this.name = name;
this.rollno = rollno;
}

public static void main(String[] args){


Strudent s1 = new Student("Test123", 20);
Strudent s2 = new Student("xyz456", 30);
}
}

Rules of writing constructors:

 Name of the class and name of the constructor must be matched.


 Return type concept is not applicable for constructor even void also.
By mistake if we are trying to declare return type for the constructor then we won't get any compile-time error because
compiler treats it as a method.

Example:

class Test{
void Test(){
System.out.println("It is method but not constructor");
}

public static void main(String[] args){


Test t = new Test();
t.Test();
}
}

output :
It is method but not constructor
hence it is legal (but stupid) to have a method whose name is exactly same as class name.

The only applicable modifiers for constructors are public, private, protected, default if we are trying to use any other
modifier we will get compile time error.
1
class Test{
static Test(){} //CE: Modifier static not allowed hear.
}

Compiler is responsible to generate default constructor but not JVM


if we are not writing any constructor then only compiler will generate default constructor i.e. if we are writing at least one
constructor compiler won't generate default constructor hence every class in java can contain constructor it may be default
constructor generated by compiler or customized constructor explicitly provided by compiler but not both simultaneously.

Prototype of default constructor:

It is always no-arg constructor


The access modifier of default constructor is exactly same as access modifier of class (this rule is applicable only for
public and default)
It contains only one line super();

Programmers code Compiler generated code

class Test{ class Test{


} Test(){
super();
}
}
public class Test{ public class Test{
void Test(){ public Test(){
} super();
} }
void Test(){ }
}

The first line inside every constructor should be either super or this. And if we are not writing any thing then compiler
will always place super().

We can use super() or this() only in first line of constructor. If we are trying to take anywhere else we will get compile
time error

Example:

class Test{
Test(){
System.out.println("constructor");
super();//CE : call to super must be first statement in constructor
}
}
Within the constructor we can take either super or this but not both symuleniously
Example:

class Test{
Test(){
super();
this(); // CE : call to this must be first statement in constructor
}
}
2
We can use super() or this() only inside constructor if we are trying to use outside of constructor we will get compile
time error

Example:

class Test{
public void m1(){
super();//CE : call to super must be first statement in constructor
Sopln("Hello");
}
}
i.e we can call a constructor directly from another constructor only

Super Keyword:

The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super
reference variable.

Usages of super Keyword:


super can be used to refer immediate parent class instance variable.

Example:

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
}

super can be used to invoke immediate parent class method.

Example:

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");
}
3
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}
}

super() can be used to invoke immediate parent class constructor.

Example:

class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}
}

this keyword:

There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the current object.

Usages of this keyword:

this can be used to refer current class instance variable.

Example:

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);
4
}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}

this can be used to invoke current class method (implicitly).

Example:

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();
}
}

this() can be used to invoke current class constructor.

Example:

class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
this can be passed as an argument in the method call.

5
Example:

class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}

this can be passed as argument in the constructor call.

Example:

class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}

class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}

this can be used to return the current class instance from the method.

Syntax:

return_type method_name(){
return this;
}

Example:

class A{
A getA(){

6
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}

Difference between super(),this() methods and super, this keywords:

Super(), this() Super, this

These are constructor calls to call super class and These are keywords to referrer super class and
current class constructors current class instance members

we can use only in constructors area as first line. we can use anywhere except static.

we can use only once in constructor we can use any number of times.

Types of Constructors:

There are two types of constructors in Java:

Default constructor (no-arg constructor)


Parameterized constructor

Default Constructor:

A constructor is called "Default Constructor" when it doesn't have any parameter.


Syntax of default constructor:
<class_name>()
{
}

Example:

class Bike1{
//creating a default constructor
Bike1(){
System.out.println("Bike is created");
}
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Example-1:
7
//which displays the default values

class Student3{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}

Parameterized Constructors:

A constructor which has a specific number of parameters is called a parameterized constructor.


The parameterized constructor is used to provide different values to distinct objects. However, you can provide the
same values also.

Example:

class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Overloaded constructors:

8
Within a class we can declare multiple constructors and all these constructors having same name but different type of
arguments. Hence all these constructors are considered as overloaded constructors. Hence overloading concept applicable
for constructors.

Example:

class Test{
Test(){
Test(10);
sopln("noarg");
}
Test(int i){
Test(10.5);
sopln("int args");
}
Test(double d){
sopln("double args");
}

public static void main(String[] args){


Test t1 = new Test();
Test t2 = new Test(10);
Test t3 = new Test(10.5);
Test t1 = new Test(10l);
}
}

output :

double args
int args
no args

double args
int args

double args

double args

For constructors inheritance and overridding concepts are not applicable but overloading concept is applicable
Every class in java including abstract class can contains constructor but interface doesn't contain constructor.

Example:

class Test{
Test(){
//valid
}
}
9
abstract class Test{
Test(){
//valid
}
}

interface Test{
Test(){
//invalid
}
}

Recursive method call is a runtime exception saying stackOverFlowError but in our program if there is a chance of
recursive constructor invocation then the code won't compile and we will get compile time error.

Example:

class Test{

public static void m1(){


m2();
}
public static void m2(){
m1();
}
public static void main(String[] arg){
m1();

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

output :

CE :StackOverflowError
Example-1:

class Test{

Test(){
this(10);
}
Test(int i){
this();
}
public static void main(String[] arg){

System.out.println("Hello");
}
}
output:
10
Exception : Recursive constructor invocation.

Interface:
An interface in Java is a blueprint of a class. 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.

Advantages of Interface:

There are mainly three reasons to use interface. They are given below.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.

Declaring of Interface:

An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface
are declared with the empty body, and all the fields are public, static and final by default. A class that implements an
interface must implement all the methods declared in the interface.

Syntax:

interface interface_name{

// declare constant fields


// declare methods that abstract
// by default.
}

Interface fields are public, static and final by default, and the methods are public and abstract.

The relationship between classes and interfaces:


11
Interface Example:

package Inter;

public interface Mobile {

void calling();
void camera();
void audio();
void internet();

default void video(){


msg();
System.out.println("video");
}

static void msg(){

System.out.println("msg");
}
}

package Inter ;

public class Apple implements Mobile{

public void calling() {

System.out.println("Apple Calling");
}

public void camera() {

System.out.println("Apple Camera");
}

12
public void audio() {

System.out.println("Apple Audio");
}

public void internet() {

System.out.println("Apple Internet");
}
}

package Inter;

public class Realme implements Mobile {

public void calling() {

System.out.println("Realme Calling");
}

public void camera() {

System.out.println("Realme Camera");
}

public void audio() {

System.out.println("Realme Audio");
}

public void internet() {

System.out.println("Realme Internet");
}

public void video(){


System.out.println("realme video code");
}

package Inter;

public class user {

13
public static void main(String[] args) {

Mobile r=new Realme();


r.audio();
r.calling();
r.camera();
r.internet();
r.video();
Mobile.msg();

Mobile a=new Apple();


a.audio();
a.calling();
a.camera();
a.internet();
a.video();
Mobile.msg();
}
}

Before Java 8, interfaces could have only abstract methods. The implementation of these methods has to be provided
in a separate class. So, if a new method is to be added in an interface, then its implementation code has to be provided
in the class implementing the same interface. To overcome this issue, Java 8 has introduced the concept of default and
static methods which allow the interfaces to have methods with implementation without affecting the classes that
implement the interface.
The interfaces can have static methods as well which is similar to static method of classes.

Example: (Default)

interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}
}

Example: (Static)

interface Drawable{
void draw();
static int cube(int x)
{
return x*x*x;
}
}
14
class Rectangle implements Drawable{
public void draw()
{
System.out.println("drawing rectangle");
}
}

class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}
}

Multiple Inheritance By Interfaces:

interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}

An interface can have private methods since Java 9 version. These methods are visible only inside the class/interface,
so it's recommended to use private methods for confidential code. That's the reason behind the addition of
private methods in interfaces.

Syntax:

private void methodName()


{
//statements;
}

Example:

interface Operation {
default void addition() {
System.out.println("default method addition");
}
default void multiply() {
15
division();
System.out.println("default method multiply");
}
private void division() { // private method
System.out.println("private method division");
}
}

class PrivateMethodTest implements Operation {


public static void main(String args[]) {
PrivateMethodTest test = new PrivateMethodTest();
test.multiply();
}
}

Nested Interface in Java:

An interface, i.e., declared within another interface or class, is known as a nested interface. The nested interfaces are used
to group related interfaces so that they can be easy to maintain. The nested interface must be referred to by the outer
interface or class. It can't be accessed directly.
The nested interface must be public if it is declared inside the interface, but it can have any access modifier if declared
within the class.
Nested interfaces are declared static.

Syntax of nested interface which is declared within the interface:

interface interface_name{

interface nested_interface_name{
//statements;}
}

package Inter;
public interface NestedInterface {

interface Nest{

public void m1();


}
}

package Inter;

public class Ns implements NestedInterface.Nest{

public static void main(String[] args) {


NestedInterface.Nest n=new Ns();
n.m1();

}
public void m1() {
System.out.println("hi");
16
}
}

Syntax of nested interface which is declared within the class:

class class_name{
interface nested_interface_name{
//statements;
}
}

Example:

class A{
interface Message{
void msg();
}
}

class TestNestedInterface2 implements A.Message{


public void msg(){System.out.println("Hello nested interface");}

public static void main(String args[]){


A.Message message=new TestNestedInterface2();//upcasting here
message.msg();
}
}

Difference Between Interface and Abstract Class:

Abstract class Interface


Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8, it
abstract methods. can have default and static methods also.
Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.

Abstract class can have final, non-final, static and non-


static variables. Interface has only static and final variables.

Abstract class can provide the implementation of Interface can't provide the implementation of abstract
interface. class.
The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.

An abstract class can extend another Java class and An interface can extend another Java interface only.
implement multiple Java interfaces.

17
An abstract class can be extended using keyword An interface can be implemented using keyword
"extends". "implements".
A Java abstract class can have class members like private, Members of a Java interface are public by default.
protected, etc.
Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Exception Handling:

Exception:

An unexpected unwanted event that disturbs normal flow of the program is called exception.

Example: FileNotFoundException..etc

Purpose:

It is highly recommended to handle exceptions and the main objective of exception handling is graceful
termination of the program.

Exception Handling:

Exception handling doesn't mean repairing an exception we have to provide alternative way to continue rest
of the program normally, is the concept of exception handling.
For example our program requirement is to read data from remote file locating at London at runtime if
London file is not available our program should not be terminated abnormally we have to provide some local
file to continue rest of the program normally this way of defining alternative is nothing but exception handling.

Example:

try{
read data from remote file
locating at London
}
catch(FileNotFoundException e)
{
use local file and continue rest of the program normally
}

Runtime stack mechanism:

For every thread JVM will create runtime stack each and every method call performed by that thread will be
stored in the corresponding stack.
Each entry in the stack is called stack frame or activation record.
After completing every method call the corresponding entry from the stack will be removed.
18
After completing all method calls the stack will become empty and that empty stack will be destroyed by
JVM just before terminating the thread.

Example:

class Test
{
public static void main(String[] args)
{
doStuff();
}

public static void doStuff()


{
domoreStuff();
}
public static void domoreStuff()
{
S.o.pln("hi");
}

Default Exception in java:

Inside a method if any exception occurs the method in which it is raised is responsible to create exception
object by including the following information.

1. Name of exception
2. Description of exception
3. Location at which exception occurs(stack trace)

After creating exception object method handovers that object to the JVM.
JVM will check whether the method contains any exception handling code or not. If the method doesn't
contain exception handling code then JVM terminate that method abnormally and removes corresponding entry
from the stack.
Then JVM identifies caller method and checks weather caller method contains any handling code or not, if
the caller method doesn't contain handling code then JVM terminate also abnormally and removes
corresponding entry from the stack. This process will be continue d until main method and if the main method
also doesn't contain handling code then JVM terminate main method also abnormally and removes
corresponding entry from the stack.
Then JVM handovers responsibility of exception handling to default exception handler, which is the part of
JVM.
Default exception handler prints exception information in the following format and terminates program
abnormally.

Format:
Exception in thread "any method" Name of Exception: Description stack trace
19
Example:

class Test
{
public static void main(String []args)
{
doStuff();
}
public static void doStuff()
{
domoreStuff();
}
public static void domoreStuff()
{
System.out.println(10/0);
}
}

o/p: Exception in thread "main" java.lang.ArthimeticException: devide by zero Exception


at Test.domoreStuff()
at Test.doStuff()
at Test.main()

Note: In a program if at least one method terminates abnormally then the program termination is obnormal
termination.

If all methods terminated normally then only program termination is normal termination.

Exception Hierarchy:

Throwable class acts as root for java exception hierarchy


Throwable class defines two child class

1. Exception
2. Error

Exception:

Most of the times exceptions are caused by our program and these are recoverable.
for example our program requirement is to read data from remote file locating at London at runtime if remote
file is not available then we will get runtime exception saying file not found exception. If file not found
exception occurs we can provide local file and continue rest of the program normally.

Example:

try{
read data from remote file
20
locating at london
}
catch(FileNotFoundException e)
{
use local file and continue rest of the program normally
}

Error:

Most of the times errors are not caused by our program and these are due to lack of system resources.
Errors are non-recoverable.
For example if OutOfMemoryError occurs being a programmer we cannot do anything the program will be
terminated abnormally. System admin or server admin is responsible to increase heap memory.

Throwable

Exceptions Errors

RuntimeException IOException InterruptedException SQLException

ArithmeticException EOFException
NullPointerException FileNotFoundException
ClassCasteException
IndexOutOfBoundsException

ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException

VirtualMachineError LinkageError AssertionError ExceptionInInitializerError

StackOverFlowError VerifyError
OutOfMemoryError

Checked vs Unchecked Exception:

Checked:

The exceptions which are checked by compiler for smooth execution of the program are called checked
exceptions.
21
Example:
FileNotFoundException.

In our program if there is a chance of raising checked exception then compulsory we should handle that
checked exception(either by try catch or by throws keyword) otherwise we will get compile time error.

import java.io.*;
class Test{
p s v main(String []args){
PrintWriter pw=new PrintWtriter("abc.txt");
pw.println("hello");

}
}

Unchecked:
The exceptions which are not checked by compiler weather programmer handling or not such type of
exceptions are called unchecked exceptions.

Example:
ArithmeticException

import java.io.*;
class Test{
p s v main(String []args){
PrintWriter pw=new PrintWtriter("abc.txt");
pw.println("hello");
S.o.pln(10/0);
}
}

Note:
Weather it is checked or unchecked every exception occurs at runtime only. There is no chance of occuring
any exception at compile time.
Runtime exception and its child classes, error and its child classes are unchecked. Except these remaining are
checked.

Fully checked vs partially checked:

 A checked exception is said to be fully checked if and only if all its child classes also checked.

Example:

IOException
InterruptedException

A checked exception is said to be partially checked if and only if some of its child classes are unchecked.
22
Example:

Throwable
Exception

Note: The only possible partially checked exceptions in java are Exception, Throwable.

Customized Exception handling by using try, catch:

It is highly recommended to handle exceptions


The code which may raise an exception is called risky code and we have to define that code inside try block
and corresponding handling code we have to define inside catch block

Syntax:

try
{
risky code
}
catch(Exception e)
{
handling code
}

Without try-catch:

class Test
{
p s v main(String []args)
{
s.o.pln("statement1");
s.o.pln(10/0);
s.o.pln("statement2");
}
}
o/p: statement1
RuntimeException: ArithmeticException:/ by zero

With try-catch:

class Test
{
p s v main(String []args)
{
s.o.pln("statement1");
try
{
23
s.o.pln(10/0);
}
catch(Exception e)
{
s.o.pln(10/2);
}
s.o.pln("statement2");
}
}

o/p: statement1
5
statement2

Control flow in try-catch:

try
{
statement1;
statement2;
statement3;
}
catch(Exception e)
{
statement4;
}
statement5;

case-1:
If there is no exception--1,2,3,5 normal termination.

case-2:
If an exception raised at statement2 and corresponding catch block matched--1,4,5 normal termination.

case-3:
If an exception raised at statement2 and corresponding catch block not matched--1, abnormal termination

case-4:
If an exception raised at statement4 or statement5 then it is always abnormal termination

Note:

Within the try block if any where an exception raised then rest of the try block won't be executed even though
we handled that exception hence within the try block we have to take only risky code and length of try block
should be as less as possible.
In addition to try block there may be a chance of raising an exception inside catch and finally blocks.
If any statement which is not part of try block and raises an exception then it is always abnormal termination.

24
Methods to print Exception information:

Throwable class defines the following methods to print exception information

printStackTrace():
Name of exception: description and stack trace

toString():
Name of exception: description

getMessage():
Description
Example:

class Test
{
public static void main(String []args)
{
try
{
s.o.pln(10/0);
}
catch(ArithmeticException e)
{
e.printStackTrace();
S.o.pln(e);orS.o.pln(e.toString());
s.o.pln(e.getMessage());
}
}
}

try with multiple catch blocks:

The way of handling an exception is varied form exception to exception

hence for exception type it is highly recommended to take separate catch block that is try with multiple catch
blocks is always possible and recommended to use.

try{
//risky code
}
catch(Exception e){

//any kind of exception


}

try{
//risky code
}
25
catch(ArithmeticException e){

//perform alternative arithmetic operations


}

catch(SQLException e){

//use Mysql db instead of oracle db


}
catch(FileNotFoundException e){

//use local file instead of remote file


}
catch(Exception e){

//default exception-handling
}

If try with multiple catch blocks present then the order of catch block is very important. We have to take
child first and then parent otherwise we will get compile time error saying Exception xxx has already been
caught.

Example:

try{
risky code
}
catch(Exception e)
{

}
catch(ArithmeticException e)
{

Example:

try{
risky code
}
catch(ArithmeticException e)
{

}
catch(Exception e)
{

}
26
We can't declare to catch block for the same exception otherwise we will get compile time error saying
Exception xxx has already been caught..

try{
risky code
}
catch(ArithmeticException e)
{

}
catch(ArithmeticException e)
{

}
Difference between final, finally and finalize():

final:

final is the modifier applicable for classes, methods and variables.


If a class declared as final we can't extend that class that is we can't create child class for that class that is
inheritance is not possible for final classes.
If a method is final then we can't override that method in the child class
If a variable declared as final then we can't perform reassignment for that variable

finally:

finally is a block always associated with try catch to maintain cleanup code.

try{
risky code
}
catch(Exception e){
handling code
}
finally{
cleanup code
}

The specialty of finally block is it will be executed always irrespective of weather exception is raised or not
raised and weather handled or not handled.

finalize():

finalize is a method always invoked by garbage collector just before destroying an object to perform cleanup
activities.

Note:

27
finally block is responsible to perform cleanup activities related to try block that is whatever resources we
opened as the part of try block will be closed inside finally block.
where as finalize method is responsible to perform cleanup activities related to object that is whatever
resources associated with the object will be deallocated before destroying an object by using finalize method.

Various possible combinations of try, catch and finally:

In try-catch-finally order is important.


whenever we are writing try compulsory we should write either catch or finally otherwise we will get
compile time error that is try without catch or finally is invalid.
whenever we are writing catch block compulsory try block must be required that is catch without try is
invalid.
whenever we are writing finally block compulsory try block must be required that is finally without try is
invalid.
Inside try-catch-finally block we can declare try, catch and finally blocks that is nesting of try catch finally is
allowed.
for try-catch-finally blocks curly braces are mandatory.
throw keyword:

Sometimes we can create exception objects explicitly and we can handover to the JVM manually for this we
have to use throw keyword

Example:

throw new ArithmeticException("/ by zero");

Hence the main objective of throw keyword is to handover our created exception object to the JVM
manually.

hence the result of following two programs exactly same

Example:

class Test
{
p s v main(String[] ags)
{
s.o.pln(10/0);
}
}

In this case main method is responsible to create exception object and handover to the JVM

class Test
{
p s v main(String[] ags)
{
throw new ArithmeticException("/ by zero");
28
}
}

In this case programmer creating exception object explicitly and handover to the JVM manually

Note:
Best use of throw keyword is for user defined exceptions or customized exceptions.

case-1:

throw e;

If e refers null then we will get null pointer exception

class Test{
static ArithmeticException e=new ArithmeticException();

p s v main(String []args)
{
throw e;
}
}ArithmeticException
/////
class Test{
static ArithmeticException e;
p s v main(String []args)
{
throw e;
}
}NullPointerException

case-2:
After throw statement we are not allowed to write any statement directly otherwise we will get compile time
error saying unreachable statement.

Example:

class Test
{
p s v main(String[] ags)
{
s.o.pln(10/0);
s.o.pln("hello");
}
}--->R.E:A.E:/ by zero

class Test
{
29
p s v main(String[] ags)
{
throw new ArithmeticException("/ by zero");
s.o.pln("hello");
}
}unreachable code

case-3:
We can use throw keyword only for throwable types if we are trying to use for normal java objects we will
get comiple time error saying incompatible types.

class Test
{
p s v main(String[] ags)
{
throw new Test();
}
}

class Test extends RuntimeException


{
p s v main(String[] ags)
{
throw new Test();
}
}

throws:

In our program if there is a possibility of raising checked exception then compulsory we should handle that
checked exception otherwise we will get compile time error saying "unreported exception xxx; must be caught
or declared to be thrown"

Example 1:

import java.io.*;
class Test
{
public static void main(String []args)
{
PrintWriter pw=new PrintWriter("abc.txt");
pw.println("hellio");
}
}

Example-2:

30
class Test
{
public static void main(String []args)
{
Thread.sleep("10000");
}
}

o/p: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown

We can handle this compile time error by using the following two ways

way-1:
By using try-catch

class Test
{
public static void main(String []args)
{
try{
Thread.sleep("10000");
}
catch(InterruptedException e)
{

}
}
}

way-2:
By using throws keyword
We can use throws keyword to delegate responsibilty of exception handling to the caller then caller(it may be
another method or JVM) then caller method is responsible to handle that exception.

public class Exception1 {

public static void main(String []args) throws InterruptedException


{
Thread.sleep("10000");
}

throws keyword required only for checked exceptions and usage of throws keyword for unchecked
exceptions there is no use or there is no impact.
throws keyword requires only to convience and usage of throws keyword doesn't prevent abnormal
termination of the program.

31
Example:

class Test
{
public static void main(String []aregs) throws InterruptedException
{
doStuff();
}
public static void doStuff() throws InterruptedException
{
domoreStuff();
}
public static void domoreStuff() throws InterruptedException
{
Thread.sleep(10000);
}
}

In the above program if we remove at least one throws statement then the code won't compile.

case-1:
We can use throws keyword for methods and constructors but not for classes.

class Test throws Exception


{
Test() throws Exception
{
}
public void m1() throws Exception
{

}
}

case-2:
We can use throws keyword only for throwable types. If we are trying to use for normal java classes then we
will get compile time error saying "incompatible types"

class Test
{
public void m1() throws Test
{
}
}

///
class Test extends RuntimeException
{
public void m1() throws Test
32
{
}
}

case-3:

Example:

class Test
{
p s v main(String[] args)
{
throw new Exception();
}
}

o/p: unreported exception java.lang.Exception; must be caught or declared to be thrown

class Test
{
p s v main(String[] args)
{
throw new Error();
}
}

o/p:Exception in thread "main" java.lang.Error at Test.main()

case-4:

Within the try block if there is no chance of raising an exception then we can't write catch block for that
exception otherwise we will get compile time error saying "Exception xxx is never thrown in body of
corresponding try statement"
But this rule is applicable only for fully-checked exceptions.

class Test
{
public static void main(String []args)
{
try
{
s.o.pln("Hello");
}
catch(ArithmeticException e)
{
}
33
}
}--->o/p Hello
///

class Test
{
public static void main(String []args)
{
try
{
s.o.pln("Hello");
}
catch(Exception e)
{
}
}
}--->o/p Hello
//////
class Test
{
public static void main(String []args)
{
try
{
s.o.pln("Hello");
}
catch(IOException e)
{
}
}
}--->o/p Exception j.l.IOE is never thrown in body of corresponding try statement

///class Test
{
public static void main(String []args)
{
try
{
s.o.pln("Hello");
}
catch(InterruptedException e)
{
}
}
}--->o/p Exception j.l.IE is never thrown in body of corresponding try statement

///class Test
{
public static void main(String []args)
34
{
try
{
s.o.pln("Hello");
}
catch(Error e)
{
}
}
}--->o/p Hello

Various possible compile time errors in exception handling:

unreported exception xxx; must be caught or declared to be thrown


Exception xxx has already been caught
Exception xxx is never thrown in body of corresponding try statement
unreachable statement
Incompatible types
found:classname
required:j.l.Throwable
try without catch or finally
catch without try
finally without try
Customized or user defined exceptions:

Sometimes to meet program requirements we can define our own exceptions such type of exceptions are
called customized or user defined exceptions.

Example:

TooYoungException
TooOldException
InSufficientException

Example:

class TooYoungException extends RuntimeException


{
TooYoungException(String s)
{
super(s);//to make description available to default exception handler
}

class TooOldException extends RuntimeException


{
TooOldException(String s)
{
super(s);
35
}

class CustException
{
public static void main(String []args)
{
int age=Integer.parseInt(args[0]);
if(age>60)
{
throw new TooYoungException("plz wait some more time ..you will get best match soon");
}
else if()
{
throw new TooOldException("your age is already crossed marriage age.. no chance of getting marriage");
}
else
{
System.out.println("you will get match details soon by email..!");
}
}
}

Note:
throw keyword is best suitable for user defined or customized exceptions but not for pre-defined exceptions.
It is highly recommended to define customized exceptions as unchecked i.e., we have to extends runtime
exceptions but not exception.

Top 10 Exceptions:

-->Based on the person who is raising an exception all exceptions are devided into two types
1)JVM Exceptions
2)programatic Exceptions
1) JVM Exceptions:
-->The exceptions which are raised automatically by JVM when ever a particular event occurs are called JVM
Exceptions.

Example:
ArithmeticException
NullPointerException..etc...

2)Programatic Exceptions:
-->The exceptions which are raised explicitly either by programmer or by API developer to indicate that
something goes wrong are called programatic Exceptions.

Example:

TooOldException
IlleagalArgumentException..etc...

36
Top-10 Exceptions:

ArrayIndexOutofBoundsException:

It is the child class of RuntimeException and hence it is unchecked.


Raised automatically by JVM whenever we are trying to access Array element with out of range index.

Example:

int[] a=new int[4];


s.o.pln(x[0]);
s.o.pln(x[6]);

NullPointerException:

t is the child class of RuntimeException and hence it is unchecked.


Raised automatically by JVM whenever we are trying to perform any operation on null.

Example:

String s=null;
S.o.pln(s.length);

ClassCasteException:

It is the child class of RuntimeException and hence it is unchecked.


Raised automatically by JVM whenever we are trying to typecaste Parent object to child type.
Examples:

String s =new String("anil");


Object o=(Object)s;-->valid

Object o=new Object();


String s=(String)o;-->Exception

Object o=new String("anil");


String s=(String)o;

StackOverFlowError:

It is the child class of error and hence it is unchecked.


Raised automatically by JVM whenever we are trying to perform recursive method call

Example:

class Test{
p s v m1()
{
m2();
37
}
p s v m2()
{
m1();
}
p s v main(String[] args)
{
m1();
}
}

NoClassDefFoundError:

It is the child class of error and hence it is unchecked.


Raised automatically by JVM whenever JVM unable to find required ".class" file.

>>java Test

If Test.class file is not avaible then we will get runtime exception saying NoClassDefFoundError:Test

ExceptionInInitializerError:

It is the child class of error and hence it is unchecked.


Raised automatically by JVM if any exception occurs while executing static variable assignments and static
blocks.
Example-1:

class Test
{
static int x=10/0;
}

Example-2:

class Test
{
static{
String s=null;
s.o.pln(s.length());
}
}

IlleagalArgumentException:

It is the child class of RuntimeException and hence it is unchecked.


Raised explicitly either by programmer or by API developer to indicate that a method has been invoked with
illegal argument.

38
Example:

The valid range of thread priorities is 1 to 10 if we are trying to set the priority with any other value then we
will get runtime exception saying IllegalArgumentException

Thread t=new Thread();


t.setPriority(7);
t.setPriority(17);

NumberFormatException:

It is the direct child class of IllegalArgumentException which is the child class of RuntimeException and
hence it is unchecked.
Raised explicitly either by programmer or API developer to indicate that we are trying to convert string to
number and the string is not properly formatted.

Example:

int i=Integer.parseInt("10");-->valid
int i=Integer.parseInt("ten");

IllegalStateException:

It is the child class of runtime exception and hence it is unchecked.


Raised explicitly either by programmer or API developer to indicate that a method hasbeen invoked at wrong
time.

Example:
After starting of a thread we are not allowed to restart the same thread once again otherwie we will get
runtime exception saying IllegalThreadStateException.

Thread t=new Thread();


t.start();
t.start();
AssersionError:

It is the child class of error and hence it is unchecked.


Raised explicitly either by programmer or API developer to indicate that assert statement fails

Example:

assert(x>10);

If x is not greater than 10 then we will get runtime exception saying assertion error.

1.7 Enhancements Related to Exceptions:

As the part of 1.7 version in exception handling the following two concepts introduced
39
1)try with resources
2)multi catch block

try with resources:

until 1.6 version it is highly recommended to write finally block to close resources which are open as the part
of try block

Example:

BufferReader br=null;
try
{
br=new BufferReader(new FileReader("input.txt));
//use br based on our requirement
}
catch(IOException e)
{
//Handling code
}
finally
{
if(br != null){
br.close();
}
}

 The problems in this approach are compulsory programmer is require to close resources inside finally block
it increases complexity of programming
we have to write compulsory and hence it increases length of the code and reduces readability.
To overcome above problems sun people introduced try with resources in 1.7 version
The main advantage of try with resources is whatever resources open as the part of try block will be closed
automatically once control reaches end of try block either normally or abnormally and hence we are not close
explicitly so that complexity of programming will be reduced.
we are not require to write finally block so that length of the code will be reduced and readability will be
improved.

try(BR br=new BR(new FR("input.txt")))


{
//br based on our requirement
}
catch(IOException e)
{
//handling code
}

conclusion-1:

we can declare multiple resources but these resources with semi colon(;).
40
try(R1;R2;R3;...;Rn)
{
//statements;
}

Example:

try(FileWriter fw=new Fi leWriter(abc.txt);FileReader fr=new FileReader(abc.txt))


{
}

conclusion-2:

All resources should be auto closable resources


A resource is said to be auto closable if and only if corresponding class implements java.lang.Autoclosable
interface
All IO related and database related and network related resources are already implemented auto closable
interface.
Being a programmer we are not require to do anything just we should aware the point.
--.Auto closable came in 1.7 version and it contains only one method close.
i.e.,
public void close();

conclusion-3:

All resource reference variable are implicitly final and hence wit in the try block we cannot perform
reassignment otherwise we will get compile time error.
Example:

import java.io.*;
class TrywithResources
{
public static void main(String []args)
{
try(BufferReader br=new BufferReader(new FileReader("input.txt")))
{
br=new BufferReader(new FileReader("input.txt"));
}
}
}

o/p:auto closable resource br may be not be assigned.

conclusion-4:

until 1.6 version try should be associated with either catch or finally but from 1.7 version onwards we can
take only try with resource without catch or finally.

41
try(R)
{
//
}

Multi catch block:

until 1.6 version even though multiple different exceptions having same handling code for every exception
type we have to write a separate catch block. It increases length of the code and reduces readability.

Example:

try{
}
catch(AE e){
e.printStackTrace();
}
catch(IOE e){
e.printStackTrace();
}
catch(NPE e){
s.o.pln(e.getMessage());
}
catch(InterruptedException e){
s.o.pln(e.getMessage());
}

To overcome this problem sun people introduced multi catch block in 1.7 version
According to this we can write a single catch block that can handle multiple different type of exceptions
try
{
}
catch(NPE|InterruptedException e){
s.o.pln(e.getMessage());
}
catch(AE|IOE e){
e.printStackTrace();
}

The main advantage of this approach is length of the code is reduced and readability of the code improved.

import java.io.*;
class TrywithMutlicatch
{
public static void main(String []args)
{
try
{
s.o.pln(10/0);
42
String s=null;
s.o.pln(s.length());
}
catch(ArithmeticException|NullPointerException e){
s.o.pln(e);
}
}
}

In the above example weather raised exception is either ArithmeticException or NullPointerException the
same catch block can listen

Note:
In multi catch block there should not be any relation between exception types(either child to parent or parent
to child or same type) otherwise we will get compile time error.

try
{
}
catch(AE|Exception e)
{
e.printStackTrace();
}

o/p:Alternatives in a multi catch statement cannot be related by sub classing.

Exception Propagation:

Inside a method if an exception raised and if we are not handling that exception then exception object will be
propagated to caller then caller method is responsible to handle exception this process is called exception
propagation.

Rethrowing Exception:

we can use this approach to convert one exception type to another exception type.

Example:

try
{
s.o.pln(10/0);
}
catch(AE e)
{
throw new NullPointerException();
43
}

File Handling:

File:

In Java, a File is an abstract data type. A named location used to store related information is known as a File.
There are several File Operations like creating a new File, getting information about File, writing into a File,
reading from a File and deleting a File.

File f=new File("abc.txt");

This line won't create any physical file. First it will check is there any physical file named with abc.txt is
available or not. If it is available then 'f' simply refers that file. If it is not available then we are just creating java
file object to represent the name abc.txt'.

Example:

File f =new File("abc.txt");


System.out.println(f.exists());
f.createNewFile();
System.out.println(f.exists());

o/p:
1st run-->false and true
2nd run-->true and true

We can use java file object to represent directory also.

Example:

File f=new File("anil");


System.out.println(f.exists());
f.mkdir();
System.out.println(f.exists());

Note: In Unix everything is treated as a file. Java file IO concept is implemented based on Unix operating
system. Hence java file object can be used to represent both files and directories.

File Class Constructors:

* File f =new File(String name);

Creates a java file object to represent name of the file or directory in current working directory.

* File f =new File(File subdir, String name);

44
Example:

File f =new File("anil123");//constructor 1


f.mkdir();
File f1=new File("anil123", "demo.txt");//constructor 2
f.createNewFile();

or
File f1=new File(f,"demo.txt");//constructor 3
f.createNewFile();

Methods present File class:

boolean exists();

Returns true if the specified file or directory available.

boolean createNewFile();

First this method will check whether the specified file is already available or not. If it is already available
then this method returns false without creating any physical file.
If the file is not already available then this method creates a new file and returns true

boolean mkdir();

boolean isFile();

Returns true if the specified file object pointing to physical file.

boolean isDirectory();

Returns true if the specified file object pointing to directory.


String[] list();

This method returns the names of all files and sub directories present in specified directory.

long length();

Returns no. of characters present in the specified file.

boolean delete();

To delete specified file or directory.

Example:

import java.io.*;

class Test
45
{
public static void main(String[] args) thows Exception
{
int count=0;
File f=new File();
String[] s=f.list("D:\\NEWZEN FOLDER\\JAVA BASIC PROGRAMS\\Filehandling");
for(String s1:s)
{
count++;
System.out.println(s1);
}
System.out.println("The total number"+count);
}
}

To display only filenames:

import java.io.*;

class Test
{
public static void main(String[] args) thows Exception
{
int count=0;
File f=new File("D:\\NEWZEN FOLDER\\JAVA BASIC PROGRAMS\\Filehandling");
String[] s=f.list();
for(String s1:s)
{
File f1=new File(f,s1);
if(f1.isFile()){
count++;
System.out.println(s1);
}
}
System.out.println("The total number"+count);
}
}

To display only directory names:

import java.io.*;

class Test
{
public static void main(String[] args) thows Exception
{
int count=0;
File f=new File();
String[] s=f.list("D:\\NEWZEN FOLDER\\JAVA BASIC PROGRAMS\\Filehandling");
46
for(String s1:s)
{
File f1=new File(f,s1);
if(f1.isDirectory()){
count++;
System.out.println(s1);
}
}
System.out.println("The total number"+count);
}
}

FileWriter:

We can use FileWriter to write charachter data to the file.

Constructors:

FileWriter fw=new FileWriter(String filename);


FileWriter fw=new FileWriter(File f);

The above file writers meant for overriding of existing data instead of overriding if we want append operation
then we have to create filewriter by using the following constructors.

FileWriter fw=new FileWriter(String filename,boolean append);


FileWriter fw=new FileWriter(File f, boolean append);//true means append

Note: If the specified file is not already available then all the above constructors will create that file.

Various methods in FileWriter:

write(int ch) //to write a single charachter


write(char[] ch)//to write an array of characters.
write(String s)//to write String to the file.

 flush()//to give the gaurantee that total data


close()//to close the writer

Example:

import java.io.*;
class FileWriterDemo
{
public static void main(String[] args)

47
{
FileWriter fw=new FileWriter("abc.txt");
fw.write(100);//adding a single character
fw.write("anil\nkumar");
fw.write('\n');
char ch[]={'a','b','c'};
fw.write(ch);
fw.write('\n');
fw.flush();
fw.close();
}
}

In the above program filewriter can perform overriding of existing data.
Instead of overriding if we want append operation then we have to create filewriter object as follows

FileWriter fw=new FileWriter("abc.txt",true);

The main problem with filewriter is we have to insert line separator '\n' manually which is varied from system
to system it is difficulty to the programmer
we can solve this problem by using BufferedWriter and PrintWriter classes.

FileReader:

We can use filereader to read character data from the file.

Constructors:

FileReader fr=new FileReader(String filename);


FileReader fr=new FileReader(File f);

Methods of FileReader:

int read()//It attempts to read next character from the file and returns its unicode value
If the next character not available then this method returns -1
As this method returns Unicode value(int value), at the time of printing we have to perform type casting.

Example:

FileReader fr=new FileReader("abc.txt");

int i=fr.read();
while(i !=-1)
{
s.o.pln((char)i);
i=fr.read();
}

48
int read(char[] ch) //It attempts the read enough characters from the file into char[] and returns no. of
characters copied from the file.

Example:

File f=new File("abc.txt");


char[] ch=new char[(int)f.length()];
FileReader f=new FileReader(f);
fr.read(ch);
for(char ch1:ch)
{
s.o.pln(ch1);
}

void close();

Example:

import java.io.File;
import java.io.FileReader;

public class String1 {

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


File f=new File("D:\\NEWZEN FOLDER\\Java Notes\\Filehandling.txt");
char[] ch=new char[(int)f.length()];
FileReader fr=new FileReader(f);
fr.read(ch);
for(char ch1:ch)
{
System.out.print(ch1);
}
System.out.println("*****************************************************************");
FileReader fr1=new FileReader("D:\\NEWZEN FOLDER\\Java Notes\\OOPS.txt");
int i=fr1.read();
while(i !=-1)
{
System.out.print((char)i);
i=fr1.read();
}
}
}

Note: By using filereader we can read data character by character which is not convinient to the programer.

Usage of Filewriter and filereader is not recommended because


while writing data by file writer we have to insert line separator(\n)manually which is varied from system to
system it is difficult to the programmer
49
By using FileReader we can read data character by character, which is not convinient to the programmer.
To overcome these problems we should go for BufferedWriter and BufferedReader

BufferdWriter:

-->we can use BufferedWriter to write character data to the File.

Constructors:

-->BufferedWriter bw=new BufferedWriter(writer w);

ex:BufferedWriter bw=new BufferedWriter(new FileWriter("abc.txt"));

-->BufferedWriter bw=new BufferedWriter(writer w,int buffersize);

Note:BufferedWriter cannot communicate directly with the file it can communicate via some writer object.

various methods:

-->write(int ch)
-->wite(char[] ch)
-->write(String s)
-->flush()
-->close()
-->newLine()//to insert a line separator

example:

import java.io.*;
class FileWriterDemo
{
public static void main(String[] args)
{
FileWriter fw=new FileWriter("abc.txt");
BufferedWriter bw=new BufferedWriter(fw);
bw.write(100);//adding a single character
bw.newLine();
bw.write("anilkumar");
bw.newLine();
char ch[]={'a','b','c'};
bw.write(ch);
bw.newLine();
bw.flush();
bw.close();
}
}

50
-->whenever we are closing BufferedWriter automatically internal filewriter will be closed and we are not
required to close explicitly.

BufferedReader:

we can use BufferedReader to read character data from the file.
The main advantage of BufferedReader when compared with FileReader is we can read data Line by line in
addition to character by character.

Constructors:

BufferedReader br=new BufferedReader(reader r);


BufferedReader br=new BufferedReader(reader r, int buffersize);

 BufferedReader cannot communicate directly with the file and it can communicate via some reader object.

Various methods:

int read();
int read(char[] ch);
void close();
String readLine();//it attempts to read next line from the file and returns it if the next line not available then
this method returns null.

Example:

FileReader fr=new FileReader("abc.txt");


BufferedReader br=new Buffered Reader(fr);
String line=br.readLine();
while(line!=null)
{
sopln(line);
br.readLine();
}
br.close();

PrintWriter:

It is the most enhanced writer to write character data to the file the main advantage of printwriter over
Filewriter and BufferedWriter is we can write any type of primitive data directly to the file.

Constructors:

PrintWriter pw=new PrintWriter(String filename);


PrintWriter pw=new PrintWriter(File f);
PrintWriter pw=new PrintWriter(writer w);
51
Note: PrintWriter can communicate directly with the file and can communicate via some writer object also.

methods:

write(int ch)
wite(char[] ch)
write(String s)
flush()
close()
newLine()

print(char ch)
print(int i)
print(double d)
print(boolean b)
print(String s)

println(char ch)
println(int i)
println(double d)
println(boolean b)
println(String s)

Example:

FileWriter fw=new FileWriter("abc.txt");


PrintWriter pw=new PrintWriter(fw);
pw.write(100);
pw.print(100);
pw.println(true);
pw.println('c');
pw.println("anil");
pw.flush();
pw.close();

Note:
In general we use readers and writers to handle character data(text)
Whereas we can use streams to handle binary data(like images, pdfs, video files,...etc)
we can use OutputStream to write binary data to the file. InputStream to read binary data from the file.

52

You might also like