Category: Java Tutorial

  • Java – File Class with Example

    Java file Class deals directly with the file and file system. That is, it is the abstract representation of file or directory pathname. It defines the properties of the file itself rather than describing how information is stored in or retrieved from files.

    File class contains various methods for working with the pathname, deleting and renaming files, creation of new directories, and many more. A file object is created to manipulate with disk’s permissions, time, date, and directory path, etc.

    Create File Object:

    A File object is created as shown below,

     File f = new File("/user/pusp/simple2code"); 

    To create a file object, the following constructor can be used:

    • File(File parent, String child):
      Creates a new File instance from a parent abstract pathname and a child pathname string.
    • File(String pathname):
      Creates a new File instance by converting the given pathname string into an abstract pathname.
    • File(String parent, String child):
      Creates a new File instance from a parent pathname string and a child pathname string.
    • File(URI uri):
      Creates a new File instance, URI into an abstract pathname.

    Some Useful Methods:

    • static File createTempFile(String prefix, String suffix): This method is used to create an empty file in the default temporary-file directory.
    • boolean canRead(): This method is used to test whether the application can read the file denoted by this abstract pathname.
    • boolean canWrite(): This method is used to test whether the application can modify the file denoted by this abstract pathname.
    • boolean delete(): This method is used to delete the file or directory denoted by this abstract pathname.
    • boolean createNewFile(): This method is used for atomically creating a new, empty file named by this abstract pathname.
    • boolean canExecute(): Method is used to test whether the application can execute the file denoted by this abstract pathname.
    • boolean isDirectory(): Method is used to test whether the file denoted by this pathname is a directory.
    • boolean isFile(): Method is used to test whether the file denoted by this abstract pathname is a normal file.
    • String getName(): Method is used to return the name of the file or directory denoted by this abstract pathname.
    • String getParent(): Method is used to return the pathname string of this abstract pathname’s parent.
    • boolean mkdir(): Method is used to create the directory named by this abstract pathname.
    • URI toURI(): Method is used to construct a file URI that represents this abstract pathname.
    • File[] listFiles(): Method is used to return an array of abstract pathnames denoting the files in the directory.

    Java Program example to demonstrate Files Class

    To check whether the new file is created or it already exists:

     import java.io.*;  
    
      public class FileCreated 
      {  
       public static void main(String[] args) 
       {  
    
        try {  
        File file = new File("javaCode.txt");  
        if (file.createNewFile()) {  
            System.out.println("New File is created.");  
        } else {  
            System.out.println("File already exists.");  
        }  
        } catch (IOException e) {  
          e.printStackTrace();  
        }  
    
       }  
      }

    Output:

     New File is created.

    A new text file named ‘javaCode.txt‘ will be created at the same directory where you saved the java file.


  • Java – Files I/O

    Java Input/Output is used for processing input and giving out output. The package java.io contains all the required classes needed for input/output operation. Java uses the term stream for the representation of I/O operation.

    Stream

    A stream is a sequence of data. A stream supports many data such as primitives, objects, localized characters, objects, etc. Java’s stream-based I/O is built upon four abstract classes: InputStream, OutputStream, Reader, and Writer.

    The two types of stream, we will be looking at are:

    • Byte Stream
    • Character Stream

    Byte stream :

    The byte stream classes provide a convenient means for handling byte-oriented I/O. The byte stream classes are topped by InputStream and OutputStream among many other classes.

    InputStream:

    InputStream is an abstract class that defines Java’s model of streaming byte input. It implements the Closeable interface.

    Some of the methods defined by InputStream are:

    • int available():
      Returns the number of bytes of input currently available for reading.
    • void close():
      Closes the input source. Further read attempts will generate an IOException.
    • void mark(int numBytes):
      Places a mark at the current point in the input stream that will remain valid until numBytes bytes are ready.
    • int read():
      Returns an integer representation of the next available byte of input. –1 is returned when the end of the file is encountered.
    • int read(byte buffer[], int offset, int numBytes):
      Attempts to read up to numBytes bytes into the buffer starting at buffer [ offset ], returning the number of bytes successfully read. –1 is returned when the end of the file is encountered.
    • void reset():
      Resets the input pointer to the previously set mark.

    OutputStream:

    OutputStream is an abstract class that defines streaming byte output. It implements the Closeable and Flushable interfaces.

    Some of the methods defined by OutputStream:

    • void close():
      Closes the output stream.
    • void flush():
      Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers.
    • void write(byte buffer[]):
      Writes a complete array of bytes to an output stream.
    • void write(int b):
      Writes a single byte to an output stream.

    FileInputStream:

    The File InputStream class creates an InputStream that you can use to read bytes from a file. These streams of raw bytes include image data, audio, video, etc.

    FileOutputStream:

    FileOutputStream creates an OutputStream that you can use to write bytes to a file.


    Character Stream:

    These streams are used to perform for a 16-bit Unicode. It provides a convenient means for handling the input and output of characters. At the top of the character stream hierarchies are the Reader and Writer abstract classes.

    Reader:

    Reader is an abstract class that defines Java’s model for reading character stream. It implements the Closeable(close()) and Readable (read(char[], int, int)) interfaces. All of the methods in this class will throw an IOException on error conditions.

    Some of the methods defined by Reader:

    • abstract void close():
      Closes the input source.
    • void mark(int numChars):
      Places a mark at the current point in the input stream that will remain valid until numChars characters are read.
    • boolean markSupported():
      Returns true if mark()/reset() are supported on this stream.
    • int read():
      Returns an integer representation of the next available character from the invoking input stream. –1 is returned when the end of the file is encountered.
    • int read(char buffer[]):
      Attempts to read up to buffer. length characters into buffer and returns the actual number of characters that were successfully read. –1 is returned when the end of the file is encountered.
    • boolean ready()
      Returns true if the next input request will not wait. Otherwise, it returns false.
    • void reset():
      Resets the input pointer to the previously set mark.

    Writer:

    Writer is an abstract class that defines Java’s model for writing character stream. It implementsthe Closeable(close()), Flushable(flush()) and Appendable(char[], int, int) interfaces.

    Some of the methods defined by Writer:

    • Writer append(char c):
      Appends c to the end of the invoking output stream. Returns a reference to the invoking stream.
    • abstract void close():
      Closes the output stream.
    • abstract void flush():
      Finalizes the output state so that any buffers are cleared. That is, it flushes the output buffers.
    • void write(int ch):
      Returns an integer representation of the next available character from the invoking input stream. –1 is returned when the end of the file is encountered. Writes a single character to the invoking output stream.
    • Writer append(CharSequence chars):
      Appends chars to the end of the invoking output stream. Returns a reference to the invoking stream.

    FileReader:

    For the reading purposes present on the file, the FileReader creates a class call Reader. It returns data in byte format like FileInputStream class.

    Two commonly used constructor in FileReader are

    • FileReader(String filePath)
    • FileReader(File fileObj)

    Methods used in FileReader:

    • int read(): return a character in ASCII form, returns -1 at the end of file.
    • void close(): close the FileReader class.

    Example: Java program for File I/O.

    The following example is to read lines and print these to the standard output stream from a file. The source file must be in the current directory.

    import java.io.*;
    
      class FileReader 
      { 
       public static void main(String args[]) throws IOException 
       { 
    
        FileReader fr=new FileReader("fileTest.txt");    
        int i;    
        while((i=fr.read())!=-1) 
        {   
         System.out.print((char)i);
        }    
        fr.close();   
       }
      } 

    We have the following text in “fileTest.txt“:

    Welcome to Simple 2 Code

    Output:

    Welcome to Simple 2 Code


    FileWriter:

    For the writing purposes present on the file, the FileWriter creates a class call Reader. It returns data in byte format like FileOutputStream class.

    Four commonly used constructors in FileWriter are:

    • FileWriter(String filePath)
    • FileWriter(String filePath, boolean append)
    • FileWriter(File fileObj)
    • FileWriter(File fileObj, boolean append)

    Methods used in FileWriter:

    • void write(String text): to write the string into FileWriter.
    • void write(char c): to write the char into FileWriter.
    • void write(char[] c): to write char array into FileWriter.
    • void flush(): to flushes the data of FileWriters.
    • void close(): to close the FileWriter.

    Example: Java program for File I/O.

    The following example is to write lines and print these to the standard output stream from a file. The source file must be in the current directory.

     import java.io.FileWriter; 
    
      public class FileWriter 
      {  
       public static void main(String args[])
       {    
        try{    
        FileWriter f = new FileWriter("WriterTest.txt");    
        f.write("Welcome to Simple2Code.");    
        f.close();
        
       }catch(Exception e){
         System.out.println(e);
        }    
       System.out.println("Done");    
       }    
      }  

    Output:

    Done

    Now check the text file, “WriterTest.txt” in the same directory.

    Welcome to Simple2Code.

    Example: Use of BufferReader in Java

     import java.io.*;
      
      class FileReaderBuffer 
      { 
       public static void main(String args[]) throws IOException 
       { 
        FileReader fr = new FileReader("FileReaderDemo.java"); 
        BufferedReader br = new BufferedReader(fr); 
        String s;
        while((s = br.readLine()) != null) 
        { 
         System.out.println(s); 
        }
        fr.close();
       }
      } 

  • Java – Applet, Life Cycle of Applet and Methods

    The applet in Java is a special type of internet-based program, that runs on the web browser and works at the client-side. It is used to make the webpage more dynamic and provide interactive features that cannot be applied by the HTML alone.

    • Any applet in Java is a class that extends the java.applet.Applet class.
    • An Applet class does not contain the main() method.
    • JVM(Java Virtual Machine) is needed to view an applet. To run an applet application, the JVM can use either a plug-in of the Web browser or a separate runtime environment.

    Some of the benefits of using Java Applet:

    1. It is secured. It runs in Sandbox which is a Byte-code verifier.
    2. Since it works at the client side so less response time.
    3. It can be executed by the browsers that are running under any platform.

    One of the Drawbacks of Java Applet is that for executing applets, plugins are required at the client browser.


    Life Cycle of a Java Applet

    Java Applet
    Java Appplet

    The various stages that an Applet undergoes from its creation to its destruction of objects is known as the Applet life cycle.

    Applet life cycle consists of 5 states and each of the states is a signified method and called callback methods.

    Following are the states in Applet:

    init() method: This method is used for the initialization of an Applet. It is only executed once in a program.

    start() method: This method is used to start the Applet and called automatically after the JVM calls init() method. It can be called repeatedly.

    paint() method: This method is called immediately after the start(). It is inherited from java.awt, used to paint the object providing the graphic class object.

    stop() method: This method is called automatically to stop the Applet. It can also be called repeatedly in the same applet.

    destroy() method: This method is used to destroy the Applet and also executed only once in the program.


    Applet Class:

    All the Applet present is an extension of the java.applet.Applet class. These classes are necessary for the execution of an applet. They include various methods for the applet such as methods to fetch and display images and play an audio clip, resize an applet, to get applet parameters, etc.

    Demonstrate a simple Applet example in Java.

     import java.applet.Applet;
      import java.awt.Graphics;
      public class FirstApplet extends Applet 
      {
       public void paint(Graphics g) 
       {
        g.drawString("First Applet Program", 20, 15);
       }
      }

    After saving this code with ‘FirstApplet.java‘. We need to create an HTML file to include this applet. Create an HTML file named first.html within the same folder where you have saved the FirstApplet.java.

    <html>
    
      <head>
        <TITLE> A Simple First Program </TITLE>
      </head>
    
      <body>
        The output:
        
      </body>
    
      </html>

    Display Methods in Applet:

    As we know applet is displayed in a window and for the input/output operations, they use AWT. To output a string, we use drawString().

    The general form for drawString():

     void drawString(String message, int x, int y)

    In the above form, this method is written, beginning at x,y which is the location we want the line to begin. This is a graphics class.

    • To set a background color of an applet’s window, we use setBackground().
    • To set the foreground color, we use setForeground().

    The general form of setBackground() and setForeground() are:

     void setBackground(Color newColor)
     void setForeground(Color newColor)
     //Here "newColor" denotes the new color.

    The class Color defines the constants shown here that can be used to specify colors:

    •   Color.black
    •   Color.blue
    •   Color.cyan
    •   Color.darkGray
    •   Color.gray
    •   Color.green
    •   Color.lightGray
    •   Color.magenta
    •   Color.orange
    •   Color.pink
    •   Color.red
    •   Color.white
    •   Color.yellow

    The following shows the source code on how to display background color.

     setBackground(Color.blue);
    
     setForeground(Color.yellow);

    Note:
    The default foreground color is black and the default background color is light gray.


  • Java – Awt Control Demo

    This a Demo Example AWT (Abstract Window Toolkit) Control in Java.

        import java.awt.*;
        import java.awt.event.*;
        
        public class AwtControlDemo {
        
            private Frame mainFrame;
            private Label headerLabel;
            private Label statusLabel;
            private Panel controlPanel;
        
            public AwtControlDemo(){
                prepareGUI();
            }
        
            public static void main(String[] args){
                AwtControlDemo  awtControlDemo = new AwtControlDemo();
                awtControlDemo.showEventDemo();
            }
        
            private void prepareGUI(){
                mainFrame = new Frame("Java AWT Examples");
                mainFrame.setSize(400,400);
                mainFrame.setLayout(new GridLayout(3, 1));
                mainFrame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent windowEvent){
                    System.exit(0);
                    }        
                });    
                headerLabel = new Label();
                headerLabel.setAlignment(Label.CENTER);
                statusLabel = new Label();        
                statusLabel.setAlignment(Label.CENTER);
                statusLabel.setSize(350,100);
        
                controlPanel = new Panel();
                controlPanel.setLayout(new FlowLayout());
        
                mainFrame.add(headerLabel);
                mainFrame.add(controlPanel);
                mainFrame.add(statusLabel);
                mainFrame.setVisible(true);  
            }
        
            private void showEventDemo(){
                headerLabel.setText("Control in action: Button"); 
        
                Button okButton = new Button("OK");
                Button submitButton = new Button("Submit");
                Button cancelButton = new Button("Cancel");
        
                okButton.setActionCommand("OK");
                submitButton.setActionCommand("Submit");
                cancelButton.setActionCommand("Cancel");
        
                okButton.addActionListener(new ButtonClickListener()); 
                submitButton.addActionListener(new ButtonClickListener()); 
                cancelButton.addActionListener(new ButtonClickListener()); 
        
                controlPanel.add(okButton);
                controlPanel.add(submitButton);
                controlPanel.add(cancelButton);       
        
                mainFrame.setVisible(true);  
            }
        
            private class ButtonClickListener implements ActionListener{
                public void actionPerformed(ActionEvent e) {
                    String command = e.getActionCommand();  
                    if( command.equals( "OK" ))  {
                    statusLabel.setText("Ok Button clicked.");
                    }
                    else if( command.equals( "Submit" ) )  {
                    statusLabel.setText("Submit Button clicked."); 
                    }
                    else  {
                    statusLabel.setText("Cancel Button clicked.");
                    }  	
                }		
            }
        }

    The output of the above code.

  • Java – Exception Handling

    An exception in Java is an event that arises during the execution of a program i.e. during runtime. The occurrence of an exception in a program disrupts the normal flow of instructions. This causes the termination of the program or application and therefore needs to be handled by calling an exception handler, which deals with the exception.

    An exception may occur for the invalid user input, or the files that need to be opened cannot be found., or loss of network connection.

    Exception handling is a mechanism to maintain the normal flow of a program by handling runtime errors. The main advantage of exception handling is to ensure that even when an exception occurs, the program’s flow doesn’t break.

    Type of exception in Java:

    • Checked:
      Checked Exceptions are also known as compile-time exceptions. These exceptions are checked by the compiler during compile-time. If a checked exception is found within the method then the method must be handled by try and catch or must declare an exception by throws keyword. These exceptions are not to be ignored.
      Some of the checked Exceptions occur are SQLException, IOException, ClassNotFoundException, etc.
    • Unchecked Exception:
      Unchecked Exceptions are also known as run-time exceptions. These exceptions occur during the time of execution of a program that is at run-time. These exceptions are not checked during compilation.
      Some of the Unchecked Exceptions occur are ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
    • Error:
      Errors are not an exception but are the problem that a user or programmer cannot handle. We can say that these are irrecoverable such as VirtualMachineError, OutOfMemoryError, AssertionError, etc.

    Exception Hierarchy:

    All exception classes are subtypes of the java.lang.Exception class. The exception types and errors are the subclasses of the Throwable class. Furthermore, they are also divided into a runtime exception and other exceptions as shown in the figure.

    Exception Hierarchy
    Exception Hierarchy

    Handling Exception in Java:

    Exception in Java is handled using five keywords:

    1. try
    2. catch
    3. throw
    4. throws
    5. finally.

    Try-Catch:

    This is one of the common ways to handle the exception. The combination of try and catch keyword is used in a method to catch an exception.
    The try block contains the exception code and the catch block is used to handle the exception if it occurs in the try block.

    Syntax for try-catch block:

     try
      {
      //  Block of exception code
      }
      catch(Exception e) 
      {
      //  Block of code to handle exception
      }

    Example: Java program to demonstrate try-catch:

    Let us see it in an example, where the code tries to try to access the fourth element in an array that has only 3 elements:

     public class TryCatchTest 
      {
        public static void main(String args[]) 
        {
          try 
          {
            int a[] = new int[3];
            System.out.println("Accessing element four :" + a[4]);
          } catch (Exception e) {
          System.out.println("Not Found");
          }
                
        }
      }

    Output:

    Not Found


    Java Multiple Catch Block:

    The code having multiple catch blocks which are followed by a try block. If there are different exceptions then each block of multiple catches must contain different exception handlers. Also, one catch block is executed at a time.

    Syntax for Multiple Catch Block:

    try 
      {
        // Exception code
      } catch (ExceptionType1 e1) {
        // Catch block
      } catch (ExceptionType2 e2) {
        // Catch block
      } catch (ExceptionType3 e3) {
        // Catch block
      }

    Example: Java program to demonstrate the Multiple catch block:

     public class MultipleCatchTest 
      {  
       public static void main(String[] args) 
       {  
                    
        try
        {    
          int a[]=new int[5];    
          a[5]=30/0;    
        }    
        catch(ArithmeticException e)  
        {  
          System.out.println("Arithmetic Exception occurs");  
        }    
        catch(ArrayIndexOutOfBoundsException e)  
        {  
          System.out.println("ArrayIndexOutOfBounds Exception occurs");  
        }    
                
       }  
      }

    Output:

    Arithmetic Exception occurs


    Throw:

    The throw keyword in Java is used to explicitly throw an exception from any block of code. throw keyword allows us to create a custom error or throw a custom exception.

    Syntax of throw keyword:

    throw new exception_type("error message");

    For example, we can throw ArithmeticException when we divide the number by 3, or any other numbers, we only need to do is set the condition and throw an exception using throw keyword. Such as:

    throw new ArithmeticException("cannot divide a number by 3");

    Example: Java Program to demonstrate throw:

    Let us see it in a program:
    Check for roll no. greater than 12, if true then allowed and if not then not allowed.

     public class ThrowTest 
      {
       static void checkRollNo(int roll) 
       {
        if (roll < 12) 
        {
          throw new ArithmeticException("Not Allowed to Enter.");
        }
        else {
          System.out.println("Allowed to Enter");
        }
       }
    
       public static void main(String[] args) 
       {
        checkRollNo(10); 
       }
      }

    Output:

    Exception in thread "main" java.lang.ArithmeticException: Not Allowed to Enter.
              at ThrowTest.checkRollNo(ThrowTest.java:7)
              at ThrowTest.main(ThrowTest.java:16)

    Throws

    throws keyword in java is used to declare an exception. It indicates that the method may throw an exception and it’s better to handle the exception using a try-catch block to maintain the normal flow of the program.

    Syntax of throws keyword:

     return_type method_name() throws exception_class_name
     {  
      //method code  
     }

    Example: Java Program to demonstrate throws:

    import java.io.IOException;  
    public class ThrowsTest
    {  
      void method1()throws IOException
      {  
        throw new IOException("Error");//checked exception  
      }  
      void method2()throws IOException
      {  
        method1();  
      }  
      void method3()
      {  
       try{  
        method2();  
       }catch(Exception e)
       {
           System.out.println("exception is handled");
       }  
      }  
      public static void main(String args[])
      {  
       ThrowsTest obj=new ThrowsTest();  
       obj.method3();  
       System.out.println("normal flow maintained");  
      }  
    }

    Output:

    exception is handled normal flow maintained


    Finally

    Finally block is used to execute the code followed by the try-catch block. finally block is always executed whether an exception is handled or not. This block appears at the end of the catch block.

    Syntax of throws keyword:

    try {
       // Protected code
    } catch (Exception1 e1) {
       // Catch block
    } catch (Exception2 e2) {
       // Catch block
    } catch (Exception3 e3) {
       // Catch block
    }finally {
       // The finally block is always executed.
    }

    Example: Java Program to demonstrate finally:

    public class FinallyTest 
    {
      public static void main(String args[]) 
      {
        int x[] = new int[5];
        try 
        {
           System.out.println("Access element 6 :" + x[6]);
        } catch (ArrayIndexOutOfBoundsException e) {
             System.out.println("Exception thrown  :" + e);
         }finally {
            x[3] = 4;
            System.out.println("Value of third element: " + x[3]);
            System.out.println("Execution of finally.");
          }
      }
    }

    Output:

    Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 6
    Value of third element: 4
    Execution of finally.


  • Java – Event Handling

    Event:

    An event is an object that describes the change of state in a source. It is the changes made within the GUI(Graphical User Interface). The activities that cause the event to be generated are the pressing of a button, selecting items, input the information, clicking of the mouse, etc, basically all the interaction with GUI.

    Two types of Event:

    • Foreground Events:
      It is the clicking of a mouse, pressing the button, input character from the keyboard. scrolling of the page etc. That is, these are events where the user is to interact directly with the GUI.
    • Background Events:
      The end-user interaction is seen in this type of event such as OS interruption, the timer expires, operation completion, etc. This is not directly caused by interactions with a user interface.

    Event Handling:

    It is a mechanism that handles all the events occurring and also controls the further process when an event occurs.
    To handle the events, Java uses the Delegation Event Model.

    Let us learn about the Delegation Event Model.

    Delegation Event Model:

    This model in Java is a new approach to handle the events. It is the standard and consistent way to Handle the events generated by the interaction with GUI components.

    The terms used:

    • Event Source:
      A source is an object that generates a specific kind of event. This may be the GUI component such as button list, Window, etc. Source provides data of the event that is occurred to the handler.
      A listener gets notified about the type of event that occurred and for that source must register a listener.
      The general form to register the listener to an event source is:
      publicvoid addTypeListener(TypeEvent e)
      Here, Type is the name of the event and e is the reference of the event listener.
    • Event Listener:
      A listener is an object that gets notified when an event occurs. In order to get notified, it must be registered to one or more event sources, and also it must implement methods to be able to receive and process it.
      These methods in Listener is found in, or need to import:
      import java.awt.event.*;
    • Process:
      Once the listener is registered, it waits for the event to occur. And when an event occurs, the source object is created and notified to the listener by the listener methods. Then, when the listener receives that object from the source, it executes the event and returns.

    Event Class:

    Java provides a number of event classes.
    Some of them are:

    • ActionEvent:
      It is the easiest and most common event occurring. To write an Action Listener extends a class AWTEvent.
      Example: when a button is pressed, the item in a list is double-clicked, etc.
    • KeyEvent:
      It extends a class InputEvent. It has three methods in the Listener interface.
      public void keyTyped(KeyEvent e)
      {active when typed}
      public void KeyPressed(KeyEvent e)
      {active when pressed}
      public void KeyReleased(KeyEvent e)
      {active when released}
    • MouseEvent:
      It extends a class InputEvent. It has 5 methods.
      It is instantiated when a mouse button is pressed, released, or clicked, or when a mouse cursor enters or exits a visible part of a component.
    • WindowEvent:
      It extends a class InputEvent. It provides 8 methods. Starts from when a Window object is opened, closed, activated, deactivated, iconified, deiconified, or gain or loss of Window Focus.
    • TextEvent:
      It extends a class AWTEvent. This class is instantiated when the text value or text area is changed.
    • ItemEvent:
      It extends AWtEvent. And instantiated when an item or from a list or a checkbox is selected or deselected.

    There are more event class such as ComponentEvent, InputEvent, FocusEvent, MouseMotionEvent etc.


    EventListener Interfaces:

    EventListener Interface class is defined by the java.util.package.
    It is an interface where every listener interface has to be extended.

    Class Declaration:

    The Following shows the declaration for java.util.EventListener interface:

    public interface EventListener

    AWT Event Listener Interfaces:

    The most commonly used event Listeners are:

    1. ActionListener:
      used for receiving the action events.
    2. AdjustmentListener:
      used for receiving the adjustment events.
    3. ComponentListener:
      used to define when a component is hidden, moved, resized, or shown.
    4. Focus Listener:
      used for receiving the focus events such as when a component loses or gains keyboard focus.
    5. KeyListener:
      used for receiving the key events such as the state of pressed, released, or typed.
    6. TextListener:
      used to receive text events like when the value of text changes.
    7. MouseMotionListener:
      used to receive the mouse motion events like when the mouse is moved or dragged.
    8. ContainerListener:
      used to receive container events like the addition or removal of the component from the container.
    9. WindowListener:
      used to receive window events such as window activation, deactivation, closed, opened or exit.
    10. MouseListener:
      used to receive mouse events such as clicking, pressed or released, etc.
    11. ItemListener:
      used to receive the item events that is the state of change of items.

  • Java – Deadlock with Example

    Deadlock in multithreading is a situation where two or more than two are a lock, waiting for each other.

    When the first thread needs to use the same lock or wait for the object lock which is acquired by a second thread and the second thread also waits for the lock acquired by a first thread then the deadlock occurs because they are waiting for each other which is caused by synchronized keyword.

    One of the example where Deadlock occur is the Dining Philosophers problem in C.


    Example: Java program for Deadlock demonstration.

     public class NamesDeadLock 
      {  
        public static void main(String[] args) 
        {  
          String Lock1 = "Prashant";  
          String Lock2 = "Karan";
          //Following, the two different thread are created t1 and t2
            
        // here t1 tries to lock Lock1 then Lock2  
        Thread t1 = new Thread() 
        {  
          public void run() 
          {  
            synchronized (Lock1) 
            {  
            System.out.println("Thread 1: Lock1 locked");  
    
            try 
            { 
                Thread.sleep(100);
            } catch (Exception e) {}  
    
            synchronized (Lock2) 
            {  
            System.out.println("Thread 1: Locked2 locked");  
            }  
            }  
          }  
        };  
        
        // here t2 tries to lock Lock2 then Lock1  
        Thread t2 = new Thread() 
        {  
          public void run() 
          {  
            synchronized (Lock2) 
            {  
            System.out.println("Thread 2: Lock2 locked");  
    
            try 
            { 
                Thread.sleep(100);
            } catch (Exception e) {}  
    
            synchronized (Lock1)
            {  
            System.out.println("Thread 2: Lock1 locked");  
            }  
            }  
          }  
        };  
        
            
        t1.start();  
        t2.start();  
        }  
      }

    Output of Deadlock:

      Thread 1: Lock1 locked
      Thread 2: Lock2 locked 

  • Java – Inter-Thread Communication

    When two or more thread needs to exchange information between them in an application, Inter-thread communication is required. Hence, we can also call it Co-Operation.

    The methods that are used for this communication are:

    1. wait()
    2. notify()
    3. notifyAll()

    1. wait()

    This method is written as:

     public void wait()

    This causes the current thread to wait until another thread invokes the notify() method that is it waits until the object is notified.

    2. notify()

    This method is written as:

     public void notify()

    This method wakes up a single thread that is waiting on this object’s monitor.

    3. notifyAll()

    This method is written as:

     public void notifyAll()

    This method wakes up all the threads that called wait( ) on the same object.


    Example: Java program to illustrate the Inter-Thread Communication:

     class Bank
      {  
      int cash = 500;  
        
      synchronized void cashWithdraw(int cash)
      {  
        System.out.println("Going to withdraw Cash");  
        
        if(this.cash < cash)
        {  
        System.out.println("Not Enough Balance");  
        try{
        wait(); //wait method
        }catch(Exception e)
        { }  
        }  
      this.cash -= cash;  
      System.out.println("Cash Withdrawal Completed");  
      }  
        
      synchronized void cashDeposit(int cash)
      {  
        System.out.println("Processing Deposit");  
        this.cash += cash;  
        System.out.println("Deposit completed");  
        notify(); //notify method 
      }  
      }  
        
      public class Main
      {  
      public static void main(String args[])
      {  
        final Bank b = new Bank();  
    
        new Thread()
        {  
        public void run()
        {
          b.cashWithdraw(1000);
        }  
        }.start();  
    
      new Thread()
      {  
        public void run()
        {
        b.cashDeposit(10000);
        }  
      }.start();  
    
      }
      }

    Output:

      Going to withdraw Cash
      Not Enough Balance
      Processing Deposit
      Deposit completed
      Cash Withdrawal Completed

  • Java – Static Synchronization

    This method is used to achieve static synchronization which locks a class, not an object.

    Why use static synchronization?

    Consider a shared class ‘Numbers’ for two objects (obj1 and obj2). The use of the synchronized method and synchronized block cannot interfere between the objects created(th1 and th2 or th3 and th4) for shared class because the lock was on the object. But interference may occur between th1 and th3 or th2 or th4 because of the class lock, th1 contain another class and th3 contain another class.

    So to solve this interference we use Static Synchronization.

    Java program to demonstrate the use of static synchronization:

     class Numbers
      {  
       synchronized static void displaySum(int a)
       {
        for(int i=1;i<=4;i++)
        {  
         System.out.println(a+i);  
         try
         {  
        
         Thread.sleep(200);  
         }catch(Exception e)
         {
           System.out.println(e);
         }  
        }
       }  
      }  
        
      class Thread1 extends Thread
      {
       Numbers n;  
       Thread1(Numbers n)
       {  
        this.n = n;  
       }
       public void run()
       {  
        n.displaySum(1);  
       }  
        
      }
        
      class Thread2 extends Thread
      { 
       Numbers n;  
       Thread2(Numbers n)
       {  
        this.n = n;  
       }
       public void run()
       {  
        n.displaySum(10);  
       }  
      }  
        
      class Thread3 extends Thread
      {  
       Numbers n;  
       Thread3(Numbers n)
       {  
        this.n = n;  
       }
       public void run()
       {  
        n.displaySum(100);  
       }  
      }  
        
      class Thread4 extends Thread
      {  
       Numbers n;  
       Thread4(Numbers n)
       {  
        this.n = n;  
       }
       public void run()
       {  
        n.displaySum(1000);  
       }  
      }  
            
      public class Main
      {  
        public static void main(String args[])
        {  
          Numbers obj = new Numbers();  
          Thread1 th1=new Thread1(obj);  
          Thread2 th2=new Thread2(obj); 
          Thread3 th3=new Thread3(obj);  
          Thread4 th4=new Thread4(obj); 
      
          th1.start();  
          th2.start();  
          th3.start();  
          th4.start();  
        }  
      }

    Output static synchronization:

      2
      3
      4
      5
      11
      12
      13
      14
      101
      102
      103
      104
      1001
      1002
      1003
      1004 

  • Java – Thread Synchronization

    Having multiple threads in a program may cause inconsistency and thread interference, that is the multiple threads when trying to access the same resource. One thread may try to write and another may try to read the shared resource or same file. So to achieve the use of only one resource or file at a time, we use synchronization.

    Synchronization makes sure that only one out of the multiple threads is allowed to access the resource at a given time.

    In this process, comes the Lock Concept, also known as monitors.
    Each object created in java is provided with the monitor. Only one thread may hold the lock at a time through which thread can lock or unlock.


    Synchronized method in java:

    Java contains a synchronized method to apply synchronous behaviour to the program. This method is used to lock an object for shared resources. The object automatically obtained a lock when it invokes the synchronized method and releases when the work is done.

    Syntax for Synchronized method:

    synchronized(object) 
     {
      //synchronized statement 
      // Access shared variables and other shared resources
     }

    Example of Java program without the use synchronized method:

     class Numbers
      {  
      void displaySum(int a)//method not synchronized  
      {
        for(int i=1;i<=4;i++)
        {  
        System.out.println(a+i);  
        try
        {  
    
          Thread.sleep(200);  
        }catch(Exception e)
        {
          System.out.println(e);
    
        }  
        }  
    
      }  
      }  
        
      class Thread1 extends Thread
      {  
       Numbers n;  
       Thread1(Numbers n)
       {  
        this.n = n;  
       }  
       public void run()
       {  
        n.displaySum(1);  
       }  
      }
        
      class Thread2 extends Thread
      {  
       Numbers n;  
       Thread2(Numbers n)
       {  
        this.n = n;  
       }  
       public void run()
       {  
        n.displaySum(20);  
       }  
      }  
        
      public class Main
      {  
      public static void main(String args[])
      {  
        Numbers obj = new Numbers();  
        Thread1 th1=new Thread1(obj);  
        Thread2 th2=new Thread2(obj);  
        th1.start();  
        th2.start();  
      }  
      }

    Output:

      2
      21
      22
      3
      23
      4
      24
      5

    Now let see an example with the use synchronized method:

     class Numbers
      {  
      synchronized void displaySum(int a)//method synchronized   
      {
        for(int i=1;i<=4;i++)
        {  
        System.out.println(a+i);  
        try
        {  
    
          Thread.sleep(200);  
          }catch(Exception e)
        {
          System.out.println(e);
    
        }  
        }  
    
      }   
      }  
        
      class Thread1 extends Thread
      {  
       Numbers n;  
       Thread1(Numbers n)
       {  
        this.n = n;  
       }  
       public void run()
       {  
        n.displaySum(1);  
       }  
    
      }
        
      class Thread2 extends Thread
      {  
       Numbers n;  
       Thread2(Numbers n)
       {  
        this.n = n;  
       }  
       public void run()
       {  
        n.displaySum(20);  
       }  
      }  
        
      public class Main
      {  
      public static void main(String args[])
      {  
        Numbers obj = new Numbers();  
        Thread1 th1=new Thread1(obj);  
        Thread2 th2=new Thread2(obj);  
        th1.start();  
        th2.start();  
      }  
      }

    Output:

      2
      3
      4
      5
      21
      22
      23
      2

    Synchronized block in java:

    It is also used to achieve synchronization in java which locks an object for any shared resource. It is the same as a synchronized method.

    Using Synchronized block only selected lines of code can be synchronized.

    Syntax for Synchronized block:

    synchronized (object reference) 
     {   
      //code block need to synchronized   
     }

    Example to demonstrate the use of Synchronized block in Java:

     class Numbers
      {  
      void displaySum(int a)
      {
        synchronized(this)// synchronized  block
        {
        for(int i=1;i<=4;i++)
        {  
          System.out.println(a+i);  
          try
          {  
    
          Thread.sleep(200);  
          }catch(Exception e)
          {
          System.out.println(e);
    
          }  
        }
        } 
    
      }  
      }  
        
      class Thread1 extends Thread
      {  
      Numbers n;  
      Thread1(Numbers n)
      {  
        this.n = n;  
      }  
      public void run()
      {  
        n.displaySum(1);  
      }  
    
      }
    
      class Thread2 extends Thread
      {  
      Numbers n;  
      Thread2(Numbers n)
      {  
        this.n = n;  
      }  
      public void run()
      {  
        n.displaySum(20);  
      }  
      }  
        
      public class Main
      {  
      public static void main(String args[])
      {  
        Numbers obj = new Numbers(); 
        Thread1 th1=new Thread1(obj);  
        Thread2 th2=new Thread2(obj);  
        th1.start();  
        th2.start();  
      }  
      } 

    Output:

      2
      3
      4
      5
      21
      22
      23
      24

    Note that:
    The scope of the synchronized method is higher than the synchronized block.