OOPS Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

Lab Manual OOP with JAVA

KCA-251
Session: 2021-22
INDEX
UNIT 1: Java Basic Programs:
1. Write a Java program to insert 3 numbers from keyboard and find out greater number
among 3 numbers.
2. Write a Java program to find out the sum of command line arguments.
3. Write a Java program to create a Room class, the attributes of this class is roomno,
roomtype, roomarea and ACmachine. In this class the member functions are setData and
displayData. Use member function to set data and display that data using displayData()
method.
4. Write a Java program to create a class “SimpleObject” and display message by using
constructor of this class.
5. Write a program to demonstrate static variables, methods, and blocks.

UNIT 2: Java Object Oriented Programs:


1. Write a Java program to create a class named Shape and create three sub classes Circle,
Triangle and Square, each class has two-member function named draw () and erase ().
Implement this concepts using polymorphism.
2. Write a Java program to give a simple example for abstract class.
3. Write a Java program to give example for multiple inheritance in Java.
4. Write a Java program to create class Number with only one private instance variable as a
double primitive type, include the following methods isZero(), isPositive(), isNegative( ),
isOdd( ), isEven( ), isPrime(), isAmstrong() in this class and all above methods should
return boolean primitive type like for isPositive() should return “Positive = True”.

UNIT 3: Java Exception Handling:


1. Write a Java program to illustrate usage of try\catch with finally clause.
2. Write a Java program to describe usage of throws clause.
3. Write a Java program for creation of user defined exception.
4. Create a class Customer having following members:

private String custNo


private String custName
private String category

Parameterized constructor to initialize all instance variables


Getter methods for all instance variables

Perform following validations in the constructor

• custNo must start with ‘C’ or ‘c’


• custName must be atleast of 4 characters
• category must be either ‘Platinum’, ‘Gold’ or ‘Silver ‘

When any of these validations fail, then raise a user defined exception
InvalidInputException

Create a class TestCustomer having main method. Ask user to enter customer details.
Create an object of Customer and perform validations. Print details of customer.

5. Write a Java program to create a text file in the path c:\Java\abc.txt and check whether
that file exists or not. Using the command exists(), isDirectory(), isFile(), getName() and
getAbsolutePath().

6. Create a class Employee having members as follows:


private int empNo
private String empName
private int empBasic
Parameterized constructor to initialize members.
Getter methods for all instance variables
Create a class WriteEmployee having main method. Ask user to enter details of an
employee and set them in an Employee object. Store details of this object in a file
emp.txt.
Read employee details from the file and display those details.

UNIT 4: Java Multi-Threading Programs:


1. Create a class MyThread derived from Thread class and override the run method.

Create a class ThreadDemo having main method. Create 2 objects of MyThread class and
observe the behavior of threads

2. Modify the above to create MyThread class by implementing Runnable interface and
observe the behavior of threads.

3. Assign different priorities to the 2 threads and observe the behaviour

4. Implement three classes: Storage, Counter and Printer

The Storage class should store an integer.


The Counter class should create a thread and starts counting from 0 (0,1,2, 3 ...) and
stores each value in the Storage class.
The Printer class should create a thread that keeps reading the value in the Storage class
and printing it.

Write a program that creates an instance of the Storage class and set up a Counter and
Printer object to operate on it.
UNIT 5: Java GUI Applications:
1. Design and implement a GUI for the Temperature class. One challenge of this design
is to find a good way for the user to indicate whether a Fahrenheit or Celsius value is
being input. This should also determine the order of the conversion: F to C or C to F.
[C/5 = (F -32)/9]
2. Design and implement a GUI application for Calculator same as Windows OS
calculator.
3. Design and create small notepad type application using Swing/AWT.
Unit -1

Experiment-1
Objective: JAVA basic programs
Scheduled Date Compiled Date Submission Date
10-April-2021 12-April-2021 19-April-2021

Program:- Write a Java program to insert 3 numbers from


keyboard and find out greater number among 3 numbers.

import java.util.Scanner;

class Greatest
{
int num1,num2,num3;
void getdata()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter number1=");
num1=input.nextInt();
System.out.println("Enter number2=");
num2=input.nextInt();
System.out.println("Enter number3=");
num3=input.nextInt();
if(num1>=num2&&num1>=num3)
{
System.out.println("greatest"+num1);
}
else if(num2>=num1&&num2>=num3)
{
System.out.println("greatest"+num2);
}
else if(num3>=num1&&num3>=num2)
{
System.out.println("greatest"+num3);
}
else
{
System.out.println("all are equal");
}
}
}
public class GreatestMain {

public static void main(String[] args) {


// TODO Auto-generated method stub
Greatest g = new Greatest();
g.getdata();

Output:-
Experiment-2
Objective: JAVA basic programs
Scheduled Date Compiled Date Submission Date
10-April-2021 12-April-2021 19-April-2021

Program:- Write a Java program to find out the sum of


command line arguments.

public class CommandLineEx


{
public static void main(String args[])
{
int sum=0;
String data="";
if(args.length>0)
{
for(int i=0;i<args.length;i++)
{
data=args[i];

sum=sum+Integer.parseInt(data);
}
/*for(String data:args)
{
sum=sum+Integer.parseInt(data);
}*/
System.out.println(sum);
}
else
{
System.out.println("you did not pass
any command line argument");
}
}
}

Output:-
Experiment-3
Objective: JAVA basic programs
Scheduled Date Compiled Date Submission Date
10-April-2021 12-April-2021 19-April-2021

Program:- Write a Java program to create a Room class, the


attributes of this class is roomno, roomtype, roomarea and
ACmachine. In this class the member functions are setData and
displayData. Use member function to set data and display that
data using displayData() method.

import java.util.Scanner;

class Room
{
int roomno;
String roomtype,roomarea,acmachine;
void setData()
{
Scanner input = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
System.out.println("Enter room no=");
roomno=input.nextInt();
System.out.println("Enter room type=");
roomtype=sc.nextLine();
System.out.println("Enter room area=");
roomarea=sc.nextLine();
System.out.println("Enter AC machine=");
acmachine=sc.nextLine();
}
void displayData()
{
System.out.println("room no:"+roomno);
System.out.println("room type:"+roomtype);
System.out.println("room area:"+roomarea);
System.out.println("AC machine:"+acmachine);
}
}
public class MainRoom {

public static void main(String[] args) {


// TODO Auto-generated method stub
Room r = new Room();
r.setData();
r.displayData();

Output:-
Experiment-4
Objective: JAVA basic programs
Scheduled Date Compiled Date Submission Date
10-April-2021 12-April-2021 19-April-2021

Program:- Write a Java program to create a class “SimpleObject”


and display message by using constructor of this class.

class SimpleObject
{
SimpleObject()
{
System.out.println("I am in class simple
object default constructor");
}
SimpleObject(int a)
{
System.out.println("I am in super class
parameterized constructor");
}
}
public class MainSimple {

public static void main(String[] args) {


// TODO Auto-generated method stub
new SimpleObject();
new SimpleObject(100);

Output:-
Experiment-5
Objective: JAVA basic programs
Scheduled Date Compiled Date Submission Date
10-April-2021 12-April-2021 19-April-2021

Program:- Write a program to demonstrate static variables,


methods, and blocks.

public class MainStatic


{
static int i=10;
static
{
m1();
System.out.println("first static block");
}

public static void main(String[] args) {


// TODO Auto-generated method stub
m1();
System.out.println("Main method");

}
public static void m1()
{
System.out.println(j);
}
static
{
System.out.println("second static block");
}
static int j=20;
}

Output:-
Unit -2

Experiment-1
Objective: JAVA object oriented programs
Scheduled Date Compiled Date Submission Date
20-April-2021 25-April-2021 04-May-2021

Program:- Write a Java program to create a class named Shape


and create three sub classes Circle, Triangle and Square, each
class has two-member function named draw () and erase ().
Implement this concepts using polymorphism.
class Shape
{
void draw()
{
System.out.println("shape is draw");
}
void erase()
{
System.out.println("shape is erase");
}

}
class Circle extends Shape
{
void draw() //overriding
{
System.out.println("circle is draw");
}
void erase() //overriding
{
System.out.println("circle is erase");
}
}
class Triangle extends Shape
{
void draw(int x) //overloading
{
System.out.println("Triangle is draw");
}
void erase() //overriding
{
System.out.println("Triangle is erase");
}
}
class Square extends Shape
{
void draw() //overriding
{
System.out.println("square is draw");
}
void erase() //overriding
{
System.out.println("square is erase");
}
}
public class ShapeMain {

public static void main(String[] args) {


// TODO Auto-generated method stub
Circle c= new Circle();
c.draw();
c.erase();
Triangle t = new Triangle();
t.draw();
t.draw(10);
t.erase();
Square s = new Square();
s.draw();
s.erase();
Shape s1 = new Circle();
s1.draw();
s1.erase();

Experiment-2
Objective: JAVA object oriented programs
Scheduled Date Compiled Date Submission Date
20-April-2021 25-April-2021 04-May-2021
Program:- Write a Java program to give a simple example for
abstract class.

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..");
}
}

public class AbstractMain


{
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
obj.changeGear();
}

Output:-

Experiment-3
Objective: JAVA object oriented programs
Scheduled Date Compiled Date Submission Date
20-April-2021 25-April-2021 04-May-2021

Program:- Write a Java program to give example for multiple


inheritance in Java.

class A
{
String msg="hello i am in class";
void getmsg()
{
System.out.println(msg);
}

}
class B extends A //single inheritance
{
void getBmsg()
{
System.out.println("this is new msg by class
B");
}
}
class C extends B //multilevel inheritance supported
{
C()
{
System.out.println("this is class C");
}
}
/*class c extends A,B //multiple inheritance not
supported
{

}*/
public class InheritanceEx {

public static void main(String[] args) {


// TODO Auto-generated method stub
//B b1= new B();
//b1.getmsg();
//b1.getBmsg();
C c1= new C();
c1.getmsg();
c1.getBmsg();

Output:-
Experiment-4
Objective: JAVA object oriented programs
Scheduled Date Compiled Date Submission Date
20-April-2021 25-April-2021 04-May-2021

Program:- Write a Java program to create class Number with


only one private instance variable as a double primitive type,
include the following methods isZero(), isPositive(), isNegative( ),
isOdd( ), isEven( ), isPrime(), isAmstrong() in this class and all
above methods should return boolean primitive type like for
isPositive() should return “Positive = True”.

class Number
{
private double n;
Number(int n)
{
this.n=n;
}
public boolean isZero()
{
if(n==0)
return true;
else
return false;
}
public boolean isPositive()
{
if(n>0)
return true;
else
return false;
}
public boolean isNegative()
{
if(n<0)
return true;
else
return false;
}
public boolean isOdd()
{
if(n%2!=0)
return true;
else
return false;
}
public boolean isEven()
{
if(n%2==0)
return true;
else
return false;
}
public boolean isPrime()
{
double a=2,f=0;
while(a<n)
{
if(n%a==0)
{
f=1;
break;
}
a++;

}
if(f==0)
return true;
else
return false;

}
public boolean isArmstrong()
{
double m;
double temp,sum=0;
temp=n;
while(n>0)
{
m=n%10;
sum=sum+m*m*m;
n=n/10;
}
if(sum==temp)
return true;
else
return false;

}
}
public class NumberMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
Number n1= new Number(10);
System.out.println("zero="+n1.isZero());

System.out.println("positive="+n1.isPositive());

System.out.println("nagative="+n1.isNegative());
System.out.println("odd="+n1.isOdd());
System.out.println("even="+n1.isEven());
System.out.println("prime="+n1.isPrime());

System.out.println("armstrong="+n1.isArmstrong())
;
}
}
Output:-
Unit -3

Experiment-1
Objective: JAVA Exception Handling
Scheduled Date Compiled Date Submission Date
25-May-2021 01-June-2021 03-June-2021

Program:- Write a Java program to illustrate usage of try\catch with finally


clause.
package filehandling;

import java.io.File;
import java.io.IOException;

public class CanExecute {

public static void main(String[] args) {


// TODO Auto-generated method stub
File f = new File("newfile.txt");
if(f.exists())
{
System.out.println("file exists");
System.out.println(f.getAbsolutePath());
if(f.canExecute())
{
System.out.println("this is executable
file");
}
if(f.canRead())
{
System.out.println("this file can be
read");
}
if(f.canWrite())
{
System.out.println("this file is
writable");
}
}
else
{
System.out.println("file does not exists");
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
System.out.println("new file created");
System.out.println("thanks for using our
services");
}

Output:-
Experiment-2
Objective: JAVA Exception Handling
Scheduled Date Compiled Date Submission Date
25-May-2021 01-June-2021 03-June-2021

Program:- Write a Java program to describe usage of throws


clause.
package exceptionhandling;
class Voter
{
int age;
Voter(int age)
{
this.age=age;
}
boolean checkAge() throws Exception
{
if(age<18)
{
throw new Exception("age should be greater
then 18");
}
else
{
return true;
}
}
void checkValidity() throws Exception
{
if(checkAge())
{
System.out.println("you can vote");
}
}
}
public class CustomException {

public static void main(String[] args) {


// TODO Auto-generated method stub
Voter v= new Voter(20);
try {
v.checkValidity();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Output:-

Experiment-3
Objective: JAVA Exception Handling
Scheduled Date Compiled Date Submission Date
25-May-2021 01-June-2021 03-June-2021

Program:- Write a Java program for creation of user defined


exception.
package exceptionhandling;
@SuppressWarnings("serial")
class CheckAgeException extends Exception
{
String msg;
CheckAgeException(String msg)
{
this.msg=msg;
}
public String toString()
{
return msg;
}

}
class CanVote
{
int age;
void checkAge(int age) throws CheckAgeException
{
if(age<18)
{
throw new CheckAgeException("your age should
be greater then 18");
}
else
{
System.out.println("you can vote");
}
}
}
public class UserDefineException {

public static void main(String[] args) {


// TODO Auto-generated method stub
CanVote v = new CanVote();
try {
v.checkAge(13);
} catch (CheckAgeException e) {
// TODO Auto-generated catch block
System.out.println(e.toString());
}
}

}
Output:-

Experiment-4
Objective: JAVA Exception Handling
Scheduled Date Compiled Date Submission Date
25-May-2021 01-June-2021 03-June-2021

Program:- Create a class Customer having following members:

private String custNo

private String custName

private String category

Parameterized constructor to initialize all instance variables


Getter methods for all instance variables

Perform following validations in the constructor

· custNo must start with ‘C’ or ‘c’

· custName must be atleast of 4 characters

· category must be either ‘Platinum’, ‘Gold’ or ‘Silver ‘

When any of these validations fail, then raise a user defined


exception InvalidInputException

Create a class TestCustomer having main method. Ask user to enter


customer details. Create an object of Customer and perform validations.
Print details of customer.

package exceptionhandling;

import java.util.Scanner;

@SuppressWarnings("serial")
class InvalidInputException extends Exception{
String msg;
InvalidInputException(String msg)
{
this.msg=msg;
}
public String toString()
{
return msg;
}
}
class Customer
{
String custNo,custName,category;
Customer(String custNo,String custName,String category)
{
this.custNo=custNo;
this.custName=custName;
this.category=category;
}
public void customerNo()
{
try
{
if(custNo.charAt(0)=='c'||custNo.charAt(0)=='C')
{
System.out.println(custNo);
}
else
{
throw new InvalidInputException("customer no
is not valid");
}
}catch(InvalidInputException e)
{
System.out.println(e.toString());
}
}
public void customerName()
{
try {
if(custName.length()>=4)
{
System.out.println(custName);
}
else
{
throw new InvalidInputException("customer
name is not valid");
}
}catch(InvalidInputException e)
{
System.out.println(e.toString());
}
}
public void custCategory()
{
try {

if(category.equals("Platinum")||category.equals("Gold")|
|category.equals("Silver"))
{
System.out.println(category);
}
else
{
throw new InvalidInputException("customer
category is not valid");
}
}catch(InvalidInputException e)
{
System.out.println(e.toString());
}
}
}

public class TestCustomer {

public static void main(String[] args) {


// TODO Auto-generated method stub
String s1,s2,s3;
Scanner input = new Scanner(System.in);
System.out.println("Enter customer no=");
s1=input.nextLine();
System.out.println("Enter customer name=");
s2=input.nextLine();
System.out.println("Enter category=");
s3=input.nextLine();
Customer c= new Customer(s1,s2,s3);
c.customerNo();
c.customerName();
c.custCategory();
input.close();

Output:-
Experiment-5
Objective: JAVA Exception Handling
Scheduled Date Compiled Date Submission Date
25-May-2021 01-June-2021 03-June-2021

Program:- Write a Java program to create a text file in the path


c:\Java\abc.txt and check whether that file exists or not. Using the
command exists(), isDirectory(), isFile(), getName() and
getAbsolutePath().

package filehandling;

import java.io.File;

public class FileList {


public static void main(String[] args) {
// TODO Auto-generated method stub
File directoryPath = new File("C:\\Users\\Vidhi
Agarwal\\eclipse-workspace\\vidhi\\src\\filehandling");
File filesList[] = directoryPath.listFiles();
System.out.println("list of files and directories
in the specified directory");
for(File file:filesList)
{
System.out.println("file name:"+file.getName());
String path = file.getAbsolutePath();
System.out.println("file path:"+path);

System.out.println("extension:"+path.substring(path.lastInde
xOf('.')));
System.out.println("size :"+file.getTotalSpace());
System.out.println(" ");
}
}

Output:-
Experiment-6
Objective: JAVA Exception Handling
Scheduled Date Compiled Date Submission Date
25-May-2021 01-June-2021 03-June-2021

6. Program:- Create a class Employee having members as follows:

private int empNo

private String empName

private int empBasic

Parameterized constructor to initialize members.

Getter methods for all instance variables


Create a class WriteEmployee having main method. Ask user to enter
details of an employee and set them in an Employee object. Store details
of this object in a file emp.txt.

Read employee details from the file and display those details.

package filehandling;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class WriteEmployee {

public static void main(String[] args) {


// TODO Auto-generated method stub
String empName;
int empNo,empBasic;
Scanner input = new Scanner(System.in);
Scanner s = new Scanner(System.in);
System.out.println("Enter employee name=");
empName=input.nextLine();
System.out.println("Enter employee no=");
empNo=s.nextInt();
System.out.println("Enter employee salary=");
empBasic=s.nextInt();
input.close();
s.close();
File f=new File("src\\filehandling\\emp.txt");
try {
FileWriter fw = new FileWriter(f,true);
fw.write("employee name:"+empName+" ");
fw.write(" employee no:"+empNo+" ");
fw.write(" employee salary:"+empBasic+" ");
fw.close();
System.out.println("data inserted");
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Output:-
Unit -4

Experiment-1
Objective: JAVA Multi Threading programs
Scheduled Date Compiled Date Submission Date
05-June-2021 05-June-2021 05-June-2021

Program:- Create a class MyThread derived from Thread class and


override the run method.
Create a class ThreadDemo having main method. Create 2 objects of
MyThread class and observe the behavior of threads

package Threading;

public class FirstThread {

public static void main(String[] args) {


// TODO Auto-generated method stub
System.out.println("I am in main thread");
System.out.println("Thread
name="+Thread.currentThread().getName());
MyThread t1=new MyThread("Thread 1");
t1.start();
MyThread t2=new MyThread("Thread 2");
t2.start();

}
}
class MyThread extends Thread
{
MyThread(String name)
{
super(name);
}
public void run()
{
System.out.println("Thread
name="+Thread.currentThread().getName());
}
}

Output:-

Experiment-2
Objective: JAVA Multi Threading programs
Scheduled Date Compiled Date Submission Date
10-June-2021 12-June-2021 12-June-2021

Program:- Modify the above to create MyThread class by implementing


Runnable interface and observe the behavior of threads.

package Threading;

public class RunnableThread {

public static void main(String[] args) {


// TODO Auto-generated method stub
System.out.println("Thread
name="+Thread.currentThread().getName());
Thread t1=new Thread(new MyRThread());
t1.setName("Thread 1");
t1.start();
Thread t2=new Thread(new MyRThread());
t2.setName("Thread 2");
t2.start();

}
class MyRThread implements Runnable
{
public void run() {
System.out.println("Thread
name="+Thread.currentThread().getName());
}
}

Output:-
Experiment-3
Objective: JAVA Multi Threading programs
Scheduled Date Compiled Date Submission Date
13-June-2021 14-June-2021 14-June-2021

Program:- Assign different priorities to the 2 threads and observe the


behavior

package Threading;
class MyPriorityThread extends Thread
{
MyPriorityThread(String s)
{
super(s);
start();
}
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("Thread
Name:"+Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

public class PriorityExample {


public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Thread
Name:"+Thread.currentThread().getName());
MyPriorityThread m1=new MyPriorityThread ("My
Thread 1");
m1.setPriority(Thread.MAX_PRIORITY);
int p1=m1.getPriority();
System.out.println("Thread Priroty: "+p1);
MyPriorityThread m2=new MyPriorityThread("My Thread
2");
m2.setPriority(Thread.MIN_PRIORITY);
int p2=m2.getPriority();
System.out.println("Thread Priroty: "+p2);

Output:-
Experiment-4
Objective: JAVA Multi Threading programs
Scheduled Date Compiled Date Submission Date
15-June-2021 16-June-2021 16-June-2021

Program:- Implement three classes: Storage, Counter and Printer

The Storage class should store an integer.


The Counter class should create a thread and starts counting from 0 (0,1,2,
3 ...) and stores each value in the Storage class.
The Printer class should create a thread that keeps reading the value in the
Storage class and printing it.
Write a program that creates an instance of the Storage class and set up a
Counter and Printer object to operate on it.

package Threading;

class Counter implements Runnable{

Storage st;
public Counter(Storage store){
st = store;
}
@Override
public void run() {
synchronized(st) {
for(int i = 0 ; i < 10; i++){
while(!st.isPrinted()) {
//loop to take care of spontaneous wake-ups
try {
st.wait();
} catch(Exception e) { }
}
st.setValue(i);
st.setPrinted(false);
st.notify();
}
}
}

}
class Printer implements Runnable{
Storage st;
public Printer(Storage st){
this.st = st;
}
@Override
public void run() {
synchronized(st) {
for(int i = 0; i < 10; i++) {
while(st.isPrinted()) {
//loop to take care of spontaneous wake-ups
try {
st.wait();
} catch(Exception e) { }
}

System.out.println(Thread.currentThread().getName() + " " +


st.getValue());
st.setPrinted(true);
st.notify();
}
}
}

}
class Storage{
int i;
boolean printed = true;
public void setValue(int i){
this.i = i;
}
public int getValue(){
return this.i;
}
public boolean isPrinted() {
return printed;
}
public void setPrinted(boolean p) {
printed = p;
}
}
class MainClass {
public static void main(String[] args) {
Storage st = new Storage();
Counter c = new Counter(st);
Printer p = new Printer(st);
new Thread(c,"Counter").start(); //start the
counter
new Thread(p,"Printer").start(); //start the
printer
}
}

Output:-
Unit -5

Experiment-1
Objective: JAVA GUI Applications
Scheduled Date Compiled Date Submission Date
15-June-2021 16-June-2021 16-June-2021

Program:- Design and implement a GUI for the Temperature


class. One challenge of this design is to find a good way for the
user to indicate whether a Fahrenheit or Celsius value is being
input. This should also determine the order of the conversion: F to
C or C to F. [C/5 = (F -32)/9]

package SwingPrograms;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class temp extends JFrame {


private JLabel celsiusLabel;
private JLabel fahrenheitLabel;

private JTextField celsiusTF;


private JTextField fahrenheitTF;

private CelsHandler celsiusHandler;


private FahrHandler fahrenheitHandler;

private static final int WIDTH = 500;


private static final int HEIGHT = 75;
private static final double FTOC = 5.0 / 9.0;
private static final double CTOF = 9.0 / 5.0;
private static final int OFFSET = 32;

public temp() {
setTitle("Temperature Conversion");
Container c = getContentPane();
c.setLayout(new GridLayout(1, 4));

celsiusLabel = new JLabel("Temp in Celsius: ",


SwingConstants.RIGHT);
fahrenheitLabel = new JLabel("Temp in Fahrenheit: ",
SwingConstants.RIGHT);

celsiusTF = new JTextField(7);


fahrenheitTF = new JTextField(7);

c.add(celsiusLabel);
c.add(celsiusTF);
c.add(fahrenheitLabel);
c.add(fahrenheitTF);

celsiusHandler = new CelsHandler();


fahrenheitHandler = new FahrHandler();

celsiusTF.addActionListener(celsiusHandler);
fahrenheitTF.addActionListener(fahrenheitHandler);

setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

private class CelsHandler implements ActionListener {


public void actionPerformed(ActionEvent e) {
double celsius, fahrenheit;
celsius =
Double.parseDouble(celsiusTF.getText());
fahrenheit = celsius * CTOF + OFFSET;
fahrenheitTF.setText(String.format("%.2f",
fahrenheit));
}
}

private class FahrHandler implements ActionListener {


public void actionPerformed(ActionEvent e) {
double celsius, fahrenheit;
fahrenheit =
Double.parseDouble(fahrenheitTF.getText());
celsius = (fahrenheit - OFFSET) * FTOC;
celsiusTF.setText(String.format("%.2f",
celsius));
}
}
public static void main(String[] args) {
temp tempConv = new temp();
tempConv.setLocationRelativeTo(null);
}
}

Output:-
Experiment-2
Objective: JAVA GUI Applications
Scheduled Date Compiled Date Submission Date
20-June-2021 21-June-2021 21-June-2021

Program:- Design and implement a GUI application for Calculator


same as Windows OS calculator.

package SwingPrograms;

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
class Calculator extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;

// create a frame
static JFrame f;

// create a textfield
static JTextField l;

// store operator and operands


String s0, s1, s2;

// default constructor
Calculator()
{
s0 = s1 = s2 = "";
}

// main function
public static void main(String args[])
{
// create a frame
f = new JFrame("calculator");

try {
// set look and feel

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClass
Name());
}
catch (Exception e) {
System.err.println(e.getMessage());
}

// create a object of class


Calculator c = new Calculator();

// create a textfield
l = new JTextField(16);
// set the textfield to non editable
l.setEditable(false);

// create number buttons and some operators


JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba,
bs, bd, bm, be, beq, beq1;

// create number buttons


b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");

// equals button
beq1 = new JButton("=");

// create operator buttons


ba = new JButton("+");
bs = new JButton("-");
bd = new JButton("/");
bm = new JButton("*");
beq = new JButton("C");

// create . button
be = new JButton(".");

// create a panel
JPanel p = new JPanel();

// add action listeners


bm.addActionListener(c);
bd.addActionListener(c);
bs.addActionListener(c);
ba.addActionListener(c);
b9.addActionListener(c);
b8.addActionListener(c);
b7.addActionListener(c);
b6.addActionListener(c);
b5.addActionListener(c);
b4.addActionListener(c);
b3.addActionListener(c);
b2.addActionListener(c);
b1.addActionListener(c);
b0.addActionListener(c);
be.addActionListener(c);
beq.addActionListener(c);
beq1.addActionListener(c);

// add elements to panel


p.add(l);
p.add(ba);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bs);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(bm);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);

// set Background of panel


p.setBackground(Color.blue);

// add panel to frame


f.add(p);

f.setSize(200, 220);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();

// if the value is a number


if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') ||
s.charAt(0) == '.') {
// if operand is present then add to second no
if (!s1.equals(""))
s2 = s2 + s;
else
s0 = s0 + s;

// set the value of text


l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == 'C') {
// clear the one letter
s0 = s1 = s2 = "";

// set the value of text


l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == '=') {
double te;

// store the value in 1st


if (s1.equals("+"))
te = (Double.parseDouble(s0) +
Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) -
Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) /
Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) *
Double.parseDouble(s2));

// set the value of text


l.setText(s0 + s1 + s2 + "=" + te);

// convert it to string
s0 = Double.toString(te);

s1 = s2 = "";
}
else {
// if there was no operand
if (s1.equals("") || s2.equals(""))
s1 = s;
// else evaluate
else {
double te;

// store the value in 1st


if (s1.equals("+"))
te = (Double.parseDouble(s0) +
Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) -
Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) /
Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) *
Double.parseDouble(s2));

// convert it to string
s0 = Double.toString(te);

// place the operator


s1 = s;

// make the operand blank


s2 = "";
}

// set the value of text


l.setText(s0 + s1 + s2);
} }
}
Output:-
Experiment-3
Objective: JAVA GUI Applications
Scheduled Date Compiled Date Submission Date
25-June-2021 25-June-2021 25-June-2021

Program:- Design and create small notepad type application using


Swing/AWT.
package SwingPrograms;

import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.plaf.metal.*;
import javax.swing.text.*;
class editor extends JFrame implements ActionListener {
// Text component
JTextArea t;

// Frame
JFrame f;
// Constructor
editor()
{
// Create a frame
f = new JFrame("editor");

try {
// Set metal look and feel

UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAn
dFeel");

// Set theme to ocean


MetalLookAndFeel.setCurrentTheme(new
OceanTheme());
}
catch (Exception e) {
}

// Text component
t = new JTextArea();

// Create a menubar
JMenuBar mb = new JMenuBar();

// Create amenu for menu


JMenu m1 = new JMenu("File");

// Create menu items


JMenuItem mi1 = new JMenuItem("New");
JMenuItem mi2 = new JMenuItem("Open");
JMenuItem mi3 = new JMenuItem("Save");
JMenuItem mi9 = new JMenuItem("Print");

// Add action listener


mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
mi9.addActionListener(this);

m1.add(mi1);
m1.add(mi2);
m1.add(mi3);
m1.add(mi9);

// Create amenu for menu


JMenu m2 = new JMenu("Edit");

// Create menu items


JMenuItem mi4 = new JMenuItem("cut");
JMenuItem mi5 = new JMenuItem("copy");
JMenuItem mi6 = new JMenuItem("paste");

// Add action listener


mi4.addActionListener(this);
mi5.addActionListener(this);
mi6.addActionListener(this);

m2.add(mi4);
m2.add(mi5);
m2.add(mi6);

JMenuItem mc = new JMenuItem("close");

mc.addActionListener(this);

mb.add(m1);
mb.add(m2);
mb.add(mc);

f.setJMenuBar(mb);
f.add(t);
f.setSize(500, 500);
f.show();
}

// If a button is pressed
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();

if (s.equals("cut")) {
t.cut();
}
else if (s.equals("copy")) {
t.copy();
}
else if (s.equals("paste")) {
t.paste();
}
else if (s.equals("Save")) {
// Create an object of JFileChooser class
JFileChooser j = new JFileChooser("f:");

// Invoke the showsSaveDialog function to show


the save dialog
int r = j.showSaveDialog(null);

if (r == JFileChooser.APPROVE_OPTION) {

// Set the label to the path of the selected


directory
File fi = new
File(j.getSelectedFile().getAbsolutePath());

try {
// Create a file writer
FileWriter wr = new FileWriter(fi,
false);

// Create buffered writer to write


BufferedWriter w = new
BufferedWriter(wr);

// Write
w.write(t.getText());

w.flush();
w.close();
}
catch (Exception evt) {
JOptionPane.showMessageDialog(f,
evt.getMessage());
}
}
// If the user cancelled the operation
else
JOptionPane.showMessageDialog(f, "the user
cancelled the operation");
}
else if (s.equals("Print")) {
try {
// print the file
t.print();
}
catch (Exception evt) {
JOptionPane.showMessageDialog(f,
evt.getMessage());
}
}
else if (s.equals("Open")) {
// Create an object of JFileChooser class
JFileChooser j = new JFileChooser("f:");
// Invoke the showsOpenDialog function to show
the save dialog
int r = j.showOpenDialog(null);

// If the user selects a file


if (r == JFileChooser.APPROVE_OPTION) {
// Set the label to the path of the selected
directory
File fi = new
File(j.getSelectedFile().getAbsolutePath());

try {
// String
String s1 = "", sl = "";

// File reader
FileReader fr = new FileReader(fi);

// Buffered reader
BufferedReader br = new
BufferedReader(fr);

// Initialize sl
sl = br.readLine();

// Take the input from the file


while ((s1 = br.readLine()) != null) {
sl = sl + "\n" + s1;
}

// Set the text


t.setText(sl);
}
catch (Exception evt) {
JOptionPane.showMessageDialog(f,
evt.getMessage());
}
}
// If the user cancelled the operation
else
JOptionPane.showMessageDialog(f, "the user
cancelled the operation");
}
else if (s.equals("New")) {
t.setText("");
}
else if (s.equals("close")) {
f.setVisible(false);
}
}

// Main class
public static void main(String args[])
{
editor e = new editor();
}
}

Output:-

You might also like