Java Experiments
Java Experiments
JAVA Experiments
Experiment no :- 01
Problem Statement: Create a class Book and define a display method to display book
information. Inherit Reference_Book and Magazine classes from Book class and override display
method of Book class in Reference_Book and Magazine classes. Make necessary assumptions
required.
Theory:
Inheritance : The process by which one class acquires the properties(data members) and
functionalities(methods) of another class is called inheritance.
Super Class: The class whose features are inherited is known as superclass(or a base class or a
parent class).
Sub Class: The class that inherits the other class is known as subclass(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition to
the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can derive
our new class from the existing class. By doing this, we are reusing the fields and methods of
the existing class.
Syntax:
class derived-class extends base-class
{
//methods and fields
}
Types Of Inheritance :
1 .Single Inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple Inheritance
5. Hybrid inheritance
Algorithm:
1. Start the Program
2. Create a Class
3. Declare the Display Method in different names of Books
4. Create another class and Extend the Parent class with declare display method
5. Call the main method and create object
6. Display the object
7. Stop the Program
Program:
class Book
{
void display()
{
System.out.println("Name - The Complete Reference Java 2");
System.out.println("Author - Herbert Schildt");
}
}
class Reference_Book extends Book
{
void display()
{
System.out.println("Name - Pure Java 2");
System.out.println("Author - Kenneth Litwak");
}
}
class Magazine extends Book
{
void display()
{
System.out.println("Name - Core Java");
System.out.println("Author - Cay S. Horstmann");
}
}
class TestInheritance
{
public static void main(String args[])
{ Book b; b=new Book();
b.display(); b=new
Reference_Book();
b.display(); b=new
Magazine(); b.display();
}
}
Conclusion:
Inheritance is a strong weapon of Java that helps to make it a widely acceptable language. It
helps to reduce code duplication and also cuts down on the bugs. With the code written in the
parent class, you no longer need to write the same code for multiple child classes that has the
same properties.
Experiment no :- 02
Title : To create classes for students and adding constructor and method in each
class using inheritance.
Theory:
Prior concept:
1) Classes, Objects and Variables
2) Constructor
3) Method
Syntax: class_name
object_name;
Array-
Array of Objects-
Syntax:
//Define an array of 5 objects of class student for (int i=0; i<5; i++)
Constructor-
Constructor is a special type of method which enables to initialize an object
when it is first created. It has the same name as the class in which it is declared.
It does not specify a return type not even void.
Syntax:
ConstructorName()
// initialization statements
Syntax:
// initialization statements
Types of Constructors:
● Default Constructor
● Parameterized Constructor
● Copy Constructor
● Default argument Constructor ● Multiple Constructor
Methods-
Java methods are where you put the operations on data (variables) in your Java
code. In other words, you group Java operations (code) inside Java methods. Java
methods must be located inside a Java class.
public MyClass{
}
}
Types of methods:
Program:
import java.io.*;
class graduate_student{
int Roll no,Marks;
string Name,subject;
try {
System.out.print("Enter Marks");
Roll no=Integer.parseInt(br.readline())
Marks=Integer.parseInt(br.readline())
System.out.print("Enter Name");
System.out.print("Enter Subject")
Name=Integer.parseInt(br.readline())
Subject=Integer.parseInt(br.readline())
} catch(Exception
e){
void display() {
int i;
graduate_student g[]= new graduate_student[5]
for(i=0; i<5; i++)
{ g[i]=new graduate_student();
} for(i=0; i<5; i++) {
g[i].accept(); } for(i=0; i<5;
i++)
{ g[i].display(); }
class research_student{
int Roll no,Marks;
string Name,subject;
void accept()
try {
System.out.print("Enter Marks");
Roll no=Integer.parseInt(br.readline())
System.out.print("Enter Subject")
Name=Integer.parseInt(br.readline())
Subject=Integer.parseInt(br.readline())
} catch(Exception
e){
void display() {
int i;
}
}
Output:
For Research Students;
Conclusion: So, Here we have displayed students records with their following attributes using
inheritance of interface in java.
Experiment no :- 03
(iii) Create a method named display_all_info with suitable parameters. This method should
display all the information about the object of a class.
Algorithm:
Step 1: Start the program.
Step 5: Declare and define constructor Hockey and derive the fuction and from the
Interface and define it.
Step 6: Declsre the class Athletc and implements the interface Sportperson.
Step 7: Declare and define constructor Athletc and derive the fuction and from
the Interface and define it.
Step 9: Declare the derived class object and call the function using object and also
invoke the constructor.
void display_all_info();
String name;
int age; int
goals;
{ name =
n; age =
a; goals =
g; }
System.out.println("Hockey Player:" + " Name: "+ name + " Age: "+ age +"
Number of goals:" + goals);
String type;
String name;
int age;
{ name =
n; age =
a; type =
t;
System.out.println("Athlete:" + " Name: "+ name + " Age: "+ age +" Type of
athlete:" + type);
}
}
}}
Atual Input/Output:
Experiment no :- 04
Title:-
Inheritance And Exceptional Handling
Problem statement:-
Java program to create:-
i. A Class called Account that creates account with 1000Rs minimum
balance, a deposit() method to deposit amount, a withdraw() method to
withdraw amount and also throws LessBalanceException if an account holder
tries to withdraw money which makes the balance become less than 1000Rs.
ii. A Class called LessBalanceException which returns the statement that
says withdraw amount ( Rs) is not valid. iii. A Class which creates 2 accounts,
both account deposit money and one account tries to withdraw more money
which generates a LessBalanceException take appropriate action for the same.
Theory:-.
Exception handling is one of the most important feature of java programming that
allows us to handle the runtime errors caused by exceptions. In this guide, we
will learn what is an exception, types of it, exception classes and how to handle
exceptions in java with examples.
Algorithm :-
1.The try-catch block is used to handle exceptions in Java. Here's the syntax of
try...catch block:
try {
// code
} catch(Exception e)
{ // code
2.Here, we have placed the code that might generate an exception inside the try block.
Every try block is followed by a catch block.
3.When an exception occurs, it is caught by the catch block. The catch block cannot
be used without the try block.
Program:-
import java.io.*; class LessBalanceException
extends Exception
double amt;
LessBalanceException(double wamt)
amt=wamt;
} class
Account
Account(){bal=500.0;
}
public void deposit(double damt)
bal=bal+damt;
{ if((bal-wamt)<=1000)throw(new
LessBalanceException(wamt)); else{bal=bal-wamt;
System.out.println("Amount withdrawn:"+wamt);
System.out.println("balance:"+bal);
System.out.println("balance of a1:"+a1.bal);
System.out.println("balance of a2:"+a2.bal);
try
a1.withdraw(4000);
a2.withdraw(5000);
catch(LessBalanceException e)
{
System.out.println("cant withdraw"+e);
Conclusion:-
Thus we have created account using java program
Experiment no :- 05
Title : Create two threads such that one thread will print even number and another
will print odd number in an ordered fashion.
Theory :
Multithreading in Java :
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread Object class and implements Runnable interface.
Prog
ram :
public class PrintEvenOddTester {
public static void main(String... args) {
Printer print = new Printer();
this.isEvenNumber = isEvenNumber;
@Override
public void run() {
} else {
print.printOdd(number);
}
number += 2;
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Even:" + number);
isOdd = false; notifyAll();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Odd:" + number);
isOdd = true; notifyAll();
Input/output :
Conclusion : we had a look at how we can print odd and even numbers
alternatively using two threads in Java.
Experiment no :- 06
Aim : Assume that two brothers, Joe and John, share a common bank account.
They both can, independently, read the balance, make a deposit, and withdraw
some money. Implement java application demonstrate how the transaction in a
bank can be carried out concurrently.
Theory :
Exception Handling :
Dictionary Meaning:
There are mainly two types of exceptions: checked and unchecked. Here, an error
is considered as the unchecked exception. According to Oracle, there are three
types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
Checked Exception –
The classes which directly inherit Throwable class except RuntimeException and
Error are known as checked exceptions e.g. IOException, SQLException etc.
Checked exceptions are checked at compile-time.
Unchecked Exception –
The classes which inherit RuntimeException are known as unchecked exceptions
e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
Error - Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Synchronization :
Program:
public class AccountTesting implements Runnable
{ private Account acct = new Account(); public
static void main(String[] args) {
@Override
System.out.println("account is overdrawn!");
}
}
}
System.out.println(Thread.currentThread().getName() + " is
going to withdraw");
try {
Thread.sleep(100);
acct.withdraw(amt);
System.out.println(Thread.currentThread().getName() + "
completes the withdrawal");
} else {
} } class Account {
private int balance = 50; public
Output :
Experiment no :- 07
Aim: Study of Swing
LO Number: 2-Design and develop Graphical User Interface using Abstract Window
Toolkit and Swings along with response to the events.
Theory:
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
1) JButton: JButton class is used to create a push-button on the UI. The
button can contain some display text or image. It generates an event when clicked
and double-clicked. A JButton can be implemented in the application by calling
one of its constructors.
Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
11) JTree: The JTree class is used to display the tree structured data or
hierarchical data. JTree is a complex component. It has a 'root node' at the top
most which is a parent for all nodes in the tree. It inherits JComponent class.
12) JTable: The JTable class is used to display data in tabular form. It is
composed of rows and columns.
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
jmb.setBounds(1,1,800,20); JMenu
jm.add(i1);
jm.add(i2);
jm.add(i3);
jm.add(i4);
jmb.add(jm);
jf.add(jmb);
type.setBounds(150,100,150,50);
jf.add(type);
jrd1.setBounds(15,200,100,30);
jrd2.setBounds(15,240,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(jrd1);
bg.add(jrd2);
jf.add(jrd1);
jf.add(jrd2);
String[] week=
{ "January","Feburary","March","April","May","June","July"};
JList list= new JList(week) ;
JScrollPane jsp=new
JScrollPane(list);
jsp.setBounds(150,250,100,80);
jsp.getViewport().add(list);
jf.add(jsp);
JTable jtab=new
JTable(rows,column); JScrollPane sp = new
JScrollPane(jtab);
sp.setBounds(30,400,200,80);
sp.getViewport().add(jtab); jf.add(sp);
jbt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(jbt, "User
Registered");
}
}) ;
DefaultMutableTreeNode main=new
DefaultMutableTreeNode("MAIN");
DefaultMutableTreeNode top=new
DefaultMutableTreeNode("Options");
top.add(a1);
top.add(a2);
top.add(a3);
top2.add(b1);
top2.add(b2);
top2.add(b3);
main.add(top);
main.add(top2);
jf.setVisible(true) ;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Expt13 obj=new Expt13();
}
}
Output:
Conclusion:
Created a GUI with basic Java Swing Components. A Menu Bar is created in
which menu is included. In the menu there is menu items like File ,Open, Save
and Exit. Label is used to display some information on the frame like here it is
used to display Enter Name. In front of the label a text box is used to take input
from user. There is ComboBox for selecting one item from the drop down. A
table is used to display information of students. There is a list to select name of
month. Scroll Pane is added to table and list for scrolling vertically. A tree is
created with two sub tree named option and option 2. Both the sub trees have
three sub tree. At the end of the frame button named SUBMIT is created. The
button is added an ActionListener. When button is clicked a message box appears
with message written as “User Registered”.
Experiment no :- 08
Title : Write a java program to create a student profile form using AWT
controls.
Problem Statement :
Java program to store a Student Information in a File using AWT.
Theory :
Swing is a part of the JFC (Java Foundation Classes). Building Graphical User
Interface in Java requires the use of Swings. Swing Framework contains a large
set of components which allow a high level of customization and provide rich
functionalities, and is used to create window-based applications. Java swing
components are lightweight, platform-independent, provide powerful
components like tables, scroll panels, buttons, list, colour chooser, etc.
In this article, we will see how to write the students information in a Jframe and
store it in a file.
Algorithm :
Program :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
String s1 = t1.getText();
String s2 = t2.getText();
String s3 = j1.getSelectedItem() + "";
String s4 = j2.getSelectedItem() + "";
String s5 = t3.getText();
if (e.getSource() == b1) {
try {
w.write(s1 + "\n");
w.write(s2 + "\n");
w.write(s3 + "\n");
w.write(s4 + "\n");
w.write(s5 + "\n");
w.close();
}
catch (Exception ae) {
System.out.println(ae);
}
}
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
Actual input/output :
a) The window displayed on running the program:
Experiment no :- 09
Title: To study GUI programming- I(AWT,Event Handling, Swing) and
implement the program.
Theory:
1.The GridLayout class is a layout manager that lays out a container's
components in a rectangular grid.
4.The JButton class is used to create a labeled button that has platform
independent implementation.
5.JLabel is used to display a short string or an image icon. JLabel can display
text, image or both.
7 .The Color class is used to encapsulate colors in the default sRGB color .
9 .The setSize() method of Java Vector class is used to set the size of a vector.
10.The getContentPane() method retrieves the content pane layer so that you
can add an object to it.
12.setTitle(String title) Sets the title for this frame to the specified string.
Algorithm:
Algorithm Steps:
Step 1: Write a html applet tag with code set class name and comment the tag
Step 3: Define a class that extends applet and implements action listener and
action listener
iii)Add action listener to each button and add all of them to button panel iv) If
background is checked then set the background color to the selected color
iii) If background is checked then set the background color to the selected color
Program:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
JFrame f;
public abcd()
{
f = new JFrame() ;
red = new JButton("red") ;
green = new JButton("green") ;
blue = new JButton("blue") ;
yellow = new JButton("yellow") ; black
= new JButton("black") ;
cyan = new JButton("cyan") ; pink
= new JButton("pink") ; orange =
new JButton("orange") ; gray = new
JButton("gray") ;
red.addActionListener(this) ;
green.addActionListener(this) ; blue.addActionListener(this)
; yellow.addActionListener(this) ;
black.addActionListener(this) ;
cyan.addActionListener(this) ;
pink.addActionListener(this) ;
orange.addActionListener(this) ;
gray.addActionListener(this) ;
f.add(red);
f.add(green);
f.add(blue) ;
f.add(yellow) ;
f.add(black) ;
f.add(cyan) ;
f.add(pink) ;
f.add(orange) ;
f.add(gray) ;
f.add(label) ;
f.setVisible(true) ;
f.setSize(500,500);
f.setTitle("Color Changer") ;
f.setLayout(new GridLayout(4,3,40,40));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
f.getContentPane().setBackground(Color.white) ;
if (e.getSource() == green)
{
label.setText("Green selected") ;
f.getContentPane().setBackground(Color.GREEN) ;
}
if(e.getSource() == blue)
{
label.setText("Blue selected") ;
f.getContentPane().setBackground(Color.BLUE) ;
}
if(e.getSource() == yellow)
{
label.setText("Yellow selected") ;
f.getContentPane().setBackground(Color.YELLOW) ;
}
if (e.getSource() == black)
{ label.setText("black
selected") ;
f.getContentPane().setBackground(Color.BLACK) ;
if (e.getSource() == cyan)
{
label.setText("Cyan selected") ;
f.getContentPane().setBackground(Color.CYAN) ;
}
if(e.getSource() == pink)
{
label.setText("Pink selected") ;
f.getContentPane().setBackground(Color.PINK) ;
}
if(e.getSource() == orange)
{
label.setText("orange selected") ;
f.getContentPane().setBackground(Color.ORANGE) ;
}
if(e.getSource() == gray)
{ label.setText("Grey
selected") ;
f.getContentPane().setBackground(Color.GRAY) ;
} }