Notes Java
Notes Java
Exception is an event that interrupts the normal flow of execution. It is a disruption during
the execution of the Java program.
Checked Exception
The exception that can be predicted by the programmer at the compile time.Example
: File that need to be opened is not found. These type of exceptions must be checked at
compile time.
Unchecked Exception
Error
Errors are typically ignored in code because you can rarely do anything about an
error. Example :if stack overflow occurs, an error will arise. This type of error cannot be
handled in the code.
Compile time errors can be again classified again into two types:
Syntax Errors
Semantic Errors
Instead of declaring int a; you mistakenly declared it as in a; for which compiler will
throw an error.
Example:
You have declared a variable int a; and after some lines of code you again declare an
integer as int a;. All these errors are highlighted when you compile the code.
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that is why
we use exception handling. Let's take a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement 5,
rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform
exception handling, rest of the statement will be executed. That is why we use exception
handling in java.
1. try
2. catch
3. finally
4. throw
5. throws
Java try-catch
Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw exception
3. }finally{}
Java catch block is used to handle the Exception. It must be used after the try block only.
Output:
Exception in thread main java.lang.ArithmeticException:/ by zeroAs displayed in the above
example, rest of the code is not executed (in such case, rest of the code... statement is not
printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
Output:
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:
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
task1 completed
The try block within a try block is known as nested try block in java.
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
1. class Excep6{
2. public static void main(String args[]){
3. try{
4. try{
5. System.out.println("going to divide");
6. int b =39/0;
7. }catch(ArithmeticException e){System.out.println(e);}
8. try{
9. int a[]=new int[5];
10. a[5]=4;
11. }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
12.
13. System.out.println("other statement);
14. }catch(Exception e){System.out.println("handeled");}
15.
16. System.out.println("normal flow..");
17. } }
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.
Note: If you don't handle exception, before terminating the program, JVM executes
finally block(if any).
o Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.
Let's see the different cases where java finally block can be used.
Let's see the java finally example where exception doesn't occur.
1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code..."); } }
Output:5
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.
1. throw exception;
In this example, we have created the validate method that takes integer value as a parameter.
If the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
Output:
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
exception handled
normal flow...
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. } }
6. public class Testthrows2{
7. public static void main(String args[]){
8. try{
9. M m=new M();
10. m.method();
11. }catch(Exception e){System.out.println("exception handled");}
12. System.out.println("normal flow...");
13. }
14. }
Output
:exception handled
normal flow...
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Output:device operation performed
normal flow...
There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:
4) Throw is used within the method. Throws is used with the method
signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions
e.g.
public void method()throws
IOException,SQLException.
1. void m(){
2. throw new ArithmeticException("sorry");
3. }
There are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:
1. class FinalExample{
2. public static void main(String[] args){
3. final int x=100;
4. x=200;//Compile Time Error
5. }}
1. class FinallyExample{
2. public static void main(String[] args){
3. try{
4. int x=300;
5. }catch(Exception e){System.out.println(e);}
6. finally{System.out.println("finally block is executed");}
7. }}
1. class FinalizeExample{
2. public void finalize(){System.out.println("finalize called");}
3. public static void main(String[] args){
4. FinalizeExample f1=new FinalizeExample();
5. FinalizeExample f2=new FinalizeExample();
6. f1=null;
7. f2=null;
8. System.gc();
9. }}
Java Package
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Let's take an example, Sun Microsystem has definded a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group
e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes
are for networking etc and so on. So, Sun has subcategorized the java package into subpackages
such as lang, net, io etc. and put the Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
Output:Hello subpackage
There is a scenario, I want to put the class file of A.java source file in classes folder of c: drive.
For example:
1. /save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory
where the class file resides.
The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java that tells
where to look for class file. For example:
Output:Welcome to package
o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file in
the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved by the
public class name.
1. //save as A.java
2.
3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}
What is Thread in java
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
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.
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended
to be executed by a thread. Runnable interface have only one method named run().
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has
not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
Multithreading in Java
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.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
As shown in the above figure, thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS and one
process can have multiple threads.
o wait()
o notify()
o notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description
public final void wait(long timeout)throws InterruptedException waits for the specified a
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on
this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation. Syntax:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
Let's see the important differences between wait and sleep methods.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32.
33. }}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
Each thread have a priority. Priorities are represented by a number between 1 and 10. In
most cases, thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification
that which scheduling it chooses.
Output
Java Applet
An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following −
• A main() method is not invoked on an applet, and an applet class will not define
main().
• When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
• A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
• The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
• Applets have strict security rules that are enforced by the Web browser. The security
of an applet is often referred to as sandbox security, comparing the applet to a child
playing in a sandbox with various rules that must be followed.
• Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.
Life Cycle of an Applet
Four methods in the Applet class gives you the framework on which you build any serious
applet −
• init − This method is intended for whatever initialization is needed for your applet. It
is called after the param tags inside the applet tag have been processed.
• start − This method is automatically called after the browser calls the init method. It
is also called whenever the user returns to the page containing the applet after having
gone off to other pages.
• stop − This method is automatically called when the user moves off the page on
which the applet sits. It can, therefore, be called repeatedly in the same applet.
• destroy − This method is only called when the browser shuts down normally.
Because applets are meant to live on an HTML page, you should not normally leave
resources behind after a user leaves the page that contains the applet.
• paint − Invoked immediately after the start() method, and also any time the applet
needs to repaint itself in the browser. The paint() method is actually inherited from
the java.awt.
import java.applet.*;
import java.awt.*;
These import statements bring the classes into the scope of our applet class −
• java.applet.Applet
• java.awt.Graphics
Without those import statements, the Java compiler would not recognize the classes Applet
and Graphics, which the applet class refers to.
Advantage of Applet
Drawback of Applet
java.awt.Component class
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
1. By html file.
2. By appletViewer tool (for testing purpose).
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5. public void paint(Graphics g){
6. g.drawString("welcome",150,150);
7. }
8. }
Note: class must be public because its object is created by Java Plugin software that resides
on the browser.
myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer First.java. Now Html file is not
required but it is for testing purpose only.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
1. import java.applet.Applet;
2. import java.awt.*;
3. public class GraphicsDemo extends Applet{
4.
5. public void paint(Graphics g){
6. g.setColor(Color.red);
7. g.drawString("Welcome",50, 50);
8. g.drawLine(20,30,20,300);
9. g.drawRect(70,100,30,30);
10. g.fillRect(170,100,30,30);
11. g.drawOval(70,200,30,30);
12.
13. g.setColor(Color.pink);
14. g.fillOval(170,200,30,30);
15. g.drawArc(90,150,30,30,30,270);
16. g.fillArc(270,150,30,30,0,180);
17.
18. }
19. }
myapplet.html
1. <html>
2. <body>
3. <applet code="GraphicsDemo.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>