You are on page 1of 66

JAVA

Exception
• An exception is an event that occurs during the
execution of a program that disrupts the normal
flow of instructions.
• At compilation time syntax and semantics
checking is done and code is not executed on
machine so exceptions can only be detected
at run time.
• JRE tries to find someone that can handle the
raised exception. 
• When an exception occurs within a method, the
method creates an exception object and hands it
off
to
the
runtime
system.
This
is
called “throwing
the
exception”.
The
exception object contains a lot of debugging

Exception handling
• After a method throws an exception, the runtime
system receives the exception object, it tries to
find the handler for the exception. Exception
Handler is the block of code that can process the
exception object.
•  If appropriate exception handler is found,
exception object is passed to the handler to
process it. The handler is said to be “catching
the exception”.
• If there are no appropriate exception handler
found
then
program
terminates
printing
information about the exception.

When an exception occurs program
processing gets terminated and doesn’t
continue further. In such cases we get a system
generated error message.  It is an object which is

Runtime Exceptions are cause by bad programming. SQLException. These exceptions need not be included in any method’s throws list because compiler does not check to see if a method handles or throws these exceptions.Classisfication • The sun microsystem says there are three types of exceptions: – Checked Exception: The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g. ClassNotFoundException. ArithmeticException.  Checked Exceptions are exceptional scenarios that we can anticipate in a program and try to recover from it. etc. We should catch this exception and provide useful message to user and log it properly for debugging purpose. – Unchecked Exception: The classes that extend RuntimeException are known as unchecked exceptions e. logic errors or improper use of an API etc. IllegalAccessException. NoSuchFieldException EOFException etc. These exceptions cannot simply be ignored at the time of compilation. NullPointerException.  But it’s the duty of the programmer to handle these exceptions and provide a safe exit. – Error: Error are irrecoverable. ArrayIndexOutOfBoundsException. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. Checked exceptions are checked at compile-time. it will give compilation error.IOException.  If these exceptions are not handled/declared in the program. Errors indicate serious problems and . the Programmer should take care of (handle) these exceptions.g.

Exception Hierarchy .

Exception Hierarchy .

Throwable class implementation of this method simply use getMessage() method to return the exception message. public String toString() – This method returns the information about Throwable in String format.Useful Exception Methods Some of the useful methods of Throwable class are. this method is overloaded and we can pass PrintStream or PrintWriter as argument to write the stack trace information to the file or stream. the returned String contains the name of Throwable class and localized message. public synchronized Throwable getCause() – This method returns the cause of the exception or null id the cause is unknown. – – – – – public String getMessage() – This method returns the message String of Throwable and the message can be provided while creating the exception through it’s constructor. public void printStackTrace() – This method prints the stack trace information to the standard error stream. . public String getLocalizedMessage() – This method is provided so that subclasses can override it to provide locale specific message to the calling program.

Checked Exceptions are not forwarded in calling chain (propagated) • In java exceptions are handled by following mechanisms – Try-catch/try-finally/try-multiple catch – Throws – Throw – Finally – User defined exceptions . the exception again drops down to the previous method. If not caught there. it drops down the call stack to the previous method.Exception Handling in Java • Java Exception handling is a framework that is used to handle runtime errors only. compile time errors are not handled by exception handling framework. • An exception is first thrown from the top of the stack and if it is not caught. and so on until they are caught or until they reach the very bottom of the call stack. This is called exception propagation. By default Unchecked Exceptions are forwarded in calling chain.

the catch block (or blocks) that follows the try is checked. If an exception occurs in protected code. Every try block should be immediately followed either by a catch block or finally block. the exception is passed to the catch block much as an argument is passed into a method parameter. • A catch statement involves declaring the type of exception you are trying to catch. If the type of exception that occurred is listed in a catch block. • If you do not  handle the exception in a try catch block. The code which is prone to exceptions is placed in the try block. when an exception occurs.Java try-catch block • Java try block is used to enclose the code that might throw an exception. • A simple way to capture any exception is to use an object of Exception class as other classes inherit Exception class try{   //code that may throw exception   }catch(ExceptionclassName ref){}   or try{   //code that may throw exception   }finally{}   . that exception is handled by catch block associated with it. Handling all the exceptions using the try and catch block could be cumbersome and will hinder the coders throughput. compiling will fail.

Internal working of java try-catch block .

nextInt().in).out. } catch (ArithmeticException e) { // catch block System. try { // try block result = a / b.Example class Division { public static void main(String[] args) { int a. result.println("Result = " + result). } } } .println("Exception caught: Division by zero. System. System. b = input.").out.println("Input two integers"). b.out.nextInt(). Scanner input = new Scanner(System. a = input.

    }   }  .      }      catch(ArithmeticException e){System.out. • All catch blocks must be ordered from most specific to most general i.out.println("task 2 completed"). public class TestMultipleCatchBlock{     public static void main(String args[]){      try{       int a[]=new int[5].").out.println("rest of the code.Multiple catch Blocks • If you have to perform different tasks at the occurrence of different Exceptions... use java multi catch block. catch for ArithmeticException must come before catch for Exception .}      catch(Exception e){System.println("task1 is completed").e.       a[5]=30/0.}      catch(ArrayIndexOutOfBoundsException e){System.out. •  At a time only one Exception is occured and at a time only one catch block is executed.}         System.println("common task completed").

println("other statement).out.").}             System.out.out.     }catch(Exception e){System.println(e).       }catch(ArrayIndexOutOfBoundsException e){System..println(e). • Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error.println("handeled").    }   . class Excep6{    public static void main(String args[]){     try{       try{        System.}           try{       int a[]=new int[5]. In such cases.        int b =39/0. exception handlers have to be nested.println("going to divide").       }catch(ArithmeticException e){System.println("normal flow.Nested try blocks • The try block within a try block is known as nested try block in java.out.}        System.       a[5]=4.out.out.

class Test { public static void main(String[] args) { try(BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.. The try-with-resources statement ensures that each resource is closed at the end of the statement. } } catch(IOException ie) { System.out.println(str).out. it is also referred to as automatic resource management.txt"))) { String str.. } } } . This feature add another way to exception handling with resources management.} import java.*. you do not have to explicitly close the resources. try(resource-specification) {  //use the resource  } catch() {.readLine())!=null) { System.println("exception").io. while((str=br.Try with resource management • JDK 7 introduces a new version of try statement known as try-with-resources statement.

Java finally block must be followed by try or catch block. but only one finally block. Using a finally block. lets you run any cleanup type statements that you want to execute.finally • A finally block of code always executes whether or not exception has occurred. no matter what happens in the protected code. It is used to execute important code such as closing connection.      System. stream etc. before terminating the program.println("finally block is always executed").     }     catch(ArithmeticException e){System. JVM executes finally block(if any).lang.out.ArithmeticException:/ by zero .exit() or by causing a fatal error that causes the process to abort) public class TestFinallyBlock2{     public static void main(String args[]){     try{      int data=25/0.}     finally{System. • If you don't handle exception.out.out.println(e). • For each try block there can be zero or more catch blocks.println(data). • The finally block will not be executed if program exits(either by calling System.}       }   }   Output:Exception in thread main java.

you must either caught or declare the exception. there can be two cases. In case you declare the exception. B. it throws the exception to immediate calling method in the hierarchy. – Case2:You declare the exception i. A method can do so by using the throws keyword. Either the code is being enclosed by try block and exception handling is implemented in the same method. The 'throws' clause takes arguments as a list of the objects of type 'Throwables' class. or the method can throws the exception to the calling method simply. specifying throws with the method. This is what ‘throws’ does in exception handling. • Anybody calling a method with a throws clause is needed to be enclosed within the try catch blocks type method_name(parameter_list) throws exception_list { //definition of method } . Ie In java if a code written within a method throws an exception. • If you are calling a method that declares an exception.e. so that anyone calling that method gets a prior knowledge about which exceptions to handle. the code will be executed fine. an exception will be thrown at runtime because throws does not handle the exception.throws • Any method capable of causing exceptions must list all the exceptions possible during its execution. • 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. handle the exception using try/catch. if exception does not occur. • The 'throws' clause in java programming language is to specify that the method raises particular type of exception while being executed. In case you declare the exception if exception occures. A. – Case1:You caught the exception i.e.

   class M{    void method()throws IOException{     throw new IOException("device error")...io.println("exception handled").println("normal flow.    }   }   class Testthrows3{      public static void main(String args[])th rows IOException{//declare exception        M m=new M().out.println("device operation perf ormed").        m.io.Example 1 CASE 1 caught the exception import java.*..       }catch(Exception e) {System.     }   }   Output:exception handled normal flow.println("normal flow.    }   }   public class Testthrows2{      public static void main(String args[]){       try{        M m=new M().out.out.          System..out..").method().     }   }   Output:device operation performed normal flow.method().   class M{    void method()throws IOException{     System..        m.*. . CASE 2 :A If exception doesn’t occur import java.}              System..").

..   class M{    void method()throws IOException{     throw new IOException("device error").EXAMPLE 2 CASE 2:B Program if exception occurs import java.          System.*.println("normal flow.method().").        m.     }   }   Output:Runtime Exception .    }   }   class Testthrows4{      public static void main(String args[])throws IOException{//declare exception        M m=new M().out.io.

When a throw statement is encountered and executed. (if its not explicit) • The throw keyword is used to throw an exception from within a method. • When using the throw keyword to throw a checked exception from within a method. Only object of Throwable class or its sub classes can be thrown. the method is not required to declare those unchecked exceptions in its throws clause. the method must either: –      Declares the throws clause followed by the exceptions thrown by the throw statements. and the closest catch statement is checked for matching type of exception. Syntax:Throw ThrowableInstance .throw • The Java throw keyword is used to explicitly throw an exception.ie method should be inside a trycatch block • If the throw statements throw unchecked exceptions. execution of the current method is stopped and returned to the caller. The throw keyword is mainly used to throw custom exception(user defined). • Whereas the throws keyword is used to declare that a method may throw one or some exceptions. • We can throw either checked or uncheked exception in java by throw keyword. The caller has to catch the exceptions (catching is optional if the exceptions are of type unchecked exceptions). • Throw keyword should be defined in either try catch block or the method should be defined using throws keyword. or: –     Catches the exceptions thrown by the throw statements. Program execution stops on encountering throw statement.

    } } public class TestThrow1{      static void validate(int age){        if(age<18)         throw new ArithmeticException ("not valid")..out.Syntax and Example   void aMethod() throws Exception1.         System..        else         System. Exception2 {     // statements.     if (an exception occurs) {         throw new Exception1().     }    // statements.      }      public static void main(String ar gs[]){         validate(13).     if (another exception occurs) {         throw new Exception2()....println("rest of the c ode.println("welcome to  vote")..out.").     }   } .

System.println("Input is valid!!"). • to throw your own exception explicitly using throw keyword package beginnersbook.12). } public static void main(String args[]){ int res=sum(0. System.println(res). int num2){ if (num1 == 0) throw new ArithmeticException("First parameter is not valid").printStackTrace(). } } . else System. } catch (MyOwnException e) { e. class Exception2{ static int sum(int num1.out. } } } • to throw an already defined exception using throw keyword package beginnersbook. else System. } } class EmployeeTest { static void employeeAge(int age) throws MyOwnException{ if(age < 0) throw new MyOwnException("Age can't be less than zero"). } public static void main(String[] args) { try { employeeAge(-2).out.com.out.println("Both parameters are correct!!").com.Example • Method call of a method using throw should be in try block as it is throwing an exception.out. return num1+num2.println("Continue Next statements"). class MyOwnException extends Exception { public MyOwnException(String msg) { super(msg).

Checked exception can be propagated with throws. 4) Throw is used within the method. 3) Throw is followed by an instance. exception. You can declare multiple exceptions e. public void method()throws . Throws is followed by class.Difference between throws and throw No: throw throws 1) Java throw keyword is used Java throws keyword is used to to explicitly throw an declare an exception.g. 2) Checked exception cannot be propagated using throw only. Throws is used with the method signature. 5) You cannot throw multiple exceptions.

User-defined exceptions/Custom Exceptions • You can also create your own exception sub class simply by extending java Exception class. class InvalidAgeException extends Exception{    InvalidAgeException(String s){     super(s). You can define a constructor for your Exception sub class (not compulsory) and you can override the toString() function to display your customized message on catch.println("welcome to vote").      }            public static void main(String args[]){         try{         validate(13).println("Exception occured: "+m).println("rest of the code.         }catch(Exception m){System.out.        else         System.}            System.").out.   .out.    }   }   class TestCustomException1{         static void validate(int age)throws InvalidAgeException{        if(age<18)         throw new InvalidAgeException("not valid")...

Example
package java4s;
 
public class Client {
public static void main(String[]
args)throws Exception
{
   int price = -120;
 
   if(price < 0)
      throw new
MyOwnExceptionClass(price);
   else
      System.out.println("Your age
is :"+price);
   }
}

package java4s;
 
public class MyOwnExceptionClass
extends Exception {
 
    private int price;
 
    public MyOwnExceptionClass(int price)
{
        this.price = price;
    }
 
    public String toString(){
        return "Price should not be in
negative, you are entered" +price;
    }
 
}

Example
class MyException extends Exception{
String str1;
MyException(String str2) {
str1=str2;
}
public String toString(){
return ("Output String = "+str1) ;
}
}
class CustomException{
public static void main(String args[]){
try{
throw new MyException("Custom"); // I'm throwing user defined custom exception above
}
catch(MyException exp){
System.out.println("Hi this is my catch block") ;
System.out.println(exp) ;
}}}
Output:
Hi this is my catch block Output String = Custom

ExceptionHandling with MethodOverriding in Java

There are many rules if we talk about methodoverriding
with exception handling. The Rules are as follows:
• If the superclass method does not declare an
exception
– If the superclass method does not declare an exception,
subclass overridden method cannot declare the checked
exception but it can declare unchecked exception.

• If the superclass method declares an exception
– If the superclass method declares an exception, subclass
overridden method can declare same, subclass exception or
no exception but cannot declare parent exception.

Advantage of Exceptions • Separating Error-Handling Code from "Regular" Code:Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program.  . the grouping or categorizing of exceptions is a natural outcome of the class hierarchy.  • Grouping and Differentiating Error Types: Because all exceptions thrown within a program are objects.  • Propagating Errors Up the Call Stack: A second advantage of exceptions is the ability to propagate error reporting up the call stack of methods.

we should close all the resources in finally block or use Java 7 try-with-resources enhancement to let java runtime close it for you. we can create a custom exception with error code and caller program can handle these error codes. This approach will reduce our code size and it will look cleaner too.Exception handling best practices • Use Specific Exceptions – Base classes of Exception hierarchy doesn’t provide any useful information. • Single catch block for multiple exceptions – Most of the times we log exception details and provide message to the user. • Throw Early or Fail-Fast – We should try to throw exceptions as early as possible. we may want to avoid throwing exception if the connection fails. • Catch Late – Since java enforces to either handle the checked exception or to declare it in method signature.  • Closing Resources – Since exceptions halt the processing of program. in this case we should use java 7 feature for handling multiple exceptions in a single catch block. while updating the stock quotes in database from a third party webservice. • Use Exceptions Judiciously – Exceptions are costly and sometimes it’s not required to throw exception at all and we can return a boolean variable to the caller program to indicate whether an operation was successful or not. This makes debugging easy and helps client application to handle exceptions appropriately. • Using Custom Exceptions – It’s always better to define exception handling strategy at the design time and rather than throwing and catching multiple exceptions. For example. .  always throw and catch specific exception classes so that caller will know the root cause of exception easily and process them. • Logging Exceptions – We should always log exception messages and while throwing exception provide clear message so that caller will know easily why the exception occurred. This is helpful where the operation is optional and you don’t want your program to get stuck because it fails. sometimes developers tend to catch the exception and log the error.

• An applet is a Java class that extends the java. • Applets have strict security rules that are enforced by the Web browser. . and an applet class will not define main(). • Java Plug-in software is responsible to manage the life cycle of an applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment.Applet • An applet is a Java program that runs in a Web browser and works at client side.Applet class. • When a user views an HTML page that contains an applet. comparing the applet to a child playing in a sandbox with various rules that must be followed. Applet is a special type of program that is embedded in the webpage to generate the dynamic content. • A main() method is not invoked on an applet. • A JVM is required to view an applet. the code for the applet is downloaded to the user's machine. The security of an applet is often referred to as sandbox security. • Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file. • The JVM on the user's machine creates an instance of the applet class and invokes various methods during the applet's lifetime.applet.

.Applet class. Those implementations may be overridden as necessary. The viewer may: – request information about the author. The base applet class provides methods that a derived Applet class may call to obtain information and services from the browser context. version and copyright of the applet – request a description of the parameters the applet recognizes – initialize the applet – destroy the applet – start the applet's execution – stop the applet's execution • The Applet class provides default implementations of each of these methods.applet.Applet • Every applet is an extension of the java. the Applet class provides an interface by which the viewer or browser obtains information about the applet and controls the applet's execution. These include methods that do the following: – Get applet parameters – Get the network location of the HTML file that contains the applet – Get the network location of the applet class directory – Print a status message in the browser – Fetch an image – Fetch an audio clip – Play an audio clip – Resize the applet • Additionally.

Abstract Windows Toolkit Class Hierarchy .

Panel: The Panel is the container that doesn't contain title bar and menu bars.applet. Panel Window: The window is the container that have no borders and menu bars.Graphics.Applet.awt. Java AWT components are platform-dependent i.e. There is no limit to the number of components a Container may hold. Dialog. dialog or another window for creating a window. Component is an abstract class. It can have other components like button. Eg: Frame. Eg: buttons. AWT is heavyweight i. Components added to a Container are added to the end of the list unless an index position is specified.  A frame may also have scroll bars. . checkboxes.applet package contains a class Applet which uses various interfaces such as AppletContext. textfield and scrollbars. components are displayed according to the view of operating system. its components uses the resources of system.e.. The java. Window. It can have other components like button. Component: A component is an object with a graphical representation that can interact with the user. You must use frame. but they also contain code for event handling and many 'niceties' such as controlling the cursor image and the application's icon. textfield etc. The Frame is the container that contain title bar and can have menu bars. Containers: A Container is a Component used to hold and organize components together for display purposes. java. a menu bar. The applet class is an extension of Panel class belonging to java. Container is an abstract class. The Abstract Windowing Toolkit (AWT): Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based application in java.Hierarchy of Applet Class • • • • • • • These import statements bring the classes into the scope of our applet class: java.awt package. list. AppletStub and AudioCIip. textfield etc. etc. Frame: A frame is a top-level window with a title and a border.

3. public void paint(Graphics g): is used to paint the Applet. It is invoked when Applet is stop or browser is minimized. Applet is painted. Applet is destroyed. rectangle. Applet is initialized.Applet class provide 4 life cycle methods and java.Lifecycle of Java Applet 1. 5. It is used to start the Applet. 4. public void init(): is used to initialized the Applet. . It is invoked only once.Component class provides 1 life cycle methods(paint method) for an applet. public void start(): is invoked after the init() method or browser is maximized. arc etc. public void stop(): is used to stop the Applet.applet. The java. It is invoked only once. Applet is started. Applet is stopped. It provides Graphics class object that can be used for drawing oval. 2.awt. public void destroy(): is used to destroy the Applet.

Windows. Disadvantages of Applet – Plugin is required at client browser to execute applet. Mac Os etc.Advantages and disadvantages of Applets Advantages of applets – It works at client side so less response time. – Secured – It can be executed by browsers running under many platforms. including Linux. .

To execute the applet by html file.class" width="300" height="300">  </applet>  */   . create an applet that contains applet tag in comment and compile it.class" width="300" height="300">   </applet>   </body> </html>   – By appletViewer tool (for testing purpose). /*  <applet code="Filename. Now open the html file using any java enabled web browser. After that create an html file and place the applet code in html file. After that run it by: appletviewer Filename. class must be public because its object is created by Java Plugin software that resides on the browser. create an applet and compile it. <html>   <body>   <applet code="Filename. If Html tag is used run it by: appletviewer Filename.Running an applet • There are two ways to run an applet – By html file.html. To execute the applet by appletviewer tool.java.

is visible in non-Java-enabled browsers. the holding package must be specified in the code attribute using the period character (.subpackage.  .TestApplet. values may be passed for the parameters by adding <param> tags between <applet> and </applet>.class" width="320" height="120"> • If an applet takes parameters. For example: <applet code="mypackage. To specify otherwise. • The viewer or browser looks for the compiled Java code at the location of the document. Therefore.Running an applet • Non-Java-enabled browsers do not process <applet> and </applet>.) to separate package/class components.com/applets" code="HelloWorldApplet. not related to the applet. use the codebase attribute of the <applet> tag as shown: <applet codebase="http://amrood.class" width="320" height="120"> • If an applet resides in a package other than the default. anything that appears between the tags.

• public abstract void setFont(Font font): is used to set the graphics current font to the specified font. • public abstract void drawOval(int x. int height): draws a rectangle with the specified width and height. y2). int width. Font f = new Font("Helvetica". . g. int y2): is used to draw line between the points(x1. int y): is used to draw the specified string. int arcAngle): is used draw a circular or elliptical arc. int height): is used to draw oval with the specified width and height. setBackground(lightOrange).blue).Commonly used methods of Graphics class: • public abstract void drawString(String str. int width. int y. g. 220. int y1. int x2. int y. • public abstract void drawArc(int x. ImageObserver observer): is used draw the specified image. int arcAngle): is used to fill a circular or elliptical arc.setColor (Color. 0).BOLD.setFont(f). int startAngle. int height. • public abstract void fillRect(int x. int width. int height): is used to fill rectangle with the default color and specified width and height. Font. int startAngle. int y. int width. • public abstract boolean drawImage(Image img. • public abstract void drawLine(int x1. int width. • public void drawRect(int x. • public abstract void fillOval(int x. Color lightOrange = new Color(230. int y. int width. y1) and (x2. int x. int height. • public abstract void fillArc(int x. int x. int y.20). • public abstract void setColor(Color c): is used to set the graphics current color to the specified color. int y. int height): is used to fill oval with the default color and specified width and height. int y.

 String image){}   • java. It provides getApplet() method that returns the object of Applet. ImageObserver observer): is used draw the specified image.To display an image •  The java.Graphics class provide a method drawImage() to display the image.AppletContext class provides the facility of communication between applets.applet.awt. int x. int y. Syntax:public Applet getApplet(String name){}   . We provide the name of applet through the HTML file. public abstract boolean drawImage(Image img. • The java. Syntax: public Image getImage(URL u.Applet class provides getImage() method that returns the object of Image.applet.

– Height (h).Screen Coordinates are used for Positioning Graphics • A point on the screen is a picture element (pixel).  The pixel is positioned at the intersection of its horizontal and vertical coordinates.  Each increase in the value of vert moves the pixel further to the bottom.  Increasing the value of horiz moves the pixel further to the right. –  The vertical coordinate (vert) starts as zero at the top.  – The horizontal coordinate (horiz) starts as zero at the left. As w increases. – Width (w). the object is wider.  As h increases.   • The width and height of a graphic object is measured in pixels. the object is taller. .

                g.Color.drawString("This is my First Applet". 10. import java.Color.Graphics.awt.Graphics.}         } }   /* <HTML> <HEAD> </HEAD> <BODY>         <applet code = "BasicAppletExample" width = 200 height = 200>         </applet> </BODY> </HTML> */ To Compile: : javac . public class BasicAppletExample extends  Applet{              public void paint(Graphics g){                 //write text using drawString method of Graphics class                 g.setColor(c[i]). 10 + (i*10)).blue. import java.Co lor.awt.                 for(int i = 0.drawString("This is my First Applet".green}.applet. i++){ g.Example  import java.cyan.Applet.darkGray.Color.Color.length.awt. import java.awt. public class BasicAppletExample extend s Applet{              public void paint(Graphics g){ Color c[] = {Color. i<c.applet. 10 + (i*10)).}         } }   /*         <applet code = "BasicAppletExample" width = 200 height = 200>         </applet> */  import java.gray.Applet. import java.10.Color.

Altogether there are more than 250 new classes and 75 interfaces in Swing — twice as many as in AWT. • It is a part of Java Foundation Classes (JFC) that is used to create window-based applications. which is an extension library to the AWT. JLabel.Swing • Swing. • Swing is more portable and more flexible than AWT. Some examples are JButton. • In Swing. Java Swing provides platform-independent and lightweight components. . • Swing can be used to build Standalone swing gui Apps as well as Servlets and Applets. and JSlider. classes that represent GUI components have names beginning with the letter J. includes new and improved components that enhance the look and functionality of GUIs. • It employs a model-view-control architecture.

Swing Features • • • • • • • Pluggable Look & Feel Rich controls Highly Customizable Lightweight components Uses MVC Architecture 100% Java implementation of components Three parts  Component set (subclasses of JComponent) Support classes Interfaces .

• Controller takes the input from the user on the view and reflects the changes in Component's data. The “model part” of the MV design is implemented by a model object and a change listener object. Swing has pluggable look-and-feel architecture. • Swing component have Model as a seperate element and View and Controller part are clubbed in User Interface elements. Using this way. The “view part” of the MV design is implemented with a component object and the UI object. • A Model represents component's data. • View represents visual representation of the component's data. .Swing Model-view-Control Architecture • Model represents the data. View as a visual representation of the data and Controller takes input and translates it to changes in data .

descended directly from Container. .Java Swing class hierarchy • The class JComponent. is the root class for most of Swing’s user interface components.

UI Components of SWING Class • • • • • JPanel is Swing’s version of the AWT class Panel and uses the same default layout. buttons. If you want to display a string or an image on a frame. these are the text boxes where user enters the data. you can do so by using labels.The components added to the frame are referred to as its contents. these are managed by the contentPane. JPasswordField (a direct subclass of JTextField) you can suppress the display of input. and to set the text’s font. descended from JComponent.  Frame is a window that can have title. A Swing application must have a frame to have the components added to it. menu. Panels are useful for grouping components and placing them to appropriate locations in a frame. right. border. Similar to text fields but the entered data gets hidden and displayed as dots on GUI. A label is unselectable text and images. is used to create text labels.New features include the ability to justify the text left. JPanel is descended directly from JComponent. or center. we must use its contentPane instead. FlowLayout. JFrame is Swing’s version of Frame and is descended directly from that class. To add a component to a JFrame. JLabel. .  JTextField allows editing of a single line of text. Used for capturing user inputs. text fields and several other components. Each character entered can be replaced by an echo character.

The underlying JScrollPane can be forced to always or never have either the vertical or horizontal scrollbar. All dialogs are modal. pressing a key that corresponds to the first character in some entry’s name selects that entry. the list must be associated with a scrollpane. JDialog contains a rootPane hierarchy including a contentPane. JButton is a component the user clicks to trigger a specific action. The view port used by the scroll pane can also have a user-defined border. Like JFrame and JWindow. • JComboBox is like a drop down box. JList does not support scrolling directly. JTextArea can be used in conjunction with class JScrollPane to achieve scrolling. • JList . A vertical scrollbar is used for longer lists.provides a scrollable set of items from which one or more may be selected. It can be iconified . JList actions are handled using ListSelectionListener. it uses BorderLayout by default. which means the current thread is blocked until user interaction with it has been completed. JDialog class is intended . A set of radio buttons can be associated as a group in which only one button at a time can be selected.UI Components of SWING Class • JTextArea allows editing of multiple lines of text. Like Dialog. • JDialog is Swing’s version of Dialog and is descended directly from that class. except for the default icon for each class. • JRadioButton is similar to JCheckbox. • JInternalFrame is confined to a visible area of a container it is placed in. and it also displays its current state. Like Window. JList can be populated from an Array or Vector. maximized and layered. and it allows layered and glass panes. You can click a drop-down arrow and select an option from a list. • JCheckBox is not a member of a checkbox group. • JWindow is Swing’s version of Window and is descended directly from that class. it uses BorderLayout by default. instead. when the component has focus. For example. A checkbox can be selected and deselected.

and one component is placed in each rectangle. Each component in a FlowLayout gets as much space as it needs and no more. called its display area. • JTabbedPane contains a tab that can have a tool tip and a mnemonic. • Scrollable JPopupMenu is a scrollable popup menu that can be used whenever . The display area aligns components vertically and horizontally. East. West and center of a container. The container is divided into equal-sized rectangles.UI Components of SWING Class • JToolbar contains a number of components whose type is usually some kind of button which can also include separators to group related components within the toolbar. • FlowLayout when used arranges swing components from left to right until there’s no more space available. • GridBagLayout is a layout manager that lays out a container’s components in a grid of cells with each component occupying one or more cells. Swing provides support for pull-down and popup menus. • GridLayout is a layout manager that lays out a container’s components in a rectangular grid. Each of the JMenu’s can contain a series of JMenuItem ‘s that you can select. • JMenubar can contain several JMenu’s. • BorderLayout places swing components in the North. South. without requiring that the components be of the same size. Then it begins a new row below it and moves from left to right again. and it can display both text and an image. You can add horizontal and vertical gaps between the areas.

3 public void setLayout(LayoutManager m) sets the layout manager for the component.Commonly used Methods of Component class SI N O Method 1 public void add(Component c) add a component on another component. 2 public void setSize(int width. It is by default false.int height) sets size of the component. 4 public void setVisible(boolean b) sets the visibility of the component. Description There are two ways to create a frame: •By creating the object of Frame class (association) •By extending Frame class (inheritance) .

165.          panel.add(userText).           JPasswordField passwordText = new JPasswordField(20).JPanel.      frame.setLayout(null).setBounds(10.         userText.         panel.        passwordLabel.50.Example import javax.JFrame.add(passwordLabel).JTextField. import javax.setBounds(100.     }     private static void placeComponents(JPanel panel) {        panel.setSize(350.25).                frame.JLabel.EXIT_ON_CLOSE).          loginButton.JButton.20.add(passwordText).80.swing.         panel.80.               frame.50.          panel.add(panel).20.swing. import javax.setBounds(10. import javax.JPasswordField.165.setDefaultCloseOperation(JFram e.add(userLabel).         JTextField userText = new JTextField(20).              placeComponents(panel).setBounds(10.add(loginButton).                  JLabel userLabel = new JLabel("User").         panel. public class SwingFirstExample {          public static void main(String[] args) {                    JFrame frame = new JFrame("My First Swing Example"). 25).          frame.200). import javax.25).25).     } } .                JPanel panel = new JPanel().swing. I mport javax.setVisible(true).setBounds(100.        JButton loginButton = new JButton("login").swing.          passwordText. 80.swing.         userLabel.25). 80.          JLabel passwordLabel = new JLabel("Password").swing.

the listener process the event an then returns. For example.e.It is also known as event handler.  – Listener . Listener is responsible for generating response to an event. Source is responsible for providing information of the occurred event to it's handler. From java implementation point of view the listener is also an object. Events are generated as result of user interaction with the graphical user interface components.The source is an object on which event occurs. • The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. • The Delegation Event Model has the following key participants namely: – Source .Event Handling • Change in the state of an object is known as event i. Once the event is received .  • Java Uses the Delegation Event Model to handle the events. event describes the change in state of source. This is an efficient way of handling the event because the event notifications are sent only to those listener that want to receive them. . Java provide as with classes for source object.Listener needs to be registered with the source object so that the listener can receive the event notification. • Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. clicking on a button.  • In this model . Listener waits until it receives an event. – The Event object (Event) encapsulates the state changes in the event source.

called ActionEvents. the ÄctionListener" is appropriate. – register this object with the event detector. and it sends notices to the listeners.add<EventType>Listener(<listenerObject>).Event Handling • Some subclasses of Event are ActionEvents  and  WindowEvents. there are seven kinds of WindowEvents. we need to do three things: – Implement the listener interface using ANY reasonable class. // button is the event detector. Buttons detects only one type of event . The general form for registering listener objects is: <eventDetector>. In our example. • For buttons. and their relationship:  – Event Detectors:  The former is set up to detect the occurence of certain types of event. you need to consider two types of interfaces. – Create a listener object: Listener lis = new MyPanel(). To implement the ActionListener. you need to supply the methodactionPerformed(ActionEvent) (the only method of this interface). It is the listeners that take the appropriate action. Examples of Event Detectors are windows or buttons. In contrast.addActionListener(lis). button. . • To understand events. the class will be an extension of JPanel.  –  Event Listeners. But in order for the event objects to know which listener object to send the events to.

awt. 7 AdjustmentEventThe object of this class represents the adjustment event emitted by Adjustable objects. 8 ComponentEventThe object of this class represents the change in state of a window. 6 WindowEventThe object of this class represents the change in state of a window. 5 MouseEventThis event indicates a mouse action occurred in a component.Event Classes SiN Control & Description o 1 AWTEventIt is the root event class for all SWING events.Event class. . 2 ActionEventThe ActionEvent is generated when button is clicked or the item of a list is double clicked. This class and its subclasses supercede the original java. 4 KeyEventOn entering the character the Key event is generated. 3 InputEventThe InputEvent class is root event class for all componentlevel input events.

This class is defined in java. If you do not implement the any if the predefined interfaces then your class can not act as a listener class for a source object. These Listener interfaces forecast some public abstract callback methods which must be implemented by the listener class. In order to design a listener class we have to develop some listener interfaces.Event Listener Interfaces • The Event listener represent the interfaces responsible to handle events. mouse event listener methods will accept instance of MouseEvent. . • Every method of an event listener method has a single argument as an object which is subclass of EventObject class. where MouseEvent derives from EventObject.util package. • Event Listener Inerface is a marker interface which every listener interface has to extend. For example.

5 MouseListenerThis interface is used for receiving the mouse events. 4 KeyListenerThis interface is used for receiving the key events. 2 ComponentListenerThis interface is used for receiving the component events.SWING Event Listener Interfaces Si No Control & Description 1 ActionListenerThis interface is used for receiving the action events. 8 ContainerListenerThis interface is used for receiving the . 6 WindowListenerThis interface is used for receiving the window events. 3 ItemListenerThis interface is used for receiving the item events. 7 AdjustmentListenerThis interface is used for receiving the adjusmtent events.

Adapter Classes •Adapters are abstract classes for receiving various events. . The methods in these classes are empty. 5 WindowAdapterAn abstract adapter class for receiving window events. These classes exists as convenience for creating listener objects. 4 MouseMotionAdapterAn abstract adapter class for receiving mouse motion events. 3 MouseAdapterAn abstract adapter class for receiving mouse events. 1 FocusAdapterAn abstract adapter class for receiving focus events. Sr. 2 KeyAdapterAn abstract adapter class for receiving key events. Adapter & Description No. Following is the list of commonly used adapters while listening GUI events in SWING.

add(headerLabel). headerLabel = new JLabel("". okButton.exit(0).addActionListener(new ButtonClickListener()).equals( "OK" )) { statusLabel. private JLabel headerLabel.package com.tutorialspoint.awt. mainFrame.getActionCommand().setText("Submit Button clicked.CENTER ). } private class ButtonClickListener implements ActionListener{ public void actionPerformed(ActionEvent e) { String command = e. statusLabel.add(statusLabel). JButton okButton = new JButton("OK"). import java.setText("Control in action: Button"). } . controlPanel. mainFrame. controlPanel. cancelButton. Example public SwingControlDemo(){ prepareGUI().setActionCommand("Submit").equals( "Submit" ) ) { statusLabel.addActionListener(new ButtonClickListener()).setVisible(true). mainFrame. swingControlDemo. } public static void main(String[] args){ SwingControlDemo swingControlDemo = new SwingControlDemo(). JButton submitButton = new JButton("Submit"). import java. statusLabel = new JLabel("". controlPanel. } private void showEventDemo(){ headerLabel. submitButton.add(okButton).setActionCommand("Cancel"). public class SwingControlDemo { private JFrame mainFrame.setLayout(new FlowLayout()). if( command.*.CENTER).addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System. cancelButton.setLayout(new GridLayout(3. JButton cancelButton = new JButton("Cancel").awt. mainFrame.JLabel. 1)).*.setSize(400.showEventDemo(). mainFrame.setActionCommand("OK").event.JLabel. mainFrame. mainFrame.setText("Ok Button clicked.add(cancelButton). private JPanel controlPanel.add(controlPanel). import javax. } private void prepareGUI(){ mainFrame = new JFrame("Java SWING Examples"). } }).addActionListener(new ButtonClickListener()). submitButton.setSize(350.").*.").400). okButton. controlPanel. mainFrame.add(submitButton).gui.swing.setVisible(true). } else if( command. private JLabel statusLabel.100). controlPanel = new JPanel().

NetBeans IDE • the NetBeans IDE is a free. cross-platform integrated development environment with builtin support for the Java programming language. opensource. It offers many advantages over coding with a text editor .

ODBC API was the database API to connect and execute query with the database. • JDBC Driver is a software component that enables java application to interact with the database. But. That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language). • Before JDBC. platform dependent and unsecured). . JDBC API uses jdbc drivers to connect with the database. ODBC API uses ODBC driver which is written in C language (i.JAVA JDBC Connectivity • Java JDBC is a java API to connect and execute query with the database.e.

JAVA JDBC Connectivity • There are 4 types of JDBC drivers: 1. JDBC-ODBC bridge driver Native-API driver (partially java driver) Network Protocol driver (fully java driver) Thin driver (fully java driver) • There are 6 steps to connect any java application with the database in java using JDBC.import java. The Connection object uses aDriverManager.“usrnm". 3. –.sql. and the location of the database. Eg: Class. Creating connection: To connect to a database you need a Connection object.import java. These 3 import statements should be present.“pwd") .sql.Connection. –. Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. 2.SQLException.import java. The DriverManager passes in your database username. your password.forName("com. The getConnection() method of DriverManager class is used to establish connection with the database.jdbc.DriverManager. ("jdbc:mysql://localhost:3306/dbname". 2.Driver"). 3. –. Register the driver class: The forName() method of Class class is used to register the driver class. Eg: Connection con=DriverManager. They are as follows: 1.mysql. 4.sql. This method is used to dynamically load the driver class.

   }   5. Closing connection: By closing connection object statement and ResultSet will be closed automatically.   . The close() method of Connection interface is used to close the connection.They also define methods that help bridge data type differences between Java and SQL data types used in a database.getString(2)).executeQuery("select * from emp"). and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands and receive data from your database. CallableStatement. The object of statement is responsible to execute queries with the database.createStatement().out.JAVA JDBC Connectivity 3. Eg: Statement stmt=con.close().getInt(1)+" "+rs. The JDBCStatement.println(rs. Executing queries: The executeQuery() method of Statement interface is used to execute queries to the database. Eg: con.next()){   System. This method returns the object of ResultSet that can be used to get all the records of a table.Eg: ResultSet rs=stmt.      while(rs. Creating statement: The createStatement() method of Connection interface is used to create statement.   4.

localhost is the server name on which mysql is running. localhost is the server name on which oracle is running. • Username: The default username for the mysql database is root. You may get all these informations from the tnsnames.OracleDriver. we may also use IP address.Driver. we are going to use root as the password. in such case.mysql. thin is the driver. 1521 is the port number and XE is the Oracle service name. you need to replace the sonoo with your database name. • Username: The default username for the oracle database is system.JAVA JDBC Connectivity for the mysql database: • Driver class: The driver class for the mysql database is com. oracle is the database. mysql is the database. .ora file. we may also use IP address. • Connection URL: The connection URL for the oracle10G database is jdbc:oracle:thin:@localhost:1521:xewhere jdbc is the API.jdbc.  for the oracle database: • Driver class: The driver class for the oracle database is oracle.driver. • Password: Password is given by the user at the time of installing the mysql database. 3306 is the port number and sonoo is the database name. • Password: Password is given by the user at the time of installing the oracle database.jdbc. • Connection URL: The connection URL for the mysql database is jdbc:mysql://localhost:3306/sonoo where jdbc is the API. We may use any database. In this example.

JAVA JDBC Connectivity • The DriverManager class acts as an interface between user and drivers.String userName.3) public static Connection getConnection(String url):is used to establish the connection with the specified url. . The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver(). • Commonly used methods of DriverManager class: • 1) public static void registerDriver(Driver driver):is used to register the given driver with DriverManager.2) public static void deregisterDriver(Driver driver):is used to deregister the given driver (drop the driver from the list) with DriverManager. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. username and password.String password):is used to establish the connection with the specified url.4) public static Connection getConnection(String url.

it provides factory method to get the object of ResultSet. it may be create. 4) public int[] executeBatch(): is used to execute batch of commands. insert.e. delete etc 3) public boolean execute(String sql): is used to execute queries that may return multiple results. • The important methods of Statement interface are as follows: 1) public ResultSet executeQuery(String sql): is used to execute SELECT query.rollback() etc. and DatabaseMetaData i. The Connection interface is a factory of Statement. .e.JAVA JDBC Connectivity • A Connection is the session between java application and database. PreparedStatement. object of Connection can be used to get the object of Statement and DatabaseMetaData. • Statement interface:The Statement interface provides methods to execute queries with the database. It returns the object of ResultSet 2) public int executeUpdate(String sql): is used to execute specified query. drop. update. The statement interface is a factory of ResultSet i. The Connection interface provide many methods for transaction management like commit().

• Let's see the example of parameterized query: • String sql="insert into emp values(?. • Why use PreparedStatement? • Improves performance: The performance of the application will be faster if you use PreparedStatement interface because query is compiled only once. It is used to execute parameterized query. we are passing parameter (?) for the values.PreparedStatement interface • The PreparedStatement interface is a subinterface of Statement.   • As you can see.?)".?. . Its value will be set by calling the setter methods of PreparedStatement.

public ResultSet executeQuery() executes the select query. public void setFloat(int paramIndex. update.Methods of PreparedStatement interface Method Description public void setInt(int paramIndex. sets the integer value to the given int value) parameter index. String value) sets the String value to the given parameter index. insert. public void setDouble(int paramIndex. public int executeUpdate() executes the query. delete etc. drop. float value) sets the float value to the given parameter index. It returns an instance of ResultSet. . It is used for create. double value) sets the double value to the given parameter index. public void setString(int paramIndex.

      //here sonoo is database name.jdbc.createStatement().Driver").mysql.}      }   .getInt(1)+"  "+rs.      con.out.forName("com.println(e).getConnection(   "jdbc:mysql://localhost:3306/sonoo".*.executeQuery("select * from emp").      while(rs.getString(2)+"  "+rs.   class MysqlCon{   public static void main(String args[]){   try{   Class.println(rs.      }catch(Exception e){ System.close().sql.Example import java.      Connection con=DriverManager.out."root". root is username and password      Statement stmt=con."root").getString(3)).      ResultSet rs=stmt.next())   System.