JAVA

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 127

Q1 APPLET

Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
Applet Life Cycle in Java

In Java, an applet is a special type of program embedded in the web page to generate dynamic
content. Applet is a class in Java.

The applet life cycle can be defined as the process of how the object is created, started,
stopped, and destroyed during the entire execution of its application. It basically has five core
methods namely init(), start(), stop(), paint() and destroy().These methods are invoked by the
browser to execute.

Along with the browser, the applet also works on the client side, thus having less processing
time.

There are five methods of an applet life cycle, and they are:
o init(): The init() method is the first method to run that initializes the applet. It can be
invoked only once at the time of initialization. The web browser creates the initialized
objects, i.e., the web browser (after checking the security settings) runs the init()
method within the applet.
o start(): The start() method contains the actual code of the applet and starts the applet.
It is invoked immediately after the init() method is invoked. Every time the browser is
loaded or refreshed, the start() method is invoked. It is also invoked whenever the
applet is maximized, restored, or moving from one tab to another in the browser. It is in
an inactive state until the init() method is invoked.
o stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to another
in the browser, the stop() method is invoked. When we go back to that page, the start()
method is invoked again.
o destroy(): The destroy() method destroys the applet after its work is done. It is invoked
when the applet window is closed or when the tab containing the webpage is closed. It
removes the applet object from memory and is executed only once. We cannot start the
applet once it is destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.
Applet Life Cycle Working
o The Java plug-in software is responsible for managing the life cycle of an applet.
o An applet is a Java application executed in any web browser and works on the client-
side. It doesn't have the main() method because it runs in the browser. It is thus created
to be placed on an HTML page.
o The init(), start(), stop() and destroy() methods belongs to the applet.Applet class.
o The paint() method belongs to the awt.Component class.
o In Java, if we want to make a class an Applet class, we need to extend the Applet
o Whenever we create an applet, we are creating the instance of the existing Applet class.
And thus, we can use all the methods of that class.

Java Application Vs. Java Applet

Java Application Java Applet

A Java Application also known as The Java applet works on the client side, and
application program is a type of program runs on the browser and makes use of
that independently executes on the another application program so that we can
computer. execute it.

Its execution starts with the main( ) It does not require the use of any main()
method only. The use of the main( ) is method. Java applet initializes through init( )
mandatory. method.

It cannot run independently, but requires It cannot start independently but requires
JRE to run. APIs for use (Example. APIs like Web API).

We need to install the Java application Java applet does not need to be pre-installed.
first and obviously on the local computer.

It is possible to establish connections with It cannot establish connection to other


other servers. servers.

It performs read and write tasks on a It cannot run the applications on any local
variety of files located on a local computer.
computer.

It can easily access a file or data available It cannot access the file or data found on any
on a computer system or device. local system or computer.
Java applications are pretty trusted, and Java applets are less reliable. So, they need to
thus, come with no security concerns. be safe.

Q2. paint( ) : The paint( ) method is called each time an AWT-based applet’s output must be
redrawn. This situation can occur for several reasons. For example, the window in which the
applet is running may be overwritten by another window and then uncovered. Or the applet
window may be minimized and then restored. 
paint( ) is also called when the applet begins execution. Whatever the cause, whenever the
applet must redraw its output, paint( ) is called. 
The paint( ) method has one parameter of type Graphics. This parameter will contain the
graphics context, which describes the graphics environment in which the applet is running.
This context is used whenever output to the applet is required. 

Q3. Which method are applied to all applets for controlling the applet execution . Explain the
use of update () method.
Repaint() or Update()
The repaint () method causes the AWT runtime system to execute the update () method of the
Component class which clears the window with the background color of the applet and then
calls the paint () method. For example: Suppose you want to display the current x and y
coordinates of the location where the mouse button is clicked in the applet window. As the
applet needs to update information displayed in its window (i.e. redraw the window), each
time the mouse is being clicked so this is possible with the use of repaint () method. To sum
up, the repaint() method is invoked to refresh the viewing area i.e. you call it when you have
new things to display.
Example :-
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*<applet code="RepaintJavaExample.class" width="350" height="150"> </applet>*/
public class RepaintJavaExample extends Applet implements MouseListener
{
        private int mouseX, mouseY;
        private boolean mouseclicked = false;
        public void init()
        {
          setBackground(Color.CYAN);
          addMouseListener(this);
        }
        public void mouseClicked(MouseEvent e)
        {
          mouseX = e.getX();
          mouseY=e.getY();
          mouseclicked = true;
          repaint();
        }
        public void mouseEntered(MouseEvent e){};
        public void mousePressed(MouseEvent e){};
        public void mouseReleased(MouseEvent e){};
        public void mouseExited(MouseEvent e){};
        public void paint( Graphics g )
        {
           String str;
           g.setColor(Color.RED);
           if (mouseclicked)
           {
             str = "X="+ mouseX + "," + "Y="+ mouseY ;
             g.drawString(str,mouseX,mouseY);
             mouseclicked = false;    
           }
        }
}

Example of displaying image in applet:

import java.awt.*;  
import java.applet.*;  
 public class DisplayImage extends Applet {  
  Image picture;  
  public void init() {  
    picture = getImage(getDocumentBase(),"sonoo.jpg");  
  }  
    public void paint(Graphics g) {  
    g.drawImage(picture, 30,30, this);  
  } 
  }  

myapplet.html
1. <html>  
2. <body>  
3. <applet code="DisplayImage.class" width="300" height="300">  
4. </applet>  
5. </body>  
6. </html>  
Q2. EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also.
Example of EventHandling in applet:

import java.applet.*;  
import java.awt.*;  
import java.awt.event.*;  
public class EventApplet extends Applet implements ActionListener{  
Button b;  
TextField tf;  
  
public void init(){  
tf=new TextField();  
tf.setBounds(30,40,150,20);  
  
b=new Button("Click");  
b.setBounds(80,150,60,50);  
  
add(b);add(tf);  
b.addActionListener(this);  
  
setLayout(null);  
}  
  
 public void actionPerformed(ActionEvent e){  
  tf.setText("Welcome");  
 }   
}  
In the above example, we have created all the controls in init() method because it is invoked only once.

myapplet.html
1. <html>  
2. <body>  
3. <applet code="EventApplet.class" width="300" height="300">  
4. </applet>  
5. </body>  
6. </html>  

Q3 . Swing
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written
in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Simple Java Swing Example


import javax.swing.*;  
public class FirstSwingExample {  
public static void main(String[] args) {  
JFrame f=new JFrame();//creating instance of JFrame  
JButton b=new JButton("click");//creating instance of JButton  
b.setBounds(130,100,100, 40);//x axis, y axis, width, height  
f.add(b);//adding button in JFrame  
f.setSize(400,500);//400 width and 500 height  
f.setLayout(null);//using no layout managers  
f.setVisible(true);//making the frame visible  
}  
}  

JButton

The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
Java JButton Example with ActionListener
import java.awt.event.*;  
import javax.swing.*;    
public class ButtonExample {  
public static void main(String[] args) {  
    JFrame f=new JFrame("Button Example");  
    final JTextField tf=new JTextField();  
    tf.setBounds(50,50, 150,20);  
    JButton b=new JButton("Click Here");  
    b.setBounds(50,100,95,30);  
    b.addActionListener(new ActionListener(){  
public void actionPerformed(ActionEvent e){  
            tf.setText("Welcome to Javatpoint.");  
        }  
    });  
    f.add(b);f.add(tf);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);   
}  

JFrame

The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.
JFrame works like the main window where components like labels, buttons, textfields are added
to create a GUI.

Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
JFrame Example
import java.awt.FlowLayout;  
import javax.swing.JButton;  
import javax.swing.JFrame;  
import javax.swing.JLabel;  
import javax.swing.JPanel;  
public class JFrameExample {  
    public static void main(String s[]) {  
        JFrame frame = new JFrame("JFrame Example");  
        JPanel panel = new JPanel();  
        panel.setLayout(new FlowLayout());  
        JLabel label = new JLabel("JFrame By Example");  
        JButton button = new JButton();  
        button.setText("Button");  
        panel.add(label);  
        panel.add(button);  
        frame.add(panel);  
        frame.setSize(200, 300);  
        frame.setLocationRelativeTo(null);  
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        frame.setVisible(true);  
    }  
}  

JWindow
JWindow is a container that can be displayed but does not have the title bar or window-
management buttons.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingContainerDemo {


private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JLabel msglabel;

public SwingContainerDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingContainerDemo swingContainerDemo = new SwingContainerDemo();
swingContainerDemo.showJWindowDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing 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 JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);

msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial.", JLabel.CENTER);

controlPanel = new JPanel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showJWindowDemo(){
headerLabel.setText("Container in action: JWindow");
final MessageWindow window = new MessageWindow(
mainFrame, "Welcome to TutorialsPoint SWING Tutorial.");

JButton okButton = new JButton("Open a Window");


okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
window.setVisible(true);
statusLabel.setText("A Window shown to the user.");
}
});
controlPanel.add(okButton);
mainFrame.setVisible(true);
}
class MessageWindow extends JWindow{
private String message;
public MessageWindow(JFrame parent, String message) {
super(parent);
this.message = message;
setSize(300, 300);
setLocationRelativeTo(parent);
}
public void paint(Graphics g) {
super.paint(g);
g.drawRect(0,0,getSize().width - 1,getSize().height - 1);
g.drawString(message,50,150);
}
}
}

JDialog

The JDialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Dialog class.
Java JDialog Example
import javax.swing.*;  
import java.awt.*;  
import java.awt.event.*;  
public class DialogExample {  
    private static JDialog d;  
    DialogExample() {  
        JFrame f= new JFrame();  
        d = new JDialog(f , "Dialog Example", true);  
        d.setLayout( new FlowLayout() );  
        JButton b = new JButton ("OK");  
        b.addActionListener ( new ActionListener()  
        {  
            public void actionPerformed( ActionEvent e )  
            {  
                DialogExample.d.setVisible(false);  
            }  
        });  
        d.add( new JLabel ("Click button to continue."));  
        d.add(b);   
        d.setSize(300,300);    
        d.setVisible(true);  
    }  
    public static void main(String args[])  
    {  
        new DialogExample();  
    }  
}  

JPanel

The JPanel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the JComponents class.
JPanel Example
import java.awt.*;  
import javax.swing.*;  
public class PanelExample {  
     PanelExample()  
        {  
        JFrame f= new JFrame("Panel Example");    
        JPanel panel=new JPanel();  
        panel.setBounds(40,80,200,200);    
        panel.setBackground(Color.gray);  
        JButton b1=new JButton("Button 1");     
        b1.setBounds(50,100,80,30);    
        b1.setBackground(Color.yellow);   
        JButton b2=new JButton("Button 2");   
        b2.setBounds(100,100,80,30);    
        b2.setBackground(Color.green);   
        panel.add(b1); panel.add(b2);  
        f.add(panel);  
                f.setSize(400,400);    
                f.setLayout(null);    
                f.setVisible(true);    
        }  
        public static void main(String args[])  
        {  
        new PanelExample();  
        }  
    }  

JToggleButton

JToggleButton is used to create toggle button, it is two-states button to switch on or off.


JToggleButton Example
import java.awt.FlowLayout;  
import java.awt.event.ItemEvent;  
import java.awt.event.ItemListener;  
import javax.swing.JFrame;  
import javax.swing.JToggleButton;  
  
public class JToggleButtonExample extends JFrame implements ItemListener {  
    public static void main(String[] args) {  
        new JToggleButtonExample();  
    }  
    private JToggleButton button;  
    JToggleButtonExample() {  
        setTitle("JToggleButton with ItemListener Example");  
        setLayout(new FlowLayout());  
        setJToggleButton();  
        setAction();  
        setSize(200, 200);  
        setVisible(true);  
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
    }  
    private void setJToggleButton() {  
        button = new JToggleButton("ON");  
        add(button);  
    }  
    private void setAction() {  
        button.addItemListener(this);  
    }  
    public void itemStateChanged(ItemEvent eve) {  
        if (button.isSelected())  
            button.setText("OFF");  
        else  
            button.setText("ON");  
    }  
}  
JCheckBox

The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
JCheckBox Example
import javax.swing.*;  
public class CheckBoxExample  
{  
     CheckBoxExample(){  
        JFrame f= new JFrame("CheckBox Example");  
        JCheckBox checkBox1 = new JCheckBox("C++");  
        checkBox1.setBounds(100,100, 50,50);  
        JCheckBox checkBox2 = new JCheckBox("Java", true);  
        checkBox2.setBounds(100,150, 50,50);  
        f.add(checkBox1);  
        f.add(checkBox2);  
        f.setSize(400,400);  
        f.setLayout(null);  
        f.setVisible(true);  
     }  
public static void main(String args[])  
    {  
    new CheckBoxExample();  
    }}  

JRadioButton

The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
JRadioButton Example
import javax.swing.*;    
public class RadioButtonExample {    
JFrame f;    
RadioButtonExample(){    
f=new JFrame();     
JRadioButton r1=new JRadioButton("A) Male");    
JRadioButton r2=new JRadioButton("B) Female");    
r1.setBounds(75,50,100,30);    
r2.setBounds(75,100,100,30);    
ButtonGroup bg=new ButtonGroup();    
bg.add(r1);bg.add(r2);    
f.add(r1);f.add(r2);      
f.setSize(300,300);    
f.setLayout(null);    
f.setVisible(true);    
}    
public static void main(String[] args) {    
    new RadioButtonExample();    
}    
}    

JLabel

The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.
JLabel Example
import javax.swing.*;  
class LabelExample  
{  
public static void main(String args[])  
    {  
    JFrame f= new JFrame("Label Example");  
    JLabel l1,l2;  
    l1=new JLabel("First Label.");  
    l1.setBounds(50,50, 100,30);  
    l2=new JLabel("Second Label.");  
    l2.setBounds(50,100, 100,30);  
    f.add(l1); f.add(l2);  
    f.setSize(300,300);  
    f.setLayout(null);  
    f.setVisible(true);  
    }  
    }  

JTextField

The object of a JTextField class is a text component that allows the editing of a single line text. It
inherits JTextComponent class.
TextField Example
import javax.swing.*;  
class TextFieldExample  
{  
public static void main(String args[])  
    {  
    JFrame f= new JFrame("TextField Example");  
    JTextField t1,t2;  
    t1=new JTextField("Welcome to Javatpoint.");  
    t1.setBounds(50,100, 200,30);  
    t2=new JTextField("AWT Tutorial");  
    t2.setBounds(50,150, 200,30);  
    f.add(t1); f.add(t2);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);  
    }  
    }  

JTextArea

The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class
JTextArea Example
import javax.swing.*;  
public class TextAreaExample  
{  
     TextAreaExample(){  
        JFrame f= new JFrame();  
        JTextArea area=new JTextArea("Welcome to javatpoint");  
        area.setBounds(10,30, 200,200);  
        f.add(area);  
        f.setSize(300,300);  
        f.setLayout(null);  
        f.setVisible(true);  
     }  
public static void main(String args[])  
    {  
   new TextAreaExample();  
    }}  

JList
The object of JList class represents a list of text items. The list of text items can be set up so that
the user can choose either one item or multiple items. It inherits JComponent class.
JList Example
import javax.swing.*;  
public class ListExample  
{  
     ListExample(){  
        JFrame f= new JFrame();  
        DefaultListModel<String> l1 = new DefaultListModel<>();  
          l1.addElement("Item1");  
          l1.addElement("Item2");  
          l1.addElement("Item3");  
          l1.addElement("Item4");  
          JList<String> list = new JList<>(l1);  
          list.setBounds(100,100, 75,75);  
          f.add(list);  
          f.setSize(400,400);  
          f.setLayout(null);  
          f.setVisible(true);  
     }  
public static void main(String args[])  
    {  
   new ListExample();  
    }}  

JComboBox

The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.
JComboBox Example
import javax.swing.*;    
public class ComboBoxExample {    
JFrame f;    
ComboBoxExample(){    
    f=new JFrame("ComboBox Example");    
    String country[]={"India","Aus","U.S.A","England","Newzealand"};        
    JComboBox cb=new JComboBox(country);    
    cb.setBounds(50, 50,90,20);    
    f.add(cb);        
    f.setLayout(null);    
    f.setSize(400,500);    
    f.setVisible(true);         
}    
public static void main(String[] args) {    
    new ComboBoxExample();         
}    
}   

JScrollPane

A JscrollPane is used to make scrollable view of a component. When screen size is limited, we
use a scroll pane to display a large component or a component whose size can change
dynamically.
JScrollPane Example
import java.awt.FlowLayout;  
import javax.swing.JFrame;  
import javax.swing.JScrollPane;  
import javax.swing.JtextArea;  
public class JScrollPaneExample {  
private static final long serialVersionUID = 1L;  
private static void createAndShowGUI() {  
final JFrame frame = new JFrame("Scroll Pane Example");  
frame.setSize(500, 500);  
frame.setVisible(true);  
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
frame.getContentPane().setLayout(new FlowLayout());  
JTextArea textArea = new JTextArea(20, 20);  
JScrollPane scrollableTextArea = new JScrollPane(textArea);  

scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBA
R_ALWAYS);  
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AL
WAYS);  

frame.getContentPane().add(scrollableTextArea);  
}  
public static void main(String[] args) {  
javax.swing.SwingUtilities.invokeLater(new Runnable() {  
public void run() {  
createAndShowGUI();  
}  
});  
}  
}  

JTable
The JTable class is used to display data in tabular form. It is composed of rows and columns.

JTable class declaration

Let's see the declaration for javax.swing.JTable class.

Commonly used Constructors:

Constructor Description

JTable() Creates a table with empty cells.

JTable(Object[][] rows, Object[] Creates a table with the specified


columns) data.

Java JTable Example


import javax.swing.*;    
public class TableExample {    
    JFrame f;    
    TableExample(){    
    f=new JFrame();    
    String data[][]={ {"101","Amit","670000"},    
                          {"102","Jai","780000"},    
                          {"101","Sachin","700000"}};    
    String column[]={"ID","NAME","SALARY"};         
    JTable jt=new JTable(data,column);    
    jt.setBounds(30,40,200,300);          
    JScrollPane sp=new JScrollPane(jt);    
    f.add(sp);          
    f.setSize(300,400);    
    f.setVisible(true);    
}     
public static void main(String[] args) {    
    new TableExample();    
}    
}  

Q4. AWT
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.

Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavy weight i.e. its components are using the resources of
underlying operating system (OS).

The java.awt package provides classes for AWT API such as TextField, Label, TextArea,


RadioButton, CheckBox, Choice, List etc.
Why AWT is platform independent?

Java AWT calls the native platform calls the native platform (operating systems) subroutine for
creating API components like TextField, ChechBox, button, etc.

For example, an AWT GUI with components like TextField, label and button will have different
look and feel for the different platforms like Windows, MAC OS, and Unix. The reason for this is
the platforms have different view for their native components and AWT directly calls the native
subroutine that creates those components.

In simple words, an AWT application will look like a windows application in Windows OS
whereas it will look like a Mac application in the MAC OS.

Container

The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such
as Frame, Dialog and Panel.

Types of containers:

i. Window

The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window. We need to create an instance of Window class to
create this container.

ii. Panel

The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.

iii. Frame
The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used
container while developing an AWT application.
Java AWT Example

To create simple AWT example, you need a frame. There are two ways to create a GUI using
Frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
AWT Example by Inheritance

Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.

AWTExample1.java
import java.awt.*;    
public class AWTExample1 extends Frame {    
  AWTExample1() {  
  Button b = new Button("Click Me!!"); 
      b.setBounds(30,100,80,30);  
      add(b);  
   setSize(300,300);  
   setTitle("This is our basic AWT example");   
    setLayout(null);   
    setVisible(true);  
}    
 public static void main(String args[]) {   
  AWTExample1 f = new AWTExample1();    
  }  
  }    

AWT Example by Association

Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are
creating a TextField, Label and Button component on the Frame.

AWTExample2.java
import java.awt.*;    
  class AWTExample2 {    
   AWTExample2() {  
        Frame f = new Frame();  
Label l = new Label("Employee id:");   
  Button b = new Button("Submit");  
   TextField t = new TextField();  
      l.setBounds(20, 80, 80, 30);  
      t.setBounds(20, 100, 80, 30);  
      b.setBounds(100, 100, 80, 30);  
    f.add(b);  
      f.add(l);  
      f.add(t);  
        f.setSize(400,300);  
  f.setTitle("Employee info");   
       f.setLayout(null);   
   f.setVisible(true);  
}    
public static void main(String args[]) {   
AWTExample2 awt_obj = new AWTExample2();    
}  
}    

AWT Button

A button is basically a control component with a label that generates an event when pushed.
The Button class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.

When we press a button and release it, AWT sends an instance of ActionEvent to that button by
calling processEvent on the button. The processEvent method of the button receives the all the
events, then it passes an action event by calling its own method processActionEvent. This
method passes the action event on to action listeners that are interested in the action events
generated by the button.

To perform an action on a button being pressed and released, the ActionListener interface


needs to be implemented. The registered new listener can receive events from the button by
calling addActionListener method of the button. The Java application can use the button's
action command as a messaging protocol.

Example 1:

ButtonExample.java
import java.awt.*;    
public class ButtonExample {    
public static void main (String[] args) {   
  
    // create instance of frame with the label   
    Frame f = new Frame("Button Example");    
  
    // create instance of button with label  
    Button b = new Button("Click Here");   
  
    // set the position for the button in frame   
    b.setBounds(50,100,80,30);    
  
    // add button to the frame  
    f.add(b);    
    // set size, layout and visibility of frame  
    f.setSize(400,400);    
    f.setLayout(null);    
    f.setVisible(true);     
}    
}    
AWT Label

The object of the Label class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by a programmer but a user cannot edit it
directly.

It is called a passive control as it does not create any event when it is accessed. To create a
label, we need to create the object of Label class.

LabelExample.java
import java.awt.*;    
  
public class LabelExample {    
public static void main(String args[]){   
  
    // creating the object of Frame class and Label class  
    Frame f = new Frame ("Label example");  
    Label l1, l2;    
  
    // initializing the labels   
    l1 = new Label ("First Label.");   
    l2 = new Label ("Second Label.");   
  
    // set the location of label  
    l1.setBounds(50, 100, 100, 30);    
    l2.setBounds(50, 150, 100, 30);  
  
    // adding labels to the frame    
    f.add(l1);  
    f.add(l2);   
  
    // setting size, layout and visibility of frame   
    f.setSize(400,400);    
    f.setLayout(null);    
    f.setVisible(true);    
}    
}    

Text Component
AWT TextField

The object of a TextField class is a text component that allows a user to enter a single line text
and edit it. It inherits TextComponent class, which further inherits Component class.

When we enter a key in the text field (like key pressed, key released or key typed), the event is
sent to TextField. Then the KeyEvent is passed to the registered KeyListener. It can also be
done using ActionEvent; if the ActionEvent is enabled on the text field, then the ActionEvent
may be fired by pressing return key. The event is handled by the ActionListener interface.
import java.awt.*;   
public class TextFieldExample1 {  
    // main method  
    public static void main(String args[]) {    
    // creating a frame  
    Frame f = new Frame("TextField Example");    
  
    // creating objects of textfield  
    TextField t1, t2;    
    t1 = new TextField("Welcome to Javatpoint.");    
    t1.setBounds(50, 100, 200, 30);    
    t2 = new TextField("AWT Tutorial");    
    t2.setBounds(50, 150, 200, 30);    
    // adding the components to frame  
    f.add(t1);  
    f.add(t2);   
    // setting size, layout and visibility of frame   
    f.setSize(400,400);    
    f.setLayout(null);    
    f.setVisible(true);    
}    
}    

AWT TextArea
The object of a TextArea class is a multiline region that displays text. It allows the editing of
multiple line text. It inherits TextComponent class.

The text area allows us to type as much text as we want. When the text in the text area
becomes larger than the viewable area, the scroll bar appears automatically which helps us to
scroll the text up and down, or right and left.
import java.awt.*;    
public class TextAreaExample    
{    
     TextAreaExample() {    
        Frame f = new Frame();    
            TextArea area = new TextArea("Welcome to javatpoint");    
        area.setBounds(10, 30, 300, 300);    
        f.add(area);  
  
        f.setSize(400, 400);    
        f.setLayout(null);    
        f.setVisible(true);    
     }    
public static void main(String args[])    
{    
   new TextAreaExample();    
}    
}    

AWT Checkbox

The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
import java.awt.*;    
public class CheckboxExample1  
{    
     CheckboxExample1() {    
       Frame f = new Frame("Checkbox Example");    
        Checkbox checkbox1 = new Checkbox("C++");    
        checkbox1.setBounds(100, 100,  50, 50);    
        Checkbox checkbox2 = new Checkbox("Java", true);    
checkbox2.setBounds(100, 150,  50, 50);    
        f.add(checkbox1);    
        f.add(checkbox2);    
        f.setSize(400,400);    
        f.setLayout(null);    
        f.setVisible(true);    
     }    
public static void main (String args[])    
{    
    new CheckboxExample1();    
}    
}    

AWT CheckboxGroup

The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only
one check box button is allowed to be in "on" state and remaining check box button in "off"
state. It inherits the object class.
import java.awt.*;    
public class CheckboxGroupExample    
{    
       CheckboxGroupExample(){    
       Frame f= new Frame("CheckboxGroup Example");    
        CheckboxGroup cbg = new CheckboxGroup();  
        Checkbox checkBox1 = new Checkbox("C++", cbg, false);    
        checkBox1.setBounds(100,100, 50,50);    
        Checkbox checkBox2 = new Checkbox("Java", cbg, true);    
        checkBox2.setBounds(100,150, 50,50);    
        f.add(checkBox1);    
        f.add(checkBox2);    
        f.setSize(400,400);    
        f.setLayout(null);    
        f.setVisible(true);    
     }    
public static void main(String args[])    
{    
    new CheckboxGroupExample();    
}    
}  

 AWT Choice

The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits Component class.
import java.awt.*;   
public class ChoiceExample1 {    
        ChoiceExample1() {    
        Frame f = new Frame();    
        Choice c = new Choice();   
        c.setBounds(100, 100, 75, 75);  
        c.add("Item 1");    
        c.add("Item 2");    
        c.add("Item 3");    
        c.add("Item 4");    
        c.add("Item 5");    
          f.add(c);   
        f.setSize(400, 400);    
        f.setLayout(null);    
        f.setVisible(true);    
     }    
  public static void main(String args[])    
{    
   new ChoiceExample1();    
}    
}     

AWT List

The object of List class represents a list of text items. With the help of the List class, user can
choose either one item or multiple items. It inherits the Component class.
import java.awt.*;    
public class ListExample1  
{    
     ListExample1() {    
        Frame f = new Frame();   
        List l1 = new List(5);   
        l1.setBounds(100, 100, 75, 75);    
          l1.add("Item 1");    
        l1.add("Item 2");    
        l1.add("Item 3");    
        l1.add("Item 4");    
        l1.add("Item 5");    
          f.add(l1);   
          f.setSize(400, 400);    
        f.setLayout(null);    
        f.setVisible(true);    
     }    
  public static void main(String args[])    
{    
   new ListExample1();    
}    
}    
AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is
a GUI component allows us to see invisible number of rows and columns.It can be added to top-
level container like Frame or a component like Panel. The Scrollbar class extends
the Component class.
import java.awt.*;   
 public class ScrollbarExample1 {    
  ScrollbarExample1() {    
              Frame f = new Frame("Scrollbar Example");    
            Scrollbar s = new Scrollbar();    
              s.setBounds (100, 100, 50, 100);  
              f.add(s);    
              f.setSize(400, 400);  
            f.setLayout(null);    
            f.setVisible(true);    
}    
  public static void main(String args[]) {    
       new ScrollbarExample1();    
}    }    
AWT MenuItem and Menu

The object of MenuItem class adds a simple labeled menu item on menu. The items used in a
menu must belong to the MenuItem or any of its subclass.The object of Menu class is a pull
down menu component which is displayed on the menu bar. It inherits the MenuItem class.
import java.awt.*;  
class MenuExample  
{  
     MenuExample(){  
         Frame f= new Frame("Menu and MenuItem Example");  
         MenuBar mb=new MenuBar();  
         Menu menu=new Menu("Menu");  
         Menu submenu=new Menu("Sub Menu");  
         MenuItem i1=new MenuItem("Item 1");  
         MenuItem i2=new MenuItem("Item 2");  
         MenuItem i3=new MenuItem("Item 3");  
         MenuItem i4=new MenuItem("Item 4");  
         MenuItem i5=new MenuItem("Item 5");  
         menu.add(i1);  
         menu.add(i2);  
         menu.add(i3);  
         submenu.add(i4);  
         submenu.add(i5);  
         menu.add(submenu);  
         mb.add(menu);  
         f.setMenuBar(mb);  
         f.setSize(400,400);  
         f.setLayout(null);  
         f.setVisible(true);  
}  
public static void main(String args[])  
{  
new MenuExample();  
}  
}  
AWT Panel

The Panel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the Container class.
import java.awt.*;  
public class PanelExample {  
     PanelExample()  
        {  
        Frame f= new Frame("Panel Example");    
        Panel panel=new Panel();  
        panel.setBounds(40,80,200,200);    
        panel.setBackground(Color.gray);  
        Button b1=new Button("Button 1");     
        b1.setBounds(50,100,80,30);    
        b1.setBackground(Color.yellow);   
        Button b2=new Button("Button 2");   
        b2.setBounds(100,100,80,30);    
        b2.setBackground(Color.green);   
        panel.add(b1); panel.add(b2);  
        f.add(panel);  
        f.setSize(400,400);    
        f.setLayout(null);    
        f.setVisible(true);    
        }  
        public static void main(String args[])  
        {  
        new PanelExample();  
        }  
}  

Q 5 . Working With frame Classes


AWT Frame Class
The class Frame is a top level window with border and title. It uses BorderLayout as default
layout manager.
import java.awt.*;
import java.awt.event.*;
public class AwtContainerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
private Label msglabel;
public AwtContainerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtContainerDemo awtContainerDemo = new AwtContainerDemo();
awtContainerDemo.showFrameDemo();
}
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);
msglabel = new Label();
msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showFrameDemo(){
headerLabel.setText("Container in action: Frame");
final Frame frame = new Frame();
frame.setSize(300, 300);
frame.setLayout(new FlowLayout());
frame.add(msglabel);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
frame.dispose();
}
});
Button okButton = new Button("Open a Frame");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("A Frame shown to the user.");
frame.setVisible(true);
}
});
controlPanel.add(okButton);
mainFrame.setVisible(true);
}
}

Q6. AWT Layout Manager


The layout manager automatically positions all the components within the container. If we do
not use layout manager then also the components are positioned by the default layout
manager. It is possible to layout the controls by hand but it becomes very difficult because of
the following two reasons.
 It is very tedious to handle a large number of controls within the container.
 Oftenly the width and height information of a component is not given when we
need to arrange them.
AWT Layout Manager Classes:
1. BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west, north, south
and center.
import java.awt.*;
import java.awt.event.*;
public class AwtLayoutDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
private Label msglabel;
public AwtLayoutDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtLayoutDemo awtLayoutDemo = new AwtLayoutDemo();
awtLayoutDemo.showBorderLayoutDemo();
}
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);
msglabel = new Label();
msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showBorderLayoutDemo(){
headerLabel.setText("Layout in action: BorderLayout");
Panel panel = new Panel();
panel.setBackground(Color.darkGray);
panel.setSize(300,300);
BorderLayout layout = new BorderLayout();
layout.setHgap(10);
layout.setVgap(10);
panel.setLayout(layout);
panel.add(new Button("Center"),BorderLayout.CENTER);
panel.add(new Button("Line Start"),BorderLayout.LINE_START);
panel.add(new Button("Line End"),BorderLayout.LINE_END);
panel.add(new Button("East"),BorderLayout.EAST);
panel.add(new Button("West"),BorderLayout.WEST);
panel.add(new Button("North"),BorderLayout.NORTH);
panel.add(new Button("South"),BorderLayout.SOUTH);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
}

2. CardLayout
The CardLayout object treats each component in the container as a card. Only one card is
visible at a time.
3. FlowLayout
The FlowLayout is the default layout.It layouts the components in a directional flow.
4. GridLayout
The GridLayout manages the components in form of a rectangular grid.
5. GridBagLayout
This is the most flexible layout manager class.The object of GridBagLayout aligns the
component vertically,horizontally or along their baseline without requiring the components of
same size.

Q7. Event Handling


Event:- Change in the state of an object is known as event i.e. event describes the change in
state of source. Events are generated as result of user interaction with the graphical user
interface components. For example, clicking on a button, moving the mouse, entering a
character through keyboard,selecting an item from list, scrolling the page are the activities that
causes an event to happen.

Types of Event
 Foreground Events - Those events which require the direct interaction of
user.They are generated as consequences of a person interacting with the
graphical components in Graphical User Interface. For example, clicking on a
button, moving the mouse, entering a character through keyboard,selecting an
item from list, scrolling the page etc.
 Background Events - Those events that require the interaction of end user are
known as background events. Operating system interrupts, hardware or software
failure, timer expires, an operation completion are the example of background
events.
Event Handling
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs.

Q8. Event Delegation Model (EVM)


 In the Delegation model, a source generates an event and forwards it to one or more
listeners, where the listener waits until they receive an event. Once the listener gets the
event, it is processed by the listener, and then they return it. The UI elements can
delegate an event's processing to a separate function.

i. Event Sources

A source is an object that causes and generates an event. It generates an event when the
internal state of the object is changed. The sources are allowed to generate several different
types of events.

A source must register a listener to receive notifications for a specific event. Each event
contains its registration method. Below is an example:
public void addTypeListener (TypeListener e1)  

ii. Event Listeners

An event listener is an object that is invoked when an event triggers. The listeners require two
things; first, it must be registered with a source; however, it can be registered with several
resources to receive notification about the events. Second, it must implement the methods to
receive and process the received notifications.

The methods that deal with the events are defined in a set of interfaces. These interfaces can
be found in the java.awt.event package.

For example, the MouseMotionListener interface provides two methods when the mouse is


dragged and moved. Any object can receive and process these events if it implements the
MouseMotionListener interface.

Java Program to Implement the Event Deligation Model


import java.awt.*;  
import java.awt.event.*;  
  public class TestApp {  
    public void search() {   
        // For searching  
        System.out.println("Searching...");  
    }  
    public void sort() {   
        // for sorting  
        System.out.println("Sorting....");  
    }  
   static public void main(String args[]) {  
       TestApp app = new TestApp();  
       GUI gui = new GUI(app);  
    }  }  
  class Command implements ActionListener  {  
    static final int SEARCH = 0;  
    static final int SORT = 1;  
    int id;  
    TestApp app;  
  public Command(int id, TestApp app) {  
        this.id = id;  
        this.app = app;  
    }  
   public void actionPerformed(ActionEvent e) {  
        switch(id) {  
          case SEARCH:   
            app.search();  
            break;  
          case SORT:  
            app.sort();  
            break;  
        }   }  }  
  class GUI {  
   public GUI(TestApp app) {  
        Frame f = new Frame();  
        f.setLayout(new FlowLayout());            
  Command searchCmd = new Command(Command.SEARCH, app);  
        Command sortCmd = new Command(Command.SORT, app);  
  Button b;  
        f.add(b = new Button("Search"));  
        b.addActionListener(searchCmd);  
        f.add(b = new Button("Sort"));  
        b.addActionListener(sortCmd);  
   List l;  
        f.add(l = new List());  
        l.add("Alphabetical");  
        l.add("Chronological");  
        l.addActionListener(sortCmd);  
        f.pack();  
  f.show();  
    }  }  

Q9. ActionListener Interface

The Java ActionListener is notified whenever you click on the button or menu item. It is notified
against ActionEvent. The ActionListener interface is found in java.awt.event package. It has only
one method: actionPerformed().
actionPerformed() method

The actionPerformed() method is invoked automatically whenever you click on the registered
component.
1. public abstract void actionPerformed(ActionEvent e);  

import java.awt.*;  
import java.awt.event.*;  
public class ActionListenerExample implements ActionListener{  
public static void main(String[] args) {  
    Frame f=new Frame("ActionListener Example");  
    final TextField tf=new TextField();  
    tf.setBounds(50,50, 150,20);  
    Button b=new Button("Click Here");  
    b.setBounds(50,100,60,30);  
    b.addActionListener(this);  
    f.add(b);f.add(tf);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);   
}  
public void actionPerformed(ActionEvent e){  
            tf.setText("Welcome to Javatpoint.");  
}  
}  

Q10. Mouse Handling


1. MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five
methods.

Methods of MouseListener interface


1. public abstract void mouseClicked(MouseEvent e);  
2. public abstract void mouseEntered(MouseEvent e);  
3. public abstract void mouseExited(MouseEvent e);  
4. public abstract void mousePressed(MouseEvent e);  
5. public abstract void mouseReleased(MouseEvent e);  
Java MouseListener Example
import java.awt.*;  
import java.awt.event.*;  
public class MouseListenerExample extends Frame implements MouseListener{  
    Label l;  
    MouseListenerExample(){  
        addMouseListener(this);  
          
        l=new Label();  
        l.setBounds(20,50,100,20);  
        add(l);  
        setSize(300,300);  
        setLayout(null);  
        setVisible(true);  
    }  
    public void mouseClicked(MouseEvent e) {  
        l.setText("Mouse Clicked");  
    }  
    public void mouseEntered(MouseEvent e) {  
        l.setText("Mouse Entered");  
    }  
    public void mouseExited(MouseEvent e) {  
        l.setText("Mouse Exited");  
    }  
    public void mousePressed(MouseEvent e) {  
        l.setText("Mouse Pressed");  
    }  
    public void mouseReleased(MouseEvent e) {  
        l.setText("Mouse Released");  
    }  
public static void main(String[] args) {  
    new MouseListenerExample();  
}  
}  
2. MouseMotionListener Interface

The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified
against MouseEvent. The MouseMotionListener interface is found in java.awt.event package. It
has two methods.
Methods of MouseMotionListener interface

The signature of 2 methods found in MouseMotionListener interface are given below:


1. public abstract void mouseDragged(MouseEvent e);  
2. public abstract void mouseMoved(MouseEvent e);  
Java MouseMotionListener Example
import java.awt.*;  
import java.awt.event.*;  
public class MouseMotionListenerExample extends Frame implements MouseMotionListen
er{  
    MouseMotionListenerExample(){  
        addMouseMotionListener(this);  
          
        setSize(300,300);  
        setLayout(null);  
        setVisible(true);  
    }  
public void mouseDragged(MouseEvent e) {  
    Graphics g=getGraphics();  
    g.setColor(Color.BLUE);  
    g.fillOval(e.getX(),e.getY(),20,20);  
}  
public void mouseMoved(MouseEvent e) {}  
  
public static void main(String[] args) {  
    new MouseMotionListenerExample();  
}  
}  

Q11. Keyboard Handling


KeyListener Interface

The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in java.awt.event package, and it has three
methods.
Methods of KeyListener interface

The signature of 3 methods found in KeyListener interface are given below:

Method name Description

public abstract void keyPressed (KeyEvent e); It is invoked when a key has been pressed.

public abstract void keyReleased (KeyEvent e); It is invoked when a key has been released.

public abstract void keyTyped (KeyEvent e); It is invoked when a key has been typed.

import java.awt.*;    
import java.awt.event.*;    
public class KeyListenerExample extends Frame implements KeyListener {    
class  
 Label l;    
    TextArea area;    
    KeyListenerExample() {    
                  l = new Label();    
        l.setBounds (20, 50, 100, 20);    
        area = new TextArea();    
        area.setBounds (20, 80, 300, 300);    
        area.addKeyListener(this);  
        add(l);  
add(area);    
        setSize (400, 400);    
        setLayout (null);    
        setVisible (true);    
    }    
    public void keyPressed (KeyEvent e) {    
        l.setText ("Key Pressed");    
    }    
    public void keyReleased (KeyEvent e) {    
        l.setText ("Key Released");    
    }    
    public void keyTyped (KeyEvent e) {    
        l.setText ("Key Typed");    
    }    
    public static void main(String[] args) {    
        new KeyListenerExample();    
    }    
}   
 Q12. Adapter Classes

Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of
listener interfaces.

i. WindowAdapter:- It is an abstract (adapter) class for receiving window events. All
methods of this class are empty. This class is convenience class for creating listener
objects.
import java.awt.*;    
import java.awt.event.*;    
  public class AdapterExample {  
    Frame f;    
    AdapterExample() {    
        f = new Frame ("Window Adapter");    
        f.addWindowListener (new WindowAdapter() {    
            public void windowClosing (WindowEvent e) {    
                f.dispose();    
            }    
        });    
          f.setSize (400, 400);    
        f.setLayout (null);    
        f.setVisible (true);    
    }    
  public static void main(String[] args) {    
    new AdapterExample();    
}    
}   

ii. MouseAdapter :- It is an abstract (adapter) class for receiving mouse events. All
methods of this class are empty. This class is convenience class for creating listener
objects.
import java.awt.*;    
import java.awt.event.*;    
public class MouseAdapterExample extends MouseAdapter {    
    Frame f;    
    MouseAdapterExample() {    
        f = new Frame ("Mouse Adapter");    
        f.addMouseListener(this);    
        f.setSize (300, 300);    
        f.setLayout (null);    
        f.setVisible (true);    
    }    
    public void mouseClicked (MouseEvent e) {    
        Graphics g = f.getGraphics();    
g.setColor (Color.BLUE);    
        g.fillOval (e.getX(), e.getY(), 30, 30);    
    }    
  public static void main(String[] args) {    
    new MouseAdapterExample();    
}    
}    

iii. MouseMotionAdapter:- It is an abstract (adapter) class for receiving mouse motion
events. All methods of this class are empty. This class is convenience class for creating
listener objects.
import java.awt.*;    
import java.awt.event.*;    
public class MouseMotionAdapterExample extends MouseMotionAdapter {     
    Frame f;    
    MouseMotionAdapterExample() {    
        f = new Frame ("Mouse Motion Adapter");    
        f.addMouseMotionListener (this);    
  f.setSize (300, 300);    
        f.setLayout (null);    
        f.setVisible (true);    
    }    
  public void mouseDragged (MouseEvent e) {    
    Graphics g = f.getGraphics();    
    g.setColor (Color.ORANGE);    
 g.fillOval (e.getX(), e.getY(), 20, 20);    
}    
public static void main(String[] args) {    
    new MouseMotionAdapterExample();    
}    
}  

iv. KeyAdapter :- It is an abstract (adapter) class for receiving keyboard events. All
methods of this class are empty. This class is convenience class for creating listener
objects.
import java.awt.*;    
import java.awt.event.*;    
public class KeyAdapterExample extends KeyAdapter {    
    Label l;    
    TextArea area;    
    Frame f;    
    KeyAdapterExample() {    
        f = new Frame ("Key Adapter");    
        l = new Label();    
        l.setBounds (20, 50, 200, 20);    
        area = new TextArea();  
        area.setBounds (20, 80, 300, 300);    
        area.addKeyListener(this);    
  f.add(l);  
f.add(area);    
        f.setSize (400, 400);    
        f.setLayout (null);    
        f.setVisible (true);    
    }    
    public void keyReleased (KeyEvent e) {    
 String text = area.getText();    
        String words[] = text.split ("\\s");    
        l.setText ("Words: " + words.length + " Characters:" + text.length());    
    }    
public static void main(String[] args) {    
        new KeyAdapterExample();    
    }    
}    

Q13.  ItemListener Interface or Item Events

The Java ItemListener is notified whenever you click on the checkbox. It is notified against
ItemEvent. The ItemListener interface is found in java.awt.event package. It has only one
method: itemStateChanged().

itemStateChanged() method

The itemStateChanged() method is invoked automatically whenever you click or unclick on the
registered checkbox component.

public abstract void itemStateChanged(ItemEvent e);  
Java ItemListener Example

import java.awt.*;    
import java.awt.event.*;    
public class ItemListenerExample implements ItemListener{    
    Checkbox checkBox1,checkBox2;  
    Label label;  
    ItemListenerExample(){    
        Frame f= new Frame("CheckBox Example");    
        label = new Label();            
        label.setAlignment(Label.CENTER);    
        label.setSize(400,100);    
        checkBox1 = new Checkbox("C++");    
        checkBox1.setBounds(100,100, 50,50);    
        checkBox2 = new Checkbox("Java");    
        checkBox2.setBounds(100,150, 50,50);    
        f.add(checkBox1); f.add(checkBox2); f.add(label);    
        checkBox1.addItemListener(this);    
        checkBox2.addItemListener(this);    
        f.setSize(400,400);    
        f.setLayout(null);    
        f.setVisible(true);    
     }    
    public void itemStateChanged(ItemEvent e) {      
        if(e.getSource()==checkBox1)  
            label.setText("C++ Checkbox: "     
            + (e.getStateChange()==1?"checked":"unchecked"));   
        if(e.getSource()==checkBox2)  
        label.setText("Java Checkbox: "     
        + (e.getStateChange()==1?"checked":"unchecked"));    
     }  
public static void main(String args[])    
{    
    new ItemListenerExample();    
}    
}    

Q14. Inner Classes (Nested Classes)

Java inner class or nested class is a class that is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place to be more readable
and maintainable.

Advantage of Java inner classes

There are three advantages of inner classes in Java. They are as follows:
1. Nested classes represent a particular type of relationship that is it can access all the
members (data members and methods) of the outer class, including private.
2. Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.
Types of Inner classes
i. Member Inner class

A non-static class that is created inside a class but outside a method is called member inner
class. It is also known as a regular inner class. It can be declared with access modifiers like
public, default, private, and protected. Example :-
class TestMemberOuter1{  
 private int data=30;  
 class Inner{  
  void msg(){System.out.println("data is "+data);}  
 }  
 public static void main(String args[]){  
  TestMemberOuter1 obj=new TestMemberOuter1();  
  TestMemberOuter1.Inner in=obj.new Inner();  
  in.msg();  
 }  

}  // Output: data is 30

ii. Anonymous inner class

Java anonymous inner class is an inner class without a name and for which only a single object
is created. An anonymous inner class can be useful when making an instance of an object with
certain "extras" such as overloading methods of a class or interface, without having to actually
subclass a class.

In simple words, a class that has no name is known as an anonymous inner class in Java. It
should be used if you have to override a method of class or interface. Java Anonymous inner
class can be created in two ways:
i. Class (may be abstract or concrete).
ii. Interface
Example :- abstract class Person{  
  abstract void eat();  
}  
class TestAnonymousInner{  
 public static void main(String args[]){  
  Person p=new Person(){  
  void eat(){System.out.println("nice fruits");}  
  };  
  p.eat();  
 }  
}  // Output:- nice fruit
iii. Local inner class

A class i.e., created inside a method, is called local inner class in java. Local Inner Classes are the
inner classes that are defined inside a block. Generally, this block is a method body. Sometimes
this block can be a for loop, or an if clause. Local Inner classes are not a member of any
enclosing classes. They belong to the block they are defined within, due to which local inner
classes cannot have any access modifiers associated with them. However, they can be marked
as final or abstract. These classes have access to the fields of the class enclosing it. Example:-
public class localInner1{  
 private int data=30;//instance variable  
 void display(){  
  class Local{  
   void msg(){System.out.println(data);}  
  }  
  Local l=new Local();  
  l.msg();  
 }  
 public static void main(String args[]){  
  localInner1 obj=new localInner1();  
  obj.display();  
 }  
}  // Output :- 30

iv. Static nested class

A static class is a class that is created inside a class, is called a static nested class in Java. It
cannot access non-static data members and methods. It can be accessed by outer class name.
o It can access static data members of the outer class, including private.
o The static nested class cannot access non-static (instance) data members or
Example:- class TestOuter1{  
  static int data=30;  
  static class Inner{  
   void msg(){System.out.println("data is "+data);}  
  }  
  public static void main(String args[]){  
  TestOuter1.Inner obj=new TestOuter1.Inner();  
  obj.msg();  
  }  
}  
Nested Interface

An interface, i.e., declared within another interface or class, is known as a nested interface. The
nested interfaces are used to group related interfaces so that they can be easy to maintain. The
nested interface must be referred to by the outer interface or class. It can't be accessed
directly. Example:-
interface Showable{  
  void show();  
  interface Message{  
   void msg();  
  }  }  
class TestNestedInterface1 implements Showable.Message{  
 public void msg(){System.out.println("Hello nested interface");}  
  public static void main(String args[]){  
  Showable.Message message=new TestNestedInterface1();//upcasting here  
  message.msg();  
 }  }  

Q14 .Exception Handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,


IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions

Types of Java Exceptions

1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,


AssertionError etc.
try block

Java try block is used to enclose the code that might throw an exception. It must be used within
the method.

If an exception occurs at the particular statement in the try block, the rest of the block code will
not execute. So, it is recommended not to keep the code in try block that will not throw an
exception.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


try{    
//code that may throw an exception    
}catch(Exception_class_Name ref){}    

Syntax of try-finally block


try{    
//code that may throw an exception    
}finally{}    

 catch block

Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.

The catch block must be used after the try block only. You can use multiple catch block with a
single try block.

The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM
provides a default exception handler that performs the following tasks:
o Prints out exception description.
o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.
finally block

Java finally block is a block used to execute important code such as closing the connection, etc.

Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception
occurs or not.
The finally block follows the try-catch block.
Finally block is executed as soon as the try-catch block is executed. It's execution is not
dependant on the exception.

Finally block runs the important code even if exception occurs or not.
Finally block cleans up all the resources used in try block
throw keyword

The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has some message with it
that provides the error description. These exceptions may be related to user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly
used to throw a custom exception. We will discuss custom exceptions later in this section.

We can also define our own set of conditions and throw an exception explicitly using throw
keyword. For example, we can throw ArithmeticException if we divide a number by another
number. Here, we just need to set the condition and throw exception using throw keyword.

The syntax of the Java throw keyword is given below.

throw Instance i.e.,


1. throw new exception_class("error message");  

Q15. Built-in Exception


Built-in exceptions are the exceptions which are available in Java libraries. These exceptions
are suitable to explain certain error situations. Below is the list of important built-in
exceptions in Java.
Examples of Built-in Exception:
1. Arithmetic exception : It is thrown when an exceptional condition has occurred in
an arithmetic operation.
class ArithmeticException_Demo {
public static void main(String args[])
    {
        try {
            int a = 30, b = 0;
            int c = a / b; // cannot divide by zero
            System.out.println("Result = " + c);
        }
        catch (ArithmeticException e) {
            System.out.println("Can't divide a number by 0");
        }
    }
}

ArrayIndexOutOfBounds Exception : It is thrown to indicate that an array has been accessed
with an illegal index. The index is either negative or greater than or equal to the size of the
array.
class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
    {
        try {
            int a[] = new int[5];
            a[6] = 9; // accessing 7th element in an array of
            // size 5
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array Index is Out Of Bounds");
        }
    }
}
ClassNotFoundException : This Exception is raised when we try to access a class whose
definition is not found.

class Bishal {
  
} class Geeks {
  
} class MyClass {
public static void main(String[] args)
    {
        Object o = class.forName(args[0]).newInstance();
        System.out.println("Class created for" + o.getClass().getName());
    }
}
FileNotFoundException : This Exception is raised when a file is not accessible or does not open.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
  
public static void main(String args[])
    {
        try {
              File file = new File("E:// file.txt");
   FileReader fr = new FileReader(file);
        }
        catch (FileNotFoundException e) {
            System.out.println("File does not exist");
        }}}
IOException : It is thrown when an input-output operation failed or interrupted

// Java program to illustrate IOException


import java.io.*;
class Geeks {
public static void main(String args[])
    {FileInputStream f = null;
 f = new FileInputStream("abc.txt");
        int i;
        while ((i = f.read()) != -1) {
            System.out.print((char)i);
        }
        f.close();
    }
}

InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some processing,
and it is interrupted.

class Geeks {
public static void main(String args[])
    {
        Thread t = new Thread();
        t.sleep(10000);
    }
}

NoSuchMethodException : t is thrown when accessing a method which is not found.

// Java Program to illustrate 


// NoSuchMethodException
class Geeks {
public Geeks()
    {
        Class i;
        try {
            i = Class.forName("java.lang.String");
            try {
                Class[] p = new Class[5];
            }
            catch (SecurityException e) {
                e.printStackTrace();
            }
            catch (NoSuchMethodException e) {
                e.printStackTrace();
            } 
catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
  
public static void main(String[] args)
    {
        new Geeks();
    }
}

StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an index is


either negative than the size of the string.

class StringIndexOutOfBound_Demo {
public static void main(String args[])
    {
        try {
            String a = "This is like chipping "; // length is 22
            char c = a.charAt(24); // accessing 25th element
            System.out.println(c);
        }
        catch (StringIndexOutOfBoundsException e) {
            System.out.println("StringIndexOutOfBoundsException");
        }
    }
}

Example of Exception Handling or User defined Exception


class InvalidAgeException  extends Exception  
{  
    public InvalidAgeException (String str)  
    {   
        super(str);  
    }  
}  
public class TestCustomException1  
{  
 static void validate (int age) throws InvalidAgeException{    
       if(age < 18){  
  throw new InvalidAgeException("age is not valid to vote");    
    }  
       else {   
        System.out.println("welcome to vote");   
        }   
     }    
   public static void main(String args[])  
    {  
        try  
        {  
             validate(13);  
        }  
        catch (InvalidAgeException ex)  
        {  
            System.out.println("Caught the exception");  
      System.out.println("Exception occured: " + ex);  
        }  
   System.out.println("rest of the code...");    
    }  
}  

Output: Caught the exception

Exception occurred: InvalidAgeException: age is not valid to vote

Rest of code….

Q16. Multithreading in Java

Multithreading s a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single


thread.

Thread in java

A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of


execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.

Life cycle of a thread 


A thread goes through various stages in its lifecycle. For example, a thread is born, started,
runs, and then dies. The following diagram shows the complete life cycle of a thread.

Following are the stages of the life cycle −


 New − A new thread begins its life cycle in the new state. It remains in this state
until the program starts the thread. It is also referred to as a born thread.
  Runnable − After a newly born thread is started, the thread becomes runnable.
A thread in this state is considered to be executing its task.
  Waiting − Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task. Thread transitions back to the
runnable state only when another thread signals the waiting thread to continue
executing.
  Timed Waiting − A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the runnable
state when that time interval expires or when the event it is waiting for occurs.
  Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.

Creating Thread using thread class and runnable interface

Thread class:

Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.

Java Thread Example by extending Thread class

FileName: Multi.java
class Multi extends Thread{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi t1=new Multi();  
t1.start();  
 }  
}  

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to
be executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.

Java Thread Example by implementing Runnable interface

FileName: Multi3.java
class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}  
  
public static void main(String args[]){  
Multi3 m1=new Multi3();  
Thread t1 =new Thread(m1);   // Using the constructor Thread(Runnable r)  
t1.start();  
 }  
}  

Q17. Garbage Collection

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
The Garbage collector of JVM collects only those objects that are created by new keyword. So if
you have created any object without new, you can use finalize method to perform cleanup
processing (destroying remaining objects).

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.

There are many ways:


o By nulling the reference
o By assigning a reference to another
o By anonymous object etc.

1) By nulling a reference:
1. Employee e=new Employee();  
2. e=null;  

2) By assigning a reference to another:


1. Employee e1=new Employee();  
2. Employee e2=new Employee();  
3. e1=e2;//now the first object referred by e1 is available for garbage collection  

3) By anonymous object:
1. new Employee();  

Example :- public class TestGarbage1{  
 public void finalize(){System.out.println("object is garbage collected");}  
 public static void main(String args[]){  
  TestGarbage1 s1=new TestGarbage1();  
  TestGarbage1 s2=new TestGarbage1();  
  s1=null;  
  s2=null;  
  System.gc();  
 }  
}  
Output:-
object is garbage collected
object is garbage collected

Q. Thread Synchronization
When we start two or more threads within a program, there may be a situation when multiple
threads try to access the same resource and finally they can produce unforeseen result due to
concurrency issues. For example, if multiple threads try to write within a same file then they
may corrupt the data because one of the threads can override data or while one thread is
opening the same file at the same time another thread might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only one
thread can access the resource at a given point in time. This is implemented using a concept
called monitors. Each object in Java is associated with a monitor, which a thread can lock or
unlock. Only one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and synchronizing
their task by using synchronized blocks. 
Multithreading Example with Synchronization
Here is the same example which prints counter value in sequence and every time we run it, it
produces the same result.
Example:-
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo( String name, PrintDemo pd) {
threadName = name;
PD = pd;
}

public void run() {


synchronized(PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
T1.start();
T2.start();
try {
T1.join();
T2.join();
} catch ( Exception e) {
System.out.println("Interrupted");
}
}
}
Output:-
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.

Q. Priority of a Thread (Thread Priority)

Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, the thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses. Note that not only JVM a Java programmer can also assign the
priorities of a thread explicitly in a Java program.
Setter & Getter Method of Thread Priority

Let's discuss the setter and getter method of the thread priority.

public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of


the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method updates


or assign the priority of the thread to newPriority. The method throws
IllegalArgumentException if the value newPriority goes out of the range, which is 1 (minimum)
to 10 (maximum).
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the


value of MAX_PRIORITY is 10.

Example of priority of a Thread:


import java.lang.*;  
public class ThreadPriorityExample extends Thread   
{  
public void run()  
{  
System.out.println("Inside the run() method");  
}  
public static void main(String argvs[])  
{  
ThreadPriorityExample th1 = new ThreadPriorityExample();  
ThreadPriorityExample th2 = new ThreadPriorityExample();  
ThreadPriorityExample th3 = new ThreadPriorityExample();  
System.out.println("Priority of the thread th1 is : " + th1.getPriority());  
System.out.println("Priority of the thread th2 is : " + th2.getPriority());  
System.out.println("Priority of the thread th2 is : " + th2.getPriority());  
  
th1.setPriority(6);  
th2.setPriority(3);  
th3.setPriority(9);  
System.out.println("Priority of the thread th1 is : " + th1.getPriority());  
System.out.println("Priority of the thread th2 is : " + th2.getPriority());  
System.out.println("Priority of the thread th3 is : " + th3.getPriority());   
System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName()
);  
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority()); 
 
Thread.currentThread().setPriority(10);  
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority()); 
 
}  
}  
Output:- Priority of the thread th1 is : 5
Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10

Q. Thread Communication

Inter-thread communication or Co-operation is all about allowing synchronized threads to


communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running
in its critical section and another thread is allowed to enter (or lock) in the same critical section
to be executed.It is implemented by following methods of Object class:

1) wait() method

The wait() method causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.

Method Description

public final void wait()throws It waits until object is


InterruptedException notified.

public final void wait(long It waits for the


timeout)throws specified amount of
InterruptedException time.

2) notify() method

The notify() method wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened. The choice is
arbitrary and occurs at the discretion of the implementation.

Syntax:
1. public final void notify()  

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor.

Syntax:
1. public final void notifyAll()  

Example :- Test.java
class Customer{    
int amount=10000;    
synchronized void withdraw(int amount){    
System.out.println("going to withdraw...");    
if(this.amount<amount){    
System.out.println("Less balance; waiting for deposit...");    
try{wait();}catch(Exception e){}    
}    
this.amount-=amount;    
System.out.println("withdraw completed...");    
}    
synchronized void deposit(int amount){    
System.out.println("going to deposit...");    
this.amount+=amount;    
System.out.println("deposit completed... ");    
notify();    
}    
}    
class Test{    
public static void main(String args[]){    
final Customer c=new Customer();    
new Thread(){    
public void run(){c.withdraw(15000);}    
}.start();    
new Thread(){    
public void run(){c.deposit(10000);}    
}.start();    
}
}    

OOPs Concept

OBJECT

An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table,
car, etc. It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.

An object has three characteristics:


o State: represents the data (value) of an object.
o Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID. The value of the ID
is not visible to the external user. However, it is used internally by the JVM to identify
each object uniquely.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.

Object Definitions:
o An object is a real-world entity.
o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.
ClASS

A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:


o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:


class <class_name>{  
    field;  
    method;  
}  
Advantage of OOPs over Procedure-oriented programming language

1) OOPs makes development and maintenance easier, whereas, in a procedure-oriented


programming language, it is not easy to manage if code grows as project size increases.

2) OOPs provides data hiding, whereas, in a procedure-oriented programming language, global


data can be accessed from anywhere.

3) OOPs provides the ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented Programming
language.
Example :- class Student{  
 int rollno;  
 String name;  
 void insertRecord(int r, String n){  
  rollno=r;  
  name=n;  
 }  
 void displayInformation(){System.out.println(rollno+" "+name);}  
}  
class TestStudent4{  
 public static void main(String args[]){  
  Student s1=new Student();  
  Student s2=new Student();  
  s1.insertRecord(111,"Karan");  
  s2.insertRecord(222,"Aryan");  
  s1.displayInformation();  
  s2.displayInformation();  
 }  
}  

Q. Method in Java

A method is a block of code or collection of statements or a set of code grouped together to


perform a certain task or operation. It is used to achieve the reusability of code. We write a
method once and use it many times. We do not require to write code again and again. It also
provides the easy modification and readability of code, just by adding or removing a chunk of
code. The method is executed only when we call or invoke it.
Types of Method

i. Predefined Method

In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of
the predefined methods in our program, a series of codes related to the corresponding method
runs in the background that is already stored in the library.
public class Demo   
{  
public static void main(String[] args)   
{  
// using the max() method of Math class  
System.out.print("The maximum number is: " + Math.max(9,7));  
}  
}  

ii. User-defined Method

The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
public static void findEvenOdd(int num)  
{  
//method body  
if(num%2==0)   
System.out.println(num+" is even");   
else   
System.out.println(num+" is odd");  
}  
Example of Method :- import java.util.Scanner;  
public class EvenOdd  
{  
public static void main (String args[])  
{  
Scanner scan=new Scanner(System.in);  
System.out.print("Enter the number: ");  
int num=scan.nextInt();  
findEvenOdd(num);  
}  
public static void findEvenOdd(int num)  
{  
if(num%2==0)   
System.out.println(num+" is even");   
else   
System.out.println(num+" is odd");  
}  
}  

Output 1:
Enter the number: 12
12 is even

Output 2:
Enter the number: 99
99 is odd

Q. Java Constructor

In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory.

It is a special type of method which is used to initialize the object.


Types of Java constructors
i. Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


<class_name>(){}  
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object
class Bike1{  
Bike1(){System.out.println("Bike is created");}  
public static void main(String args[]){  
Bike1 b=new Bike1();  
}  
}

Output:
Bike is created

ii. Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor.

The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.

Example:- class Student4{  
 int id;  
    String name;  
    //creating a parameterized constructor  
    Student4(int i,String n){  
    id = i;  
    name = n;  
    }  
    //method to display the values  
    void display(){System.out.println(id+" "+name);}  
   
    public static void main(String args[]){  
    //creating objects and passing values  
    Student4 s1 = new Student4(111,"Karan");  
    Student4 s2 = new Student4(222,"Aryan");  
    //calling method to display the values of object  
    s1.display();  
    s2.display();  
   }  
}  
Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be overloaded
like Java methods. Constructor overloading in Java is a technique of having more than one
constructor with different parameter lists. They are arranged in a way that each constructor
performs a different task. They are differentiated by the compiler by the number of parameters
in the list and their types. Example:-
class Student5{  
    int id;  
    String name;  
    int age;  
    Student5(int i,String n){  
    id = i;  
    name = n;  
    }  
    Student5(int i,String n,int a){  
    id = i;  
    name = n;  
    age=a;  
    }  
    void display(){System.out.println(id+" "+name+" "+age);}  
   public static void main(String args[]){  
    Student5 s1 = new Student5(111,"Karan");  
    Student5 s2 = new Student5(222,"Aryan",25);  
    s1.display();  
    s2.display();  
   }  
}  

Static keyword

The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to the
class than an instance of the class.

Example of static variable


class Student{  
   int rollno;
   String name;  
   static String college ="ITS";
   Student(int r, String n){  
   rollno = r;  
   name = n;  
   }  
   void display (){System.out.println(rollno+" "+name+" "+college);}  
}  
public class TestStaticVariable1{  
 public static void main(String args[]){  
 Student s1 = new Student(111,"Karan");  
 Student s2 = new Student(222,"Aryan");  
 s1.display();  
 s2.display();  
 }  
}  
this keyword

There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers
to the current object.
class Student{  
int rollno;  
String name;  
float fee;  
Student(int rollno,String name,float fee){  
this.rollno=rollno;  
this.name=name;  
this.fee=fee;  
}  
void display(){System.out.println(rollno+" "+name+" "+fee);}  
}  
  
class TestThis2{  
public static void main(String args[]){  
Student s1=new Student(111,"ankit",5000f);  
Student s2=new Student(112,"sumit",6000f);  
s1.display();  
s2.display();  
}}  

Super Keyword

The super keyword in Java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
Example:- class Animal{  
String color="white";  
}  
class Dog extends Animal{  
String color="black";  
void printColor(){  
System.out.println(color);//prints color of Dog class  
System.out.println(super.color);//prints color of Animal class  
}  
}  
class TestSuper1{  
public static void main(String args[]){  
Dog d=new Dog();  
d.printColor();  
}}  

Final Keyword

The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block only.
We will have detailed learning of these. Let's first learn the basics of final keyword.

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't
be changed because final variable once assigned a value can never be changed.
1. class Bike9{  
2.  final int speedlimit=90;//final variable  
3.  void run(){  
4.   speedlimit=400;  
5.  }  
6.  public static void main(String args[]){  
7.  Bike9 obj=new  Bike9();  
8.  obj.run();  
9.  }  
10. }//end of class  
The final modifier for finalizing the implementations of classes, methods, and variables.
The main purpose of using a class being declared as final is to prevent the class from being
subclassed. If a class is marked as final then no class can inherit any feature from the final
class.
You cannot extend a final class. If you try it gives you a compile time error.
Example
final class Super {
private int data = 30;
}
public class Sub extends Super{
public static void main(String args[]){
}
}

Q. Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name  
{  
   //methods and fields  
}  
Types of inheritance in java
1) Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java
1. class Animal{  
2. void eat(){System.out.println("eating...");}  
3. }  
4. class Dog extends Animal{  
5. void bark(){System.out.println("barking...");}  
6. }  
7. class TestInheritance{  
8. public static void main(String args[]){  
9. Dog d=new Dog();  
10. d.bark();  
11. d.eat();  
12. }}  
2) Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.

File: TestInheritance2.java
class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class BabyDog extends Dog{  
void weep(){System.out.println("weeping...");}  
}  
class TestInheritance2{  
public static void main(String args[]){  
BabyDog d=new BabyDog();  
d.weep();  
d.bark();  
d.eat();  
}}  

3) Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

File: TestInheritance3.java
class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class Cat extends Animal{  
void meow(){System.out.println("meowing...");}  
}  
class TestInheritance3{  
public static void main(String args[]){  
Cat c=new Cat();  
c.meow();  
c.eat();  
}}  
Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A
and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
error.
class A{  
void msg(){System.out.println("Hello");}  
}  
class B{  
void msg(){System.out.println("Welcome");}  
}  
class C extends A,B{//suppose if it were  
   
 public static void main(String args[]){  
   C obj=new C();  
   obj.msg();//Now which msg() method would be invoked?  
}  
}  

Q. Java Package
Java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


Simple example of java package

The package keyword is used to create a package in java.


1. //save as Simple.java  
2. package mypack;  
3. public class Simple{  
4.  public static void main(String args[]){  
5.     System.out.println("Welcome to package");  
6.    }  
7. }  
How to access package from another package?

There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Example of package that import the packagename.*
//save by A.java  
package pack;  
public class A{  
  public void msg(){System.out.println("Hello");}  
}  
//save by B.java  
package mypack;  
import pack.*;  
  
class B{  
  public static void main(String args[]){  
   A obj = new A();  
   obj.msg();  
  }  
}  
Output:Hello

2) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
package pack;  
public class A{  
  public void msg(){System.out.println("Hello");}  
}  
package mypack;  
import pack.A;  
  
class B{  
  public static void main(String args[]){  
   A obj = new A();  
   obj.msg();  
  }  
}  
Output:Hello
3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Example of package by import fully qualified name
package pack;  
public class A{  
  public void msg(){System.out.println("Hello");}  
}  
package mypack;  
class B{  
  public static void main(String args[]){  
   pack.A obj = new pack.A();//using fully qualified name  
   obj.msg();  
  }  
}  

Q. Encapsulation

Encapsulation  is a process of wrapping code and data together into a single unit, for example, a
capsule which is mixed of several medicines.

We can create a fully encapsulated class in Java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.

The Java Bean class is the example of a fully encapsulated class.

Advantage of Encapsulation in Java

 By providing only a setter or getter method, you can make the class read-only or write-
only. In other words, you can skip the getter or setter methods.
 It provides you the control over the data. Suppose you want to set the value of id which
should be greater than 100 only, you can write the logic inside the setter method. You
can write the logic not to store the negative numbers in the setter methods.
 It is a way to achieve data hiding in Java because other class will not be able to access
the data through the private data members.
 The encapsulate class is easy to test. So, it is better for unit testing.
 The standard IDE's are providing the facility to generate the getters and setters. So, it
is easy and fast to create an encapsulated class in Java.
Example:- class Account {  
private long acc_no;  
private String name,email;  
private float amount;  
public long getAcc_no() {  
    return acc_no;  
}  
public void setAcc_no(long acc_no) {  
    this.acc_no = acc_no;  
}  
public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}  
public String getEmail() {  
    return email;  
}  
public void setEmail(String email) {  
    this.email = email;  
}  
public float getAmount() {  
    return amount;  
}  
public void setAmount(float amount) {  
    this.amount = amount;  
}  
}  

File: TestAccount.java
public class TestEncapsulation {  
public static void main(String[] args) {  
    Account acc=new Account();  
    acc.setAcc_no(7560504000L);  
    acc.setName("Sonoo Jaiswal");  
    acc.setEmail("[email protected]");  
    acc.setAmount(500000f);  
    //getting values through getter methods  
    System.out.println(acc.getAcc_no()+" "+acc.getName()+" "+acc.getEmail()+" "+acc.getAmou
nt());  
}  
}  

Output:
7560504000 Sonoo Jaiswal [email protected] 500000.0

Access Modifiers
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

There are four types of Java access modifiers:

1) Private

The private access modifier is accessible only within the class.


class A{  
private int data=40;  
private void msg(){System.out.println("Hello java");}  
}  
  
public class Simple{  
 public static void main(String args[]){  
   A obj=new A();  
   System.out.println(obj.data);//Compile Time Error  
   obj.msg();//Compile Time Error  
   }  
}  

2) Default

If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.

Example of default access modifier


1. //save by A.java  
2. package pack;  
3. class A{  
4.   void msg(){System.out.println("Hello");}  
5. }  
1. //save by B.java  
2. package mypack;  
3. import pack.*;  
4. class B{  
5.   public static void main(String args[]){  
6.    A obj = new A();//Compile Time Error  
7.    obj.msg();//Compile Time Error  
8.   }  

3) Protected

The protected access modifier is accessible within package and outside the package but
through inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier


1. //save by A.java  
2. package pack;  
3. public class A{  
4. protected void msg(){System.out.println("Hello");}  
5. }  
1. //save by B.java  
2. package mypack;  
3. import pack.*;  
4.   class B extends A{  
5.   public static void main(String args[]){  
6.    B obj = new B();  
7.    obj.msg();  
8.   }  
9. }  

4) Public

The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

Example of public access modifier


1. //save by A.java  
2.   package pack;  
3. public class A{  
4. public void msg(){System.out.println("Hello");}  
5. }  
1. //save by B.java  
2.   
3. package mypack;  
4. import pack.*;  
5.   
6. class B{  
7.   public static void main(String args[]){  
8.    A obj = new A();  
9.    obj.msg();  
10.   }  
11. }  

Polymorphism

Polymorphism in Java is a concept by which we can perform a single action in different ways.
Dynamic Method Dispatch Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an


overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as
upcasting. 
class A{}  
class B extends A{}  
A a=new B();//upcasting  

 Runtime Polymorphism Example: Bank


class Bank{  
float getRateOfInterest(){return 0;}  
}  
class SBI extends Bank{  
float getRateOfInterest(){return 8.4f;}  
}  
class ICICI extends Bank{  
float getRateOfInterest(){return 7.3f;}  
}  
class AXIS extends Bank{  
float getRateOfInterest(){return 9.7f;}  
}  
class TestPolymorphism{  
public static void main(String args[]){  
Bank b;  
b=new SBI();  
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());  
b=new ICICI();  
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());  
b=new AXIS();  
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());  
}  
}  

Output:
SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

Method Overloading

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behavior of the method because its name differs.
Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java


1. By changing number of arguments
2. By changing the data type

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.
class Adder{  
static int add(int a,int b){return a+b;}  
static int add(int a,int b,int c){return a+b+c;}  
}  
class TestOverloading1{  
public static void main(String[] args){  
System.out.println(Adder.add(11,11));  
System.out.println(Adder.add(11,11,11));  
}}  

2) Method Overloading: changing data type

In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder{  
static int add(int a, int b){return a+b;}  
static double add(double a, double b){return a+b;}  
}  
class TestOverloading2{  
public static void main(String[] args){  
System.out.println(Adder.add(11,11));  
System.out.println(Adder.add(12.3,12.6));  
}}  

Q) Why Method Overloading is not possible by changing the return type of method only?

In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:

Q) Can we overload java main() method?

Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only.
Method Overloading and Type Promotion

Example of Method Overloading with TypePromotion


class OverloadingCalculation1{  
  void sum(int a,long b){System.out.println(a+b);}  
  void sum(int a,int b,int c){System.out.println(a+b+c);}  
  
  public static void main(String args[]){  
  OverloadingCalculation1 obj=new OverloadingCalculation1();  
  obj.sum(20,20);//now second int literal will be promoted to long  
  obj.sum(20,20,20);  
    }  
}  

Example of Method Overloading with Type Promotion in case of ambiguity

If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.
class OverloadingCalculation3{  
  void sum(int a,long b){System.out.println("a method invoked");}  
  void sum(long a,int b){System.out.println("b method invoked");}  
  
  public static void main(String args[]){  
  OverloadingCalculation3 obj=new OverloadingCalculation3();  
  obj.sum(20,20);//now ambiguity  
  }  
}  
Method Overriding

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
o Method overriding is used for runtime polymorphism
Example :- class Bank{  
int getRateOfInterest(){return 0;}  
}  
class SBI extends Bank{  
int getRateOfInterest(){return 8;}  
}  
class ICICI extends Bank{  
int getRateOfInterest(){return 7;}  
}  
class AXIS extends Bank{  
int getRateOfInterest(){return 9;}  
}  
class Test2{  
public static void main(String args[]){  
SBI s=new SBI();  
ICICI i=new ICICI();  
AXIS a=new AXIS();  
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());  
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());  
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());  
}  
}  
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Q. Can we override static method?

No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we


will learn it later.

Q. Why can we not override static method?

It is because the static method is bound with class whereas instance method is bound with an
object. Static belongs to the class area, and an instance belongs to the heap area.

Q. Can we override java main method?

No, because the main is a static method.

Difference Method Overloading and Method Overriding

Method Overloading Method Overriding

Method overloading is used to increase the Method overriding is used to provide the
readability of the program. specific implementation of the method that is
already provided by its super class.

Method overloading is performed within Method overriding occurs in two classes that


class. have IS-A (inheritance) relationship.

In case of method overloading, parameter In case of method overriding, parameter


must be different. must be same.
Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.

In java, method overloading can't be Return type must be same or covariant in


performed by changing return type of the method overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.

Static Binding
The binding which can be resolved at compile time by the compiler is known as static or early
binding. The binding of all the static, private, and final methods is done at compile-time.
Example:

class NewClass {
     public static class superclass {
         static void print()
        {
             System.out.println(
                "print() in superclass is called");
        }
    }
    public static class subclass extends superclass {
        static void print()
        {
             System.out.println(
                "print() in subclass is called");
        }
    }
    public static void main(String[] args)
    {
        superclass A = new superclass();
        superclass B = new subclass();
        A.print();
        B.print();
    }
}

Dynamic Binding
In Dynamic binding compiler doesn’t decide the method to be called. Overriding is a perfect
example of dynamic binding. In overriding both parent and child classes have the same
method.
Example:

public class GFG {


     public static class superclass {
        void print()
        {
             System.out.println(
                "print in superclass is called");
        }
    }
     public static class subclass extends superclass {
         @Override void print()
        {
             System.out.println(
                "print in subclass is called");
        }}
     public static void main(String[] args)
    {
  superclass A = new superclass();
         superclass B = new subclass();
        A.print();
        B.print();
    }
}

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to
the user.

Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the

Abstract class

A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.
Example :-  abstract class Bike{  
   Bike(){System.out.println("bike is created");}  
   abstract void run();  
   void changeGear(){System.out.println("gear changed");}  
 }  
 class Honda extends Bike{  
 void run(){System.out.println("running safely..");}  
 }  
//Creating a Test class which calls abstract and non-abstract methods  
 class TestAbstraction2{  
 public static void main(String args[]){  
  Bike obj = new Honda();  
  obj.run();  
  obj.changeGear();  
 }  
}  

Interface in Java

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.

There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
Example:- interface Drawable{  
void draw();  
}  
class Rectangle implements Drawable{  
public void draw(){System.out.println("drawing rectangle");}  
}  
class Circle implements Drawable{  
public void draw(){System.out.println("drawing circle");}  
}  
class TestInterface1{  
public static void main(String args[]){  
Drawable d=new Circle();
d.draw();  
}}  
Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known


as multiple inheritance.
1. interface Printable{  
2. void print();  
3. }  
4. interface Showable{  
5. void show();  
6. }  
7. class A7 implements Printable,Showable{  
8. public void print(){System.out.println("Hello");}  
9. public void show(){System.out.println("Welcome");}  
10.   
11. public static void main(String args[]){  
12. A7 obj = new A7();  
13. obj.print();  
14. obj.show();  
15.  }  
16. }  
 
Multiple inheritance is not supported through class in java, but it is possible by an interface,
why?

As we have explained in the inheritance chapter, multiple inheritance is not supported in the
case of class because of ambiguity. However, it is supported in case of an interface because
there is no ambiguity. It is because its implementation is provided by the implementation class.
For example:
1. interface Printable{  
2. void print();  
3. }  
4. interface Showable{  
5. void print();  
6. }  
7.   
8. class TestInterface3 implements Printable, Showable{  
9. public void print(){System.out.println("Hello");}  
10. public static void main(String args[]){  
11. TestInterface3 obj = new TestInterface3();  
12. obj.print();  
13.  }  
14. }  

Extending Interface
An interface contains variables and methods like a class but the methods in an interface are
abstract by default unlike a class. An interface extends another interface like a class
implements an interface in interface inheritance.
Example
interface A {
   void funcA();
}
interface B extends A {
   void funcB();
}
class C implements B {
   public void funcA() {
      System.out.println("This is funcA");
   }
   public void funcB() {
      System.out.println("This is funcB");
   }
}
public class Demo {
   public static void main(String args[]) {
      C obj = new C();
      obj.funcA();
      obj.funcB();
   }
}
Output
This is funcA
This is funcB
Q) What is marker or tagged interface?

An interface which has no member is known as a marker or tagged interface, for


example, Serializable, Cloneable, Remote, etc. They are used to provide some essential
information to the JVM so that JVM may perform some useful operation.
public interface Serializable{  
}  

Nested Interface in Java

An interface can have another interface which is known as a nested interface. We will learn it in
detail in the nested classes chapter. For example:
interface printable{  
 void print();  
 interface MessagePrintable{  
   void msg();  
 }  
}  

I/O Stream

Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The java.io package contains all
the classes required for input and output operations.We can perform file handling in Java by
Java I/O API.
Stream

A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.In Java, 3 streams are created for us
automatically. All these streams are attached with the console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream


Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of these
two classes to copy an input file into an output file −
Example
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {        
      FileInputStream in = null;
      FileOutputStream out = null;
try {
         in = new FileInputStream("input.txt");
         out = new FileOutputStream("output.txt");
         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
   }
   }
}

Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit Unicode. Though there
are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input
file (having Unicode characters) into an output file −
Example
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
      FileReader in = null;
      FileWriter out = null;
try {
         in = new FileReader("input.txt");
         out = new FileWriter("output.txt");
         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
   }
   }
}

Java File Handling

The File class from the java.io package, allows us to work with files.

To use the File class, create an object of the class, and specify the filename or directory name:
import java.io.File; // Import the File class

File myObj = new File("filename.txt"); // Specify the filename


Create a File

To create a file in Java, you can use the createNewFile() method. This method returns a boolean
value: true if the file was successfully created, and false if the file already exists. Note that the
method is enclosed in a try...catch block. This is necessary because it throws an IOException if
an error occurs (if the file cannot be created for some reason):

import java.io.File; // Import the File class

import java.io.IOException; // Import the IOException class to handle errors

public class CreateFile {

public static void main(String[] args) {

try {

File myObj = new File("filename.txt");

if (myObj.createNewFile()) {

System.out.println("File created: " + myObj.getName());

} else {

System.out.println("File already exists.");

} catch (IOException e) {

System.out.println("An error occurred.");

e.printStackTrace();

}
Write To a File

In the following example, we use the FileWriter class together with its write() method to write


some text to the file we created in the example above. Note that when you are done writing to
the file, you should close it with the close() method:
Example

import java.io.FileWriter; // Import the FileWriter class

import java.io.IOException; // Import the IOException class to handle errors

public class WriteToFile {

public static void main(String[] args) {

try {

FileWriter myWriter = new FileWriter("filename.txt");

myWriter.write("Files in Java might be tricky, but it is fun enough!");

myWriter.close();

System.out.println("Successfully wrote to the file.");

} catch (IOException e) {

System.out.println("An error occurred.");

e.printStackTrace();

}
Read a File
 We use the Scanner class to read the contents of the text file

import java.io.File; // Import the File class

import java.io.FileNotFoundException; // Import this class to handle errors

import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {


public static void main(String[] args) {

try {

File myObj = new File("filename.txt");

Scanner myReader = new Scanner(myObj);

while (myReader.hasNextLine()) {

String data = myReader.nextLine();

System.out.println(data);

myReader.close();

} catch (FileNotFoundException e) {

System.out.println("An error occurred.");

e.printStackTrace();

}
Delete a File

To delete a file in Java, use the delete() method:

import java.io.File; // Import the File class

public class DeleteFile {

public static void main(String[] args) {

File myObj = new File("filename.txt");

if (myObj.delete()) {

System.out.println("Deleted the file: " + myObj.getName());

} else {
System.out.println("Failed to delete the file.");

Wrapper classes in Java

The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects


into primitives automatically. The automatic conversion of primitive into an object is known as
autoboxing and vice-versa unboxing.
Use of Wrapper classes in Java

Java is an object-oriented programming language, so we need to deal with objects many times
like in Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where
we need to use the wrapper classes.
o Change the value in Method: Java supports only call by value. So, if we pass a primitive
value, it will not change the original value. But, if we convert the primitive value in an
object, it will change the original value.
o Serialization: We need to convert the objects into streams to perform the serialization.
If we have a primitive value, we can convert it in objects through the wrapper classes.
o Synchronization: Java synchronization works with objects in Multithreading.
o java.util package: The java.util package provides the utility classes to deal with objects.
o Collection Framework: Java collection framework works with objects only. All classes of
the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet,
TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
Autoboxing

The automatic conversion of primitive data type into its corresponding wrapper class is known
as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to
Float, boolean to Boolean, double to Double, and short to Short.

Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the
primitive into objects.

Wrapper class Example: Primitive to Wrapper


//Java program to convert primitive into objects  
//Autoboxing example of int to Integer  
public class WrapperExample1{  
public static void main(String args[]){  
//Converting int into Integer  
int a=20;  
Integer i=Integer.valueOf(a);//converting int into Integer explicitly  
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally  
  
System.out.println(a+" "+i+" "+j);  
}}  
Unboxing

The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the
intValue() method of wrapper classes to convert the wrapper type into primitives.

Wrapper class Example: Wrapper to Primitive


//Java program to convert object into primitives  
//Unboxing example of Integer to int  
public class WrapperExample2{    
public static void main(String args[]){    
//Converting Integer to int    
Integer a=new Integer(3);    
int i=a.intValue();//converting Integer to int explicitly  
int j=a;//unboxing, now compiler will write a.intValue() internally    
    
System.out.println(a+" "+i+" "+j);    
}}    

Operators in Java

Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:
o incrementing/decrementing a value by one
o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int x=10;  
4. System.out.println(x++);//10 (11)  
5. System.out.println(++x);//12  
6. System.out.println(x--);//12 (11)  
7. System.out.println(--x);//10  
8. }}  

Java Arithmetic Operators

Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.

Java Arithmetic Operator Example


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=5;  
5. System.out.println(a+b);//15  
6. System.out.println(a-b);//5  
7. System.out.println(a*b);//50  
8. System.out.println(a/b);//2  
9. System.out.println(a%b);//0  
10. }}  
Java Shift Operator

Java Left Shift Operator

The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.

Java Left Shift Operator Example


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. System.out.println(10<<2);//10*2^2=10*4=40  
4. System.out.println(10<<3);//10*2^3=10*8=80  
5. System.out.println(20<<2);//20*2^2=20*4=80  
6. System.out.println(15<<4);//15*2^4=15*16=240  
7. }}  

Java Right Shift Operator

The Java right shift operator >> is used to move the value of the left operand to right by the
number of bits specified by the right operand.

Java Right Shift Operator Example


1. public OperatorExample{  
2. public static void main(String args[]){  
3. System.out.println(10>>2);//10/2^2=10/4=2  
4. System.out.println(20>>2);//20/2^2=20/4=5  
5. System.out.println(20>>3);//20/2^3=20/8=2  
6. }}  

Java Assignment Operator

Java assignment operator is one of the most common operators. It is used to assign the value
on its right to the operand on its left.

Java Assignment Operator Example


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=20;  
5. a+=4;//a=a+4 (a=10+4)  
6. b-=4;//b=b-4 (b=20-4)  
7. System.out.println(a);  
8. System.out.println(b);  
9. }}  

Java Ternary Operator

Java Ternary operator is used as one line replacement for if-then-else statement and used a lot
in Java programming. It is the only conditional operator which takes three operands.

Java Ternary Operator Example


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=2;  
4. int b=5;  
5. int min=(a<b)?a:b;  
6. System.out.println(min);  
7. }}  

Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.
1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=5;  
5. int c=20;  
6. System.out.println(a<b&&a<c);//false && true = false  
7. System.out.println(a<b&a<c);//false & true = false  
8. }}  

Output:
false
false

Java AND Operator Example: Logical && vs Bitwise &


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=5;  
5. int c=20;  
6. System.out.println(a<b&&a++<c);//false && true = false  
7. System.out.println(a);//10 because second condition is not checked  
8. System.out.println(a<b&a++<c);//false && true = false  
9. System.out.println(a);//11 because second condition is checked  
10. }}  

Output:
false
10
false
11

Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn't check the second condition if the first condition is true. It checks
the second condition only if the first one is false.

The bitwise | operator always checks both conditions whether first condition is true or false.
1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=5;  
5. int c=20;  
6. System.out.println(a>b||a<c);//true || true = true  
7. System.out.println(a>b|a<c);//true | true = true  
8. //|| vs |  
9. System.out.println(a>b||a++<c);//true || true = true  
10. System.out.println(a);//10 because second condition is not checked  
11. System.out.println(a>b|a++<c);//true | true = true  
12. System.out.println(a);//11 because second condition is checked  
13. }}  

Type casting

Convert a value from one data type to another data type is known as type casting.
Types of Type Casting

i. Widening Type Casting

Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no
chance to lose data. It takes place when:
o Both data types must be compatible with each other.
o The target type must be larger than the source type.

WideningTypeCastingExample.java
public class WideningTypeCastingExample  
{  
public static void main(String[] args)  
{  
int x = 7;   
long y = x;  
float z = y;  
System.out.println("Before conversion, int value "+x);  
System.out.println("After conversion, long value "+y);  
System.out.println("After conversion, float value "+z);  
}  
}  

ii. Narrowing Type Casting

Converting a higher data type into a lower one is called narrowing type casting. It is also known
as explicit conversion or casting up. It is done manually by the programmer. If we do not
perform casting then the compiler reports a compile-time error.
public class NarrowingTypeCastingExample  
{  
public static void main(String args[])  
{  
double d = 166.66;  
long l = (long)d;  
int i = (int)l;  
System.out.println("Before conversion: "+d);  
System.out.println("After conversion into long type: "+l);  
System.out.println("After conversion into int type: "+i);  
}  }  

Java StringBuffer Class

Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.

What is a mutable String?

A String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.

1) StringBuffer Class append() Method

The append() method concatenates the given argument with this String.

StringBufferExample.java
class StringBufferExample{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello ");  
sb.append("Java");//now original string is changed  
System.out.println(sb);//prints Hello Java  
}  
}  

2) StringBuffer insert() Method

The insert() method inserts the given String with this string at the given position.

StringBufferExample2.java
1. class StringBufferExample2{  
2. public static void main(String args[]){  
3. StringBuffer sb=new StringBuffer("Hello ");  
4. sb.insert(1,"Java");//now original string is changed  
5. System.out.println(sb);//prints HJavaello  
6. }  
7. }  

3) StringBuffer replace() Method


The replace() method replaces the given String from the specified beginIndex and endIndex.

StringBufferExample3.java
class StringBufferExample3{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello");  
sb.replace(1,3,"Java");  
System.out.println(sb);//prints HJavalo  
}  
}  

4) StringBuffer delete() Method

The delete() method of the StringBuffer class deletes the String from the specified beginIndex
to endIndex.

StringBufferExample4.java
1. class StringBufferExample4{  
2. public static void main(String args[]){  
3. StringBuffer sb=new StringBuffer("Hello");  
4. sb.delete(1,3);  
5. System.out.println(sb);//prints Hlo  
6. }  
7. }  

5) StringBuffer reverse() Method

The reverse() method of the StringBuilder class reverses the current String.

StringBufferExample5.java
class StringBufferExample5{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello");  
sb.reverse();  
System.out.println(sb);//prints olleH  
}  
}  

6) StringBuffer capacity() Method

The capacity() method of the StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is
16, it will be (16*2)+2=34.
StringBufferExample6.java
class StringBufferExample6{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer();  
System.out.println(sb.capacity());//default 16  
sb.append("Hello");  
System.out.println(sb.capacity());//now 16  
sb.append("java is my favourite language");  
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
}  
}  

7) StringBuffer ensureCapacity() method

The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

StringBufferExample7.java
class StringBufferExample7{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer();  
System.out.println(sb.capacity());//default 16  
sb.append("Hello");  
System.out.println(sb.capacity());//now 16  
sb.append("java is my favourite language");  
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
sb.ensureCapacity(10);//now no change  
System.out.println(sb.capacity());//now 34  
sb.ensureCapacity(50);//now (34*2)+2  
System.out.println(sb.capacity());//now 70  
}  
}  

Output:
16
16
34
34
70

Immutable String in Java


A String is an unavoidable type of variable while writing any application program. String
references are used to store various attributes like username, password, etc. In Java, String
objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once String object is created its data or state can't be changed but a new String object is
created.
Example:- Testimmutablestring.java
class Testimmutablestring{  
 public static void main(String args[]){  
   String s="Sachin";  
   s.concat(" Tendulkar");//concat() method appends the string at the end  
   System.out.println(s);//will print Sachin because strings are immutable objects  
 }  
}  
Why String objects are immutable in Java?
As Java uses the concept of String literal. Suppose there are 5 reference variables, all refer to
one object "Sachin". If one reference variable changes the value of the object, it will be affected
by all the reference variables. That is why String objects are immutable in Java.
Following are some features of String which makes String objects immutable.
1. ClassLoader:
A ClassLoader in Java uses a String object as an argument. Consider, if the String object is
modifiable, the value might be changed and the class that is supposed to be loaded might be
different.
To avoid this kind of misinterpretation, String is immutable.
2. Thread Safe:
As the String object is immutable we don't have to take care of the synchronization that is
required while sharing an object across multiple threads.
3. Security:
As we have seen in class loading, immutable String objects avoid further errors by loading the
correct class. This leads to making the application program more secure. Consider an example
of banking software. The username and password cannot be modified by any intruder because
String objects are immutable. This can make the application program more secure.
4. Heap Space:
The immutability of String helps to minimize the usage in the heap memory. When we try to
declare a new String object, the JVM checks whether the value already exists in the String pool
or not. If it exists, the same value is assigned to the new object. This feature allows Java to use
the heap space efficiently.
Why String class is Final in Java?
The reason behind the String class being final is because no one can override the methods of
the String class. So that it can provide the same features to the new String objects as well as to
the old ones.
Static Array

An array that is declared with the static keyword is known as static array. It allocates memory at
compile-time whose size is fixed. We cannot alter the static array.

If we want an array to be sized based on input from the user, then we cannot use static arrays.
In such a case, dynamic arrays allow us to specify the size of an array at run-time.

Advantages of Static Array

o It has efficient execution time.


o The lifetime of static allocation is the entire run time of the program.

Disadvantages of Static Array

o In case more static data space is declared than needed, there is waste of space.
o In case less static space is declared than needed, then it becomes impossible to expand
this fixed size during run time.

Dynamic array

The dynamic array is a variable size list data structure. It grows automatically when we try to
insert an element if there is no more space left for the new element. It allows us to add and
remove elements. It allocates memory at run time using the heap. It can change its size during
run time.

In Java, ArrayList is a resizable implementation. It implements the List interface and provides all
methods related to the list operations. The strength of the dynamic array is:

o Quick lookup
o Variable size
o Cache-friendly

Working of Dynamic Array in Java

The default capacity of dynamic arrays in Java is 10. That means internally, a dynamic array with
an internal capacity 10 is created. Whenever a user inserts an element in the dynamic array, its
size increases.

When the size of the dynamic array becomes equal to its capacity, a new array with double the
capacity gets created and the previous elements are stored inside the new array created
internally.
Program Questions
1.Program to print all prime numbers between 1 and 100
public class Prime  
{  
public static void main(String[] args)   
    {  
int ct=0,n=0,i=1,j=1;  
while(n<25)  
{  
j=1;  
ct=0;  
while(j<=i)  
{  
if(i%j==0)  
ct++;  
j++;   
}  
if(ct==2)  
{  
System.out.printf("%d ",i);  
n++;  
}  
i++;  
}    
}  
}  

Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Q. Fibonacci Series using recursion in java

class Fibonacci{  
 static int n1=0,n2=1,n3=0;    
 static void printFibonacci(int count){    
    if(count>0){    
         n3 = n1 + n2;    
         n1 = n2;    
         n2 = n3;    
         System.out.print(" "+n3);   
         printFibonacci(count-1);    
     }    
 }    
 public static void main(String args[]){    
  int count=10;    
  System.out.print(n1+" "+n2);//printing 0 and 1    
  printFibonacci(count-2);//n-2 because 2 numbers are already printed   
 }  
}  

Output:

0 1 1 2 3 5 8 13 21 34

2.Write a program to compare two object. Create two objects representing two complex
number and find the larger one.
public class Employee   
{  
private int regno;  
private String name;  
public Employee(int regno, String name)   
{  
this.name = name;  
this.regno = regno;  
}  
public int getRegno()   
{  
return regno;  
}  
public void setRegno(int Regno)   
{  
this.regno = regno;  
}  
public String getName()   
{  
return name;  
}  
public void setName(String name)   
{  
this.name = name;  
}  
}  
public class HashcodeExample  
{  
public static void main(String[] args)   
{  
//creating two instances of the Employee class  
Employee emp1 = new Employee(918, "Maria");  
Employee emp2 = new Employee(918, "Maria");  
//invoking hashCode() method  
int a=emp1.hashCode();  
int b=emp2.hashCode();  
System.out.println("hashcode of emp1 = " + a);  
System.out.println("hashcode of emp2 = " + b);  
System.out.println("Comparing objects emp1 and emp2 = " + emp1.equals(emp2));  
}  
}  

Output:
hashcode of emp1 = 2398801145
hashcode of emp2 = 1852349007
Comparing objects emp1 and emp2 = false

3.Write a Java Program to convert a Number to Word.


class NumberToWordExample1   
{  
static void numberToWords(char num[])  
{  
int len = num.length;  
if (len == 0)   
{  

System.out.println("The string is empty.");  
return;  
}  
if (len > 4)   
{  
System.out.println("\n The given number has more than 4 digits.");  
return;  
}  
String[] onedigit = new String[] {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven"
, "Eight", "Nine"};  
String[] twodigits = new String[] {"", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fift
een", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};  
String[] multipleoftens = new String[] {"",  "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Se
venty", "Eighty", "Ninety"};  
String[] poweroftens = new String[] {"Hundred", "Thousand"};  
argument  
System.out.print(String.valueOf(num) + ": ");  
if (len == 1)   
{  
System.out.println(onedigit[num[0]-'0']);  
return;  
}  
int x = 0;  
while (x < num.length)   
{  

if (len >= 3)   
{  
if (num[x] - '0' != 0)   
{  
System.out.print(onedigit[num[x] - '0'] + " ");  

System.out.print(poweroftens[len - 3]+ " ");  
}  
--len;  
}  
else   
{  
if (num[x] - '0' == 1)   
{  
int sum = num[x] - '0' + num[x + 1] - '0';  
System.out.println(twodigits[sum]);  
return;  
}  
else if (num[x] - '0' == 2 && num[x + 1] - '0' == 0)   
{  
System.out.println("Twenty");  
return;  
}  
else   
{  
int i = (num[x] - '0');  
if (i > 0)  
System.out.print(multipleoftens[i]+ " ");  
else  
System.out.print("");  
++x;  
if (num[x] - '0' != 0)  
System.out.println(onedigit[num[x] - '0']);  
}  
}  
++x;  
}  
}  
public static void main(String args[])  
{  
numberToWords("1111".toCharArray());  
numberToWords("673".toCharArray());  
numberToWords("85".toCharArray());  
numberToWords("5".toCharArray());  
numberToWords("0".toCharArray());  
numberToWords("20".toCharArray());  
numberToWords("1000".toCharArray());  
numberToWords("12345".toCharArray());  
numberToWords("".toCharArray());  
}  
}  

Q. Write a Java Program to copy all elements of one array into another array
public class CopyArray {    
    public static void main(String[] args) {        
        int [] arr1 = new int [] {1, 2, 3, 4, 5};     
        int arr2[] = new int[arr1.length];    
for (int i = 0; i < arr1.length; i++) {     
            arr2[i] = arr1[i];     
        }          
        System.out.println("Elements of original array: ");    
        for (int i = 0; i < arr1.length; i++) {     
           System.out.print(arr1[i] + " ");    
        }     
System.out.println();    
        System.out.println("Elements of new array: ");    
        for (int i = 0; i < arr2.length; i++) {     
           System.out.print(arr2[i] + " ");    
        }     
    }    
}    

Output:
Elements of original array
12345
Elements of new array:
12345

Q.Write a Java Program to sort the elements of an array in ascending order


public class SortAsc {    
    public static void main(String[] args) {        
  int [] arr = new int [] {5, 2, 8, 7, 1};     
        int temp = 0;    
 System.out.println("Elements of original array: ");    
        for (int i = 0; i < arr.length; i++) {     
            System.out.print(arr[i] + " ");    
        }    
        for (int i = 0; i < arr.length; i++) {     
            for (int j = i+1; j < arr.length; j++) {     
               if(arr[i] > arr[j]) {    
                   temp = arr[i];    
                   arr[i] = arr[j];    
                   arr[j] = temp;    
               }     
            }     
        }    
 System.out.println();    
        System.out.println("Elements of array sorted in ascending order: ");    
        for (int i = 0; i < arr.length; i++) {     
            System.out.print(arr[i] + " ");    
        }    
    }    
}    

Output:
Elements of original array:
52871
Elements of array sorted in ascending order:
12578

Q. Write a Applet Program for Background color and foreground color


import java.applet.Applet;
import java.awt.*;                //Color and Graphics belongs to java.awt,
import java.awt.event.*;
public class ColorApplet extends Applet
{
        public static void main(String[] args)
       {
        Frame ForegroundBackgroundColor = new Frame("Change Background and Foreground
Color of Applet");
        ForegroundBackgroundColor.setSize(420, 180);
        Applet ColorApplet = new ColorApplet();
        ForegroundBackgroundColor.add(ColorApplet);
        ForegroundBackgroundColor.setVisible(true);
ForegroundBackgroundColor.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);
}
       });
     }
  public void paint(Graphics g)
{
    Color c = getForeground();
    setBackground(Color.yellow); 
    setForeground(Color.red);   
    g.drawString("Foreground color set to red", 100, 50);
    g.drawString(c.toString(), 100, 80);
   g.drawString("Change Background and Foreground Color of Applet", 50, 100);
 }
}

Q. Write a Java Program to find the frequency of odd & even numbers in the given matrix
public class OddEven    
{    
    public static void main(String[] args) {    
        int rows, cols, countOdd = 0, countEven = 0;    
        int a[][] = {       
                        {4, 1, 3},    
                        {3, 5, 7},    
                        {8, 2, 6}    
                    };    
          rows = a.length;    
        cols = a[0].length;       
        for(int i = 0; i < rows; i++){    
            for(int j = 0; j < cols; j++){    
              if(a[i][j] % 2 == 0)    
                countEven++;    
              else    
                countOdd++;    
            }    
        }    
System.out.println("Frequency of odd numbers: " + countOdd);    
        System.out.println("Frequency of even numbers: " + countEven);    
    }    
}    

Output:
Frequency of odd numbers: 5
Frequency of even numbers: 4

Q. Write a Java Program to determine whether a given string is palindrome


public class PalindromeString    
{    
    public static void main(String[] args) {    
        String string = "Kayak";    
        boolean flag = true;    
        string = string.toLowerCase();    
        for(int i = 0; i < string.length()/2; i++){    
            if(string.charAt(i) != string.charAt(string.length()-i-1)){    
                flag = false;    
                break;    
            }    
        }    
        if(flag)    
            System.out.println("Given string is palindrome");    
        else    
            System.out.println("Given string is not a palindrome");    
    }    
}    

Output:
Given string is palindrome

Q. Write a Java program to draw a pattern such as

a) 2 4
369 b) 000*000*
4 8 12 16 0*00*00*0
00*0*0*00
000***000
b)  public class pattern  
{    
 public static void main(String[] args){    
    int lines=4;    
    int i,j;    
    for(i=1;i<=lines;i++){// this loop is used to print lines    
      for(j=1;j<=lines;j++){// this loop is used to print * in a line    
          if(i==j)    
             System.out.print("*");    
            else    
           System.out.print("0");    
      }    
      j--;    
       System.out.print("*");    
      while(j>=1){// this loop is used to print * in a line    
          if(i==j)    
           System.out.print("*");    
          else    
           System.out.print("0");    
          j--;    
      }    
    System.out.println("");    
  }    
         }    
}    

Q. Write a java program GCD of Two number


import java.util.Scanner;  
public class FindGCDExample4  
{  
//private static Scanner sc;  
public static void main(String[] args)   
{  
int a, b, gcd = 0;  
Scanner sc = new Scanner(System.in);  
System.out.print("Enter the First Number: ");  
a = sc.nextInt();     
System.out.print("Enter the Second Number: ");  
b = sc.nextInt();  
gcd = findGCD(a, b);  
System.out.println("GCD of " + a + " and " + b + " =  " + gcd);  
}  
public static int findGCD(int a, int b)  
{  
while(b != 0)  
{  
if(a > b)  
{  
a = a - b;  
}  
else  
{  
b = b - a;  
}  
}  
return a;  
}  
}  

Output:
Enter the First Number: 75
Enter the Second Number: 125
GCD of 75 and 125 = 25

Q. Write a Java program to convert Decimal to Binary in Java


public class DecimalToBinaryExample2{    
public static void toBinary(int decimal){    
     int binary[] = new int[40];    
     int index = 0;    
     while(decimal > 0){    
       binary[index++] = decimal%2;    
       decimal = decimal/2;    
     }    
     for(int i = index-1;i >= 0;i--){    
       System.out.print(binary[i]);    
     }    
System.out.println();//new line  
}    
public static void main(String args[]){      
System.out.println("Decimal of 10 is: ");  
toBinary(10);    
System.out.println("Decimal of 21 is: ");  
toBinary(21);    
System.out.println("Decimal of 31 is: ");    
toBinary(31);  
}}   

Output:
Decimal of 10 is: 1010
Decimal of 21 is: 10101
Decimal of 31 is: 11111
   

Q. Write a program to add two times given in hour minutes and seconds using class and
object.

import java.io.*;  
import java.util.*;  
class Conversion {  
static void conversion(float hours)  
{  
float minutes, seconds;  
   minutes = hours * 60;  
    seconds = hours * 3600;  
   System.out.println("There are " + minutes + " minutes in " + hours + " hours");  
    System.out.println("There are " + seconds + " seconds in " + hours + " hours");  
}  
    public static void main (String[] args) {  
    float hours;  
    System.out.println("Enter the value of hours: ");  
    Scanner sc = new Scanner(System.in);  
    hours = sc.nextFloat();  
    conversion(hours);  
    }  }  

Q. Write a Java program to find the combination c(n,r) by inheriting from a class that
computes the factorial of a number.
import java.util.*;  
class Combination {   
static int nCr(int n, int r)   
{   
    return fact(n) / (fact(r) *   
    fact(n - r));   
}   
static int fact(int n)   
{   
    int res = 1;   
           for (int i = 2; i <= n; i++)   
           res = res * i;   
          return res;   
}   
public static void main(String[] args)   
{   
int n,r;  
System.out.println("Enter the value of n and r?");  
Scanner sc = new Scanner(System.in);  
n = sc.nextInt();  
r = sc.nextInt();  
System.out.println("nCr = "+nCr(n, r));  
}   
}  

Output:
Enter the value of n and r?
6
4
nCr = 15

Q. Write a Java program to find the area of different geometrical shapes using polymorphism.
public class Main
{
public static void main(String[] args)
{
Rectangle obj = new Rectangle();
obj.Area(30, 20);
obj.Area(12.5, 4.5);
Circle obj1 = new Circle();
obj1.Area(3);
obj1.Area(5.5);
Square obj2 = new Square();
obj2.Area(20);
obj2.Area(5.2);
}
}
class Square
{
void Area(double side)
{
System.out.println("Area of the Square: "+ side * side);
}
void Area(float side)
{
System.out.println("Area of the Square: "+ side * side);
}
}
class Circle
{
static final double PI = Math.PI;
void Area(double r)
{
double A = PI * r * r;
System.out.println("The area of the circle is :" + A);
}
void Area(float r)
{
double A = PI * r * r;
System.out.println("The area of the circle is :" + A);
}
}
class Rectangle
{
void Area(double l, double b)
{
System.out.println("Area of the rectangle: " + l * b);
}
void Area(int l, int b)
{
System.out.println("Area of the rectangle: " + l * b);
}}
Output:-
Area of the rectangle: 600
Area of the rectangle: 56.25
The area of the circle is:28.274333882308138
The area of the circle is:95.03317777109123
Area of the Square: 400.0
Area of the Square: 27.040000000000003

Q. Write a Java program to create a user defined package that finds the largest among an
array of n numbers. Use this package to sort an array of n numbers using insertion/selection
sort.

Insertion Sort:- public class InsertionSortExample {  


    public static void insertionSort(int array[]) {  
        int n = array.length;  
        for (int j = 1; j < n; j++) {  
            int key = array[j];  
            int i = j-1;  
            while ( (i > -1) && ( array [i] > key ) ) {  
                array [i+1] = array [i];  
                i--;  
            }  
            array[i+1] = key;  
        }  
    }  
    public static void main(String a[]){    
        int[] arr1 = {9,14,3,2,43,11,58,22};    
        System.out.println("Before Insertion Sort");    
        for(int i:arr1){    
            System.out.print(i+" ");    
        }    
        System.out.println();    
            insertionSort(arr1);//sorting array using insertion sort    
            System.out.println("After Insertion Sort");    
        for(int i:arr1){    
            System.out.print(i+" ");    
        }    
    }    
}    

Output:
Before Insertion Sort
9 14 3 2 43 11 58 22
After Insertion Sort
2 3 9 11 14 22 43 58

Q. Selection Sort :-
public class SelectionSortExample {  
    public static void selectionSort(int[] arr){  
        for (int i = 0; i < arr.length - 1; i++)  
        {  
            int index = i;  
            for (int j = i + 1; j < arr.length; j++){  
                if (arr[j] < arr[index]){  
                    index = j;//searching for lowest index  
                }  
            }  
            int smallerNumber = arr[index];   
            arr[index] = arr[i];  
            arr[i] = smallerNumber;  
        }  
    }  
      public static void main(String a[]){  
        int[] arr1 = {9,14,3,2,43,11,58,22};  
        System.out.println("Before Selection Sort");  
        for(int i:arr1){  
            System.out.print(i+" ");  
        }  
        System.out.println();  
         selectionSort(arr1);
        System.out.println("After Selection Sort");  
        for(int i:arr1){  
            System.out.print(i+" ");  
        }  
    }  
}  

Output: Before Selection Sort

9 14 3 2 43 11 58 22
After Selection Sort
2 3 9 11 14 22 43 58

Q. Create three threads and print 1 to 10 in each thread.

public class PrintSequenceRunnable implements Runnable{


  public int PRINT_NUMBERS_UPTO=10;
    static int  number=1;
    int remainder;
    static Object lock=new Object();
 PrintSequenceRunnable(int remainder)
    {
        this.remainder=remainder;
    }
 @Override
    public void run() {
        while (number < PRINT_NUMBERS_UPTO-1) {
            synchronized (lock) {
                while (number % 3 != remainder) { // wait for numbers other than remainder
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + " " + number);
                number++;
                lock.notifyAll();
            }
        }
    }
}
public class PrintThreadsSequentiallyMain {
   public static void main(String[] args) {
   PrintSequenceRunnable runnable1=new PrintSequenceRunnable(1);
        PrintSequenceRunnable runnable2=new PrintSequenceRunnable(2);
        PrintSequenceRunnable runnable3=new PrintSequenceRunnable(0);
 Thread t1=new Thread(runnable1,"T1");
        Thread t2=new Thread(runnable2,"T2");
        Thread t3=new Thread(runnable3,"T3");
   t1.start();
        t2.start();
        t3.start();  
    }
}
Output:- T1 – 1
T2 -2
T3-3
T4-4
T5-5
T6-6
T7-7
T8-8
T9-9
T10-10

Q. Write a Java program to illustrate the concept of some exceptions such as divide by zero or
array index out of bound etc.
Arithmetic exception : It is thrown when an exceptional condition has occurred in an
arithmetic operation.
class ArithmeticException_Demo {
public static void main(String args[])
    {
        try {
            int a = 30, b = 0;
            int c = a / b; // cannot divide by zero
            System.out.println("Result = " + c);
        }
        catch (ArithmeticException e) {
            System.out.println("Can't divide a number by 0");
        }
    }
}

ArrayIndexOutOfBounds Exception : It is thrown to indicate that an array has been accessed
with an illegal index. The index is either negative or greater than or equal to the size of the
array.
class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
    {
        try {
            int a[] = new int[5];
            a[6] = 9; // accessing 7th element in an array of
            // size 5
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array Index is Out Of Bounds");
        }
    }
}
ClassNotFoundException : This Exception is raised when we try to access a class whose
definition is not found.

class Bishal {
  
} class Geeks {
  
} class MyClass {
public static void main(String[] args)
    {
        Object o = class.forName(args[0]).newInstance();
        System.out.println("Class created for" + o.getClass().getName());
    }
}
FileNotFoundException : This Exception is raised when a file is not accessible or does not open.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
  
public static void main(String args[])
    {
        try {
              File file = new File("E:// file.txt");
   FileReader fr = new FileReader(file);
        }
        catch (FileNotFoundException e) {
            System.out.println("File does not exist");
        }}}
IOException : It is thrown when an input-output operation failed or interrupted

// Java program to illustrate IOException


import java.io.*;
class Geeks {
public static void main(String args[])
    {FileInputStream f = null;
 f = new FileInputStream("abc.txt");
        int i;
        while ((i = f.read()) != -1) {
            System.out.print((char)i);
        }
  f.close();
    }
}

InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some processing,
and it is interrupted.

class Geeks {
public static void main(String args[])
    {
        Thread t = new Thread();
        t.sleep(10000);
    }
}

NoSuchMethodException : t is thrown when accessing a method which is not found.

class Geeks {
public Geeks()
    {
        Class i;
        try {
            i = Class.forName("java.lang.String");
            try {
                Class[] p = new Class[5];
            }
            catch (SecurityException e) {
                e.printStackTrace();
            }
            catch (NoSuchMethodException e) {
                e.printStackTrace();
            } 
catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
  
public static void main(String[] args)
    {
        new Geeks();
    }
}

StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an index is


either negative than the size of the string.

class StringIndexOutOfBound_Demo {
public static void main(String args[])
    {
        try {
            String a = "This is like chipping "; // length is 22
            char c = a.charAt(24); // accessing 25th element
            System.out.println(c);
        }
        catch (StringIndexOutOfBoundsException e) {
            System.out.println("StringIndexOutOfBoundsException");
        }
    }
}
Q. Bubble Sort
public class BubbleSortExample {  
    static void bubbleSort(int[] arr) {  
        int n = arr.length;  
        int temp = 0;  
         for(int i=0; i < n; i++){  
                 for(int j=1; j < (n-i); j++){  
                          if(arr[j-1] > arr[j]){  
                                 //swap elements  
                                 temp = arr[j-1];  
                                 arr[j-1] = arr[j];  
                                 arr[j] = temp;  
                         }  }  }    }  
  public static void main(String[] args) {  
                int arr[] ={3,60,35,2,45,320,5};  
                 System.out.println("Array Before Bubble Sort");  
                for(int i=0; i < arr.length; i++){  
                        System.out.print(arr[i] + " ");  
                }  
                System.out.println();  
                 bubbleSort(arr);//sorting array elements using bubble sort  
                 System.out.println("Array After Bubble Sort");  
                for(int i=0; i < arr.length; i++){  
                        System.out.print(arr[i] + " ");  
                }  
   }  
}  
Output: Array Before Bubble Sort
3 60 35 2 45 320 5
Array After Bubble Sort
2 3 5 35 45 60 320

Q. Write java program to find smallest index of largest element in an array.


public class LargestNumberIndex
{
public static void main(String[] args)
{
int a[] = new int[] { 12, 44, 23, 56, 23, 78, 13 };
int max = a[0];
int index = 0;
for (int i = 0; i < a.length; i++)
{
if (max < a[i])
{
max = a[i];
index = i;
}
}
System.out.println("Index position of Maximum value in an array is : " + index);
}
}

Q.Write a java program to find distance between two points.


class Point {
private double x;
private double y;
Point(double x, double y) {
this.x = x; this.y = y;
} public double getX()
{ return x;
} public double getY()
{ return y;
}
public double getDistance(Point p)
{
return Math.sqrt((this.getX() - p.getX()) * (this.getX() - p.getX()) + (this.getY() - p.getY()) *
(this.getY() - p.getY()));
}}
public class Sample
{
public static void main(String[] args)
{
Point px = new Point(1, 1);
Point py = new Point(5, 5);
double distance = px.getDistance(py);
System.out.println(distance);
}}

Q. Write a Java Program to store employee details into a list and display values
class EmployeeDetails {  
int emp_id, salary;  
String name, address, department, email;  
public int getEmp_id() {  
    return emp_id;  
}  
public void setEmp_id(int emp_id) {  
    this.emp_id = emp_id;  
}  
public int getSalary() {  
    return salary;  
}  
public void setSalary(int salary) {  
    this.salary = salary;  
}  
public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}  
public String getAddress() {  
    return address;  
}  
public void setAddress(String address) {  
    this.address = address;  
}  
public String getDepartment() {  
    return department;  
}  
public void setDepartment(String department) {  
    this.department = department;  
}  
public String getEmail() {  
    return email;  
}  
public void setEmail(String email) {  
    this.email = email;  
}  
@Override  
public String toString() {  
    return "Employee [emp_id = " + emp_id + ", salary = " + salary + ", name = " + name + ", a
ddress = " + address  
            + ", department = " + department + ", email = " + email + "]";  
    }  
}  
public class Employee{  
    public static void main(String args[]) {  
        EmployeeDetails emp = new EmployeeDetails();  
        emp.setEmp_id(101);  
        emp.setName("Emma Watson");  
        emp.setDepartment("IT");  
        emp.setSalary(15000);  
        emp.setAddress("New Delhi");  
        emp.setEmail("[email protected]");  
        System.out.println(emp);  
 int sal = emp.getSalary();  
        int increment = 0;  
  if ((sal >=1000) && (sal <=1500))  
        {  
            increment += (sal * 2)/100;  
            sal = sal+increment;  
              emp.setSalary(sal);  
            System.out.println("\n Salary is incremented \n");  
            System.out.println(emp);  
 }else if ((sal >=1500) && (sal <=20000)){  
            increment += (sal * 5)/100;  
            sal = sal+increment;  
              emp.setSalary(sal);  
            System.out.println("\n Salary is incremented \n");  
            System.out.println(emp);  
        }else {  
            System.out.println("\n Salary is not incremented \n");  
            System.out.println(emp);  
        }         
    }  
}  

Output

Employee [emp_id = 101, salary = 15000, name = Emma Watson, address = New Delhi,
department = IT, email = [email protected]]
Salary is incremented
Employee [emp_id = 101, salary = 15750, name = Emma Watson, address = New Delhi,
department = IT,

Q. Write a java program to design an exception class invalid data exception


class InvalidAgeException  extends Exception  
{  
    public InvalidAgeException (String str)  
    {  
        super(str);  
    }  
}  
public class TestCustomException1  
{  
      static void validate (int age) throws InvalidAgeException{    
       if(age < 18){  
   throw new InvalidAgeException("age is not valid to vote");    
    }  
       else {   
        System.out.println("welcome to vote");   
        }   
     }    
  
    public static void main(String args[])  
    {  
        try  
        {  
            validate(13);  
        }  
        catch (InvalidAgeException ex)  
        {  
            System.out.println("Caught the exception");  
    System.out.println("Exception occured: " + ex);  
        }  
      System.out.println("rest of the code...");    
    }  
}  

Q. Write a multithreaded program in which a shared int counter is incremented by 3 thread 3


times . When all the threads have finished print the final value of the counter. Initialize the
counter by 0.
Ans. public class Main {
public static void main(String[] args) {
MyObj obj = new MyObj();
for (int i = 0; i < 3; i++) {
Threaded t = new Threaded("Thread " + i, obj);
Thread thread = new Thread(t);
thread.start();
}
}
}
class MyObj {
private int count = 0;

public void inc() { count++; }

public int getCount() { return count; }


}

class Threaded implements Runnable {

private final String name;


private final MyObj obj;

public Threaded(String name, MyObj obj) {


this.name = name;
this.obj = obj;
}

@Override
public void run() {
for (int i = 0; i < 5; i++) {
obj.inc();
System.out.println(name + ": " + obj.getCount());
}
}
}

You might also like