Java Notes 2
Java Notes 2
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;
Example:
class Test{
void Test(){
System.out.println("It is method but not constructor");
}
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.
}
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.
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();
}
}
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();
}
}
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.
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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:
Default Constructor:
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);}
Parameterized Constructors:
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);}
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");
}
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{
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{
Interface fields are public, static and final by default, and the methods are public and abstract.
package Inter;
void calling();
void camera();
void audio();
void internet();
System.out.println("msg");
}
}
package Inter ;
System.out.println("Apple Calling");
}
System.out.println("Apple Camera");
}
12
public void audio() {
System.out.println("Apple Audio");
}
System.out.println("Apple Internet");
}
}
package Inter;
System.out.println("Realme Calling");
}
System.out.println("Realme Camera");
}
System.out.println("Realme Audio");
}
System.out.println("Realme Internet");
}
package Inter;
13
public static void main(String[] args) {
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));
}
}
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");}
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:
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");
}
}
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.
interface interface_name{
interface nested_interface_name{
//statements;}
}
package Inter;
public interface NestedInterface {
interface Nest{
package Inter;
}
public void m1() {
System.out.println("hi");
16
}
}
class class_name{
interface nested_interface_name{
//statements;
}
}
Example:
class A{
interface Message{
void msg();
}
}
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
}
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();
}
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);
}
}
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:
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
ArithmeticException EOFException
NullPointerException FileNotFoundException
ClassCasteException
IndexOutOfBoundsException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
StackOverFlowError VerifyError
OutOfMemoryError
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.
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.
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
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:
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());
}
}
}
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){
try{
//risky code
}
25
catch(ArithmeticException e){
catch(SQLException 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:
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.
Sometimes we can create exception objects explicitly and we can handover to the JVM manually for this we
have to use throw keyword
Example:
Hence the main objective of throw keyword is to handover our created exception object to the JVM
manually.
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;
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();
}
}
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");
}
}
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.
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.
}
}
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();
}
}
class Test
{
p s v main(String[] args)
{
throw new Error();
}
}
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
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 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:
Example:
NullPointerException:
Example:
String s=null;
S.o.pln(s.length);
ClassCasteException:
StackOverFlowError:
Example:
class Test{
p s v m1()
{
m2();
37
}
p s v m2()
{
m1();
}
p s v main(String[] args)
{
m1();
}
}
NoClassDefFoundError:
>>java Test
If Test.class file is not avaible then we will get runtime exception saying NoClassDefFoundError:Test
ExceptionInInitializerError:
class Test
{
static int x=10/0;
}
Example-2:
class Test
{
static{
String s=null;
s.o.pln(s.length());
}
}
IlleagalArgumentException:
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
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:
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.
Example:
assert(x>10);
If x is not greater than 10 then we will get runtime exception saying assertion error.
As the part of 1.7 version in exception handling the following two concepts introduced
39
1)try with resources
2)multi catch block
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.
conclusion-1:
we can declare multiple resources but these resources with semi colon(;).
40
try(R1;R2;R3;...;Rn)
{
//statements;
}
Example:
conclusion-2:
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"));
}
}
}
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)
{
//
}
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();
}
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.
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:
o/p:
1st run-->false and true
2nd run-->true and true
Example:
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.
Creates a java file object to represent name of the file or directory in current working directory.
44
Example:
or
File f1=new File(f,"demo.txt");//constructor 3
f.createNewFile();
boolean exists();
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();
boolean isDirectory();
This method returns the names of all files and sub directories present in specified directory.
long length();
boolean delete();
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);
}
}
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);
}
}
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:
Constructors:
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.
Note: If the specified file is not already available then all the above constructors will create that file.
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
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:
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:
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:
void close();
Example:
import java.io.File;
import java.io.FileReader;
Note: By using filereader we can read data character by character which is not convinient to the programer.
BufferdWriter:
Constructors:
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 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:
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:
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:
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