JAVA
JAVA
JAVA
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.
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 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;
}
}
}
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.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
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 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);
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.");
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
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.
Constructor Description
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).
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();
}
}
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.
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();
}
}
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.
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.
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)
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.
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.");
}
}
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 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
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();
}
}
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();
}
}
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.
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();
}
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
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();
} }
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
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
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.
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
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.
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
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);
}
}
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");
}
}
}
Rest of code….
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
Thread in java
Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
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.
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();
}
}
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).
1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;
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;
}
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.
Q. Thread Communication
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
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
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.
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.
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
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));
}
}
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.
Output:
Bike is created
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.
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.
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.
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();
}}
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.
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.
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.
1) Private
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.
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.
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
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
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
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
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));
}}
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:
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
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.
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.
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.
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:
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
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 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.
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();
}
}
}
}
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
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):
try {
if (myObj.createNewFile()) {
} else {
} catch (IOException e) {
e.printStackTrace();
}
Write To a File
try {
myWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
Read a File
We use the Scanner class to read the contents of the text file
try {
while (myReader.hasNextLine()) {
System.out.println(data);
myReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Delete a File
if (myObj.delete()) {
} else {
System.out.println("Failed to delete the file.");
The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.
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.
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.
Operators in Java
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 arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
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.
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 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 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.
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
Output:
false
10
false
11
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
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);
}
}
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 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.
A String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.
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
}
}
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. }
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
}
}
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. }
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
}
}
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
}
}
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
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.
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
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
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
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
Output:
Elements of original array:
52871
Elements of array sorted in ascending order:
12578
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
Output:
Given string is palindrome
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("");
}
}
}
Output:
Enter the First Number: 75
Enter the Second Number: 125
GCD of 75 and 125 = 25
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.
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+" ");
}
}
}
9 14 3 2 43 11 58 22
After Selection Sort
2 3 9 11 14 22 43 58
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
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);
}
}
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();
}
}
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 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,
@Override
public void run() {
for (int i = 0; i < 5; i++) {
obj.inc();
System.out.println(name + ": " + obj.getCount());
}
}
}