2. What is exception handling
The exception handling in java is one of the
powerful mechanism to handle the runtime errors so
that normal flow of the application can be maintained.
Exception Handling is a mechanism to handle runtime
errors such as ClassNotFound, IO, SQL, Remote etc.
3. What is exception
Dictionary Meaning: Exception is an abnormal
condition.
In java, exception is an event that disrupts the normal
flow of the program. It is an object which is thrown at
runtime.
4. The core advantage of exception
handling
Advantage of Exception Handling
The core advantage of exception handling is to
maintain the normal flow of the application.
Exception normally disrupts the normal flow of the
application.
6. Types of Exception
The sun Microsystems says there are three types of
exceptions:
Checked Exception
Unchecked Exception
Error
7. Checked Exception
A checked exception is an exception that occurs at the
compile time, these are also called as compile time
exceptions. These exceptions cannot simply be ignored
at the time of compilation, the programmer should
take care of (handle) these exceptions.
For example, if you use FileReader class in your
program to read data from a file, if the file specified in
its constructor doesn't exist, then
a FileNotFoundException occurs, and the compiler
prompts the programmer to handle the exception.
8. Unchecked exceptions
An unchecked exception is an exception that occurs at
the time of execution. These are also called
as Runtime Exceptions. These include programming
bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of
compilation.
For example, if you have declared an array of size 5 in
your program, and trying to call the 6th element of the
array then
an ArrayIndexOutOfBoundsExceptionexception occurs.
9. Errors
These are not exceptions at all, but problems that arise
beyond the control of the user or the programmer.
Errors are typically ignored in your code because you
can rarely do anything about an error. For example, if a
stack overflow occurs, an error will arise. They are also
ignored at the time of compilation.
10. Common scenarios where
exceptions may occur
1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an
ArithmeticException.
int a=50/0;//ArithmeticException
2) Scenario where NullPointerException occurs
If we have null value in any variable, performing any
operation by the variable occurs an
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
11. 3) Scenario where NumberFormatException occurs
The wrong formatting of any value, may occur
NumberFormatException. Suppose I have a string variable
that have characters, converting this variable into digit will
occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) Scenario where ArrayIndexOutOfBoundsException
occurs
If you are inserting any value in the wrong index, it would
result ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
12. Java Exception Handling Keywords
There are 5 keywords used in java exception handling.
try
catch
finally
throw
throws
13. Java try-catch
Java try block is used to enclose the code that might
throw an exception. It must be used within the
method.
Java try block must be followed by either catch or finally
block.
Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
14. Java catch block
Java catch block is used to handle the Exception. It
must be used after the try block only.
You can use multiple catch block with a single try.
15. Problem without exception
handling
Let's try to understand the problem if we don't use try-
catch block.
public class Testtrycatch1{
public static void main(String args[]){
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main
java.lang.ArithmeticException:/ by zero
16. Solution by exception handling
Let's see the solution of above problem by java try-catch block.
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by
zero rest of the code...
18. The JVM firstly checks whether the exception is
handled or not. If exception is not handled, JVM
provides a default exception handler that performs the
following tasks:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the
exception occurred).
Causes the program to terminate.
But if exception is handled by the application
programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
19. Java catch multiple exceptions
If you have to perform different tasks at the occurrence of different Exceptions,
use java multi catch block.
Let's see a simple example of java multi-catch block.
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 com
pleted");}
catch(Exception e){System.out.println("common task completed");}
System.out.println("rest of the code...");
}
}
Output:task1 completed rest of the code...
20. Java finally block
Java finally block is a block that is used to execute
important code such as closing connection, stream etc.
Java finally block is always executed whether exception
is handled or not.
Java finally block follows try or catch block.
22. Java throw keyword
The Java throw keyword is used to explicitly throw an
exception.
We can throw either checked or uncheked exception in
java by throw keyword. The throw keyword is mainly
used to throw custom exception. We will see custom
exceptions later.
The syntax of java throw keyword is given below.
throw exception;
Let's see the example of throw IOException.
throw new IOException("sorry device error);
23. java throw keyword example
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Test it NowOutput:
Exception in thread main java.lang.ArithmeticException:not
valid
24. Java throws keyword
The Java throws keyword is used to declare an
exception. It gives an information to the programmer
that there may occur an exception so it is better for the
programmer to provide the exception handling code so
that normal flow can be maintained.
25. Syntax of java throws
return_type method_name() throws exception_class_nam
e{
//method code
}
Which exception should be declared
Ans) checked exception only, because:
unchecked Exception: under your control so correct your
code.
error: beyond your control e.g. you are unable to do
anything if there occurs VirtualMachineError or
StackOverflowError.
26. Difference between throw and
throws in Java
throw throws
Java throw keyword is used to
explicitly throw an exception.
Java throws keyword is used to
declare an exception.
2) Checked exception cannot be
propagated using throw only.
Checked exception can be
propagated with throws.
3) Throw is followed by an
instance.
Throws is followed by class.
4) Throw is used within the
method.
Throws is used with the method
signature.
5) You cannot throw multiple
exceptions.
5) You can declare multiple
exceptions e.g.
public void method()throws
27. Java throw example
void m(){
throw new ArithmeticException("sorry");
}
Java throws example
void m()throws ArithmeticException{
//method code
}
Java throw and throws example
void m()throws ArithmeticException{
throw new ArithmeticException("sorry");
}
28. Difference between final, finally
and finalize
final finally finalize
Final is used to apply
restrictions on class,
method and variable.
Final class can't be
inherited, final method
can't be overridden
and final variable
value can't be
changed.
Finally is used to place
important code, it will
be executed whether
exception is handled
or not.
Finalize is used to
perform clean up
processing just before
object is garbage
collected.
Final is a keyword. Finally is a block. Finalize is a method.
29. Java final example
class FinalExample{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}}
30. Java finally example
class FinallyExample{
public static void main(String[] args){
try{
int x=300;
}catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");
}
}}
31. Java finalize example
class FinalizeExample{
public void finalize(){System.out.println("finalize call
ed");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}}
32. Multithreading in Java
Multithreading in java is a process of executing multiple
threads simultaneously.
Thread is basically a lightweight sub-process, a smallest
unit of processing. Multiprocessing and multithreading,
both are used to achieve multitasking.
But we use multithreading than multiprocessing because
threads share a common memory area. They don't allocate
separate memory area so saves memory, and context-
switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation
etc.
33. Advantages of Java Multithreading
1) It doesn't block the user because threads are
independent and you can perform multiple operations
at same time.
2) You can perform many operations together so it
saves time.
3) Threads are independent so it doesn't affect other
threads if exception occur in a single thread.
34. What is Thread in java
A thread is a lightweight sub process, a smallest unit of
processing. It is a separate path of execution.
Threads are independent, if there occurs exception in
one thread, it doesn't affect other threads. It shares a
common memory area.
36. Multitasking
Multitasking is a process of executing multiple tasks
simultaneously. We use multitasking to utilize the
CPU. Multitasking can be achieved by two ways:
Process-based Multitasking(Multiprocessing)
Thread-based Multitasking(Multithreading)
37. Multitasking
1) Process-based Multitasking (Multiprocessing)
Each process have its own address in memory i.e. each
process allocates separate memory area.
Process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another require some time
for saving and loading registers, memory maps, updating
lists etc.
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
Thread is lightweight.
Cost of communication between the thread is low.
38. Life cycle of a Thread (Thread
States)
A thread can be in one of the five states.
The life cycle of the thread in java is controlled by
JVM. The java thread states are as follows:
New
Runnable
Waiting
Non-Runnable (Blocked)
Terminated
39.
40. Thread Priorities
Every Java thread has a priority that helps the operating
system determine the order in which threads are
scheduled.
Java thread priorities are in the range between
MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a
constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a
program and should be allocated processor time before
lower-priority threads. However, thread priorities cannot
guarantee the order in which threads execute and are very
much platform dependent.
41. How to create thread
There are two ways to create a thread:
By extending Thread class
By implementing Runnable interface.
42. Thread class:
Thread class provide constructors and methods to create
and perform operations on a thread.Thread class extends
Object class and implements Runnable
interface.Commonly used Constructors of Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
43. Commonly used methods of Thread class:
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been interrupted.
44. Starting a thread:
start() method of Thread class is used to start a newly
created thread. It performs following tasks:A new
thread starts(with new callstack).
The thread moves from New state to the Runnable
state.
When the thread gets a chance to execute, its target
run() method will run.
45. 1) Java Thread Example by extending Thread
class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output:thread is running...
46. 2) Java Thread Example by implementing
Runnable interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:thread is running...
47. Synchronization in Java
Synchronization in java is the capability to control the
access of multiple threads to any shared resource.
Java Synchronization is better option where we want to
allow only one thread to access the shared resource.
48. Why use Synchronization
The synchronization is mainly used to
To prevent thread interference.
To prevent consistency problem.
49. Types of Synchronization
There are two types of synchronization
Process Synchronization
Thread Synchronization
50. Thread Synchronization
There are two types of thread synchronization mutual
exclusive and inter-thread communication.
Mutual Exclusive
Synchronized method.
Synchronized block.
static synchronization.
Cooperation (Inter-thread communication in java)
51. Java String
In java, string is basically an object that represents
sequence of char values. An array of characters works same
as java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
What is String in java
52. Java String class provides a lot of methods to perform
operations on string such as
compare(),
concat(),
equals(),
split(),
length(),
replace(),
compareTo(),
intern(),
substring() etc.
53. Generally, string is a sequence of characters. But in
java, string is an object that represents a sequence of
characters. The java.lang.String class is used to create
string object.
How to create String object?
There are two ways to create String object:
By string literal
By new keyword
54. 1) String Literal
Java String literal is created by using double quotes.
For Example:
String s="welcome";
Each time you create a string literal, the JVM checks
the string constant pool first. If the string already
exists in the pool, a reference to the pooled instance is
returned. If string doesn't exist in the pool, a new
string instance is created and placed in the pool. For
example:
String s1="Welcome";
String s2="Welcome";//will not create new instance
55. In the above example only one
object will be created. Firstly JVM
will not find any string object with
the value "Welcome" in string
constant pool, so it will create a
new object. After that it will find
the string with the value
"Welcome" in the pool, it will not
create new object but will return
the reference to the same instance.
Note: String objects are stored
in a special memory area
known as string constant pool.
56. Why java uses concept of string literal?
To make Java more memory efficient (because no new
objects are created if it exists already in string constant
pool).
57. 2) By new keyword
String s=new String("Welcome");//creates two objects
and one reference variable
In such case, JVM will create a new string object in
normal(non pool) heap memory and the literal
"Welcome" will be placed in the string constant pool.
The variable s will refer to the object in heap(non
pool).
58. Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by n
ew keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
java strings example
59. Java StringBuffer class
Java StringBuffer class is used to created mutable
(modifiable) string. The StringBuffer class in java is
same as String class except it is mutable i.e. it can be
changed.
60. Important methods of StringBuffer
class
public synchronized StringBuffer append(String s): is used
to append the specified string with this string. The append()
method is overloaded like append(char), append(boolean),
append(int), append(float), append(double) etc.
public synchronized StringBuffer insert(int offset, String
s): is used to insert the specified string with this string at the
specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public synchronized StringBuffer replace(int startIndex,
int endIndex, String str): is used to replace the string from
specified startIndex and endIndex.
public synchronized StringBuffer delete(int startIndex, int
endIndex): is used to delete the string from specified startIndex
and endIndex.
public synchronized StringBuffer reverse(): is used to reverse
the string.
61. Important methods of StringBuffer
class
public int capacity(): is used to return the current capacity.
public void ensureCapacity(int minimumCapacity): is used
to ensure the capacity at least equal to the given minimum.
public char charAt(int index): is used to return the character
at the specified position.
public int length(): is used to return the length of the string i.e.
total number of characters.
public String substring(int beginIndex): is used to return the
substring from the specified beginIndex.
public String substring(int beginIndex, int endIndex): is
used to return the substring from the specified beginIndex and
endIndex
62. Java I/O
Java I/O (Input and Output) is used to process the
input and produce the output.
Java uses the concept of stream to make I/O operation
fast. The java.io package contains all the classes
required for input and output operations.
63. Stream
A stream is a sequence of data.In Java a stream is
composed of bytes. It's called a stream because it is
like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All
these streams are attached with console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
64. OutputStream vs InputStream
OutputStream
Java application uses an
output stream to write data
to a destination, it may be
a file, an array, peripheral
device or socket.
InputStream
Java application uses an
input stream to read data
from a source, it may be a
file, an array, peripheral
device or socket.
65. OutputStream class
OutputStream class is an abstract class. It is the super
class of all classes representing an output stream of
bytes. An output stream accepts output bytes and
sends them to some sink.
66. Useful methods of OutputStream
Method Description
1) public void write(int)throws
IOException
is used to write a byte to the
current output stream.
2) public void write(byte[])throws
IOException
is used to write an array of byte to
the current output stream.
3) public void flush()throws
IOException
flushes the current output stream.
4) public void close()throws
IOException
is used to close the current output
stream.
67. InputStream class
Method Description
1) public abstract int read()throws
IOException
reads the next byte of data from
the input stream. It returns -1 at
the end of file.
2) public int available()throws
IOException
returns an estimate of the number
of bytes that can be read from the
current input stream.
3) public void close()throws
IOException
is used to close the current input
stream.
InputStream class is an abstract class. It is the super class of all
classes representing an input stream of bytes.
Useful methods of InputStream
68. Byte Streams
Java byte streams are used to perform input and output
of 8-bit bytes. Though there are many classes related
to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream.
69. Following is an example which makes use of these two
classes to copy an input file into an output file −
import java.io.*;
public class CopyFile { public static void main(String
args[]) throws IOException { FileInputStream in = null;
FileOutputStream out = null; try { in = new
FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1){
out.write(c); } }
finally { if (in != null)
{ in.close(); }
if (out != null) { out.close(); } } } }
Now let's have a file input.txt with the following content −
This is test for copy file.
70. Character Streams
Java Byte streams are used to perform input and
output of 8-bit bytes, whereas Java Character streams
are used to perform input and output for 16-bit
Unicode. Though there are many classes related to
character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally
FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here the major difference is that
FileReader reads two bytes at a time and FileWriter
writes two bytes at a time.
71. Following is an example which makes use of these two
classes to copy an input file into an output file −
import java.io.*;
public class CopyFile {
public static void main(String args[])
throws IOException { FileReader in = null;
FileWriter out = null;
try { in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c); } }
finally { if (in != null) { in.close(); }
if (out != null) { out.close(); } } } }
Now let's have a file input.txt with the following content −
This is test for copy file.
72. Standard Streams
All the programming languages provide support for
standard I/O where the user's program can take input
from a keyboard and then produce an output on the
computer screen. If you are aware of C or C++
programming languages, then you must be aware of
three standard devices STDIN, STDOUT and
STDERR.
73. Similarly, Java provides the
following three standard streams −
Standard Input − This is used to feed the data to
user's program and usually a keyboard is used as
standard input stream and represented as System.in.
Standard Output − This is used to output the data
produced by the user's program and usually a
computer screen is used for standard output stream
and represented as System.out.
Standard Error − This is used to output the error data
produced by the user's program and usually a
computer screen is used for standard error stream and
represented as System.err.
74. example
import java.io.*;
public class ReadConsole {
public static void main(String args[])
throws IOException {
InputStreamReader cin = null;
try { cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit."); char c;
do { c = (char) cin.read();
System.out.print(c); }
while(c != 'q'); }
finally { if (cin != null) {
cin.close(); } } } }
75. Java FileWriter Class
Java FileWriter class is used to write character-oriented
data to a file. It is character-oriented class which is
used for file handling in java.
76. Java FileWriter class declaration
Constructor Description
FileWriter(String file) Creates a new file. It gets file
name in string.
FileWriter(File file) Creates a new file. It gets file
name in File object.
Let's see the declaration for Java.io.FileWriter class:
public class FileWriter extends OutputStreamWriter
Constructors of FileWriter class
77. Methods of FileWriter class
Method Description
void write(String text) It is used to write the string into
FileWriter.
void write(char c) It is used to write the char into
FileWriter.
void write(char[] c) It is used to write char array into
FileWriter.
void flush() It is used to flushes the data of
FileWriter.
void close() It is used to close the FileWriter.
78. Java FileWriter Example
package com.javatpoint;
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:testout.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
Output:
Success...
testout.txt:
Welcome to javaTpoint.
79. Java FileReader Class
Java FileReader class is used to read data from the file.
It returns data in byte format like FileInputStream
class.
It is character-oriented class which is used for file
handling in java.
80. Java FileReader class declaration
public class FileReader extends InputStreamReader
Constructors of FileReader class
Constructor Description
FileReader(String file) It gets filename in string. It
opens the given file in read
mode. If file doesn't exist, it
throws FileNotFoundException.
FileReader(File file) It gets filename in file instance.
It opens the given file in read
mode. If file doesn't exist, it
throws FileNotFoundException.
81. Methods of FileReader class
Method Description
int read() It is used to return a character in
ASCII form. It returns -1 at the
end of file.
void close() It is used to close the FileReader
class.
82. Java FileReader Example
package com.javatpoint;
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to javaTpoint.
Output:
Welcome to javaTpoint.