You are on page 1of 64

Lab Assignment 1

1. Write a Java program to insert 3 numbers from keyboard and find out greater
number among 3 numbers.

Program:

public class Largest {

public static void main(String[] args) {

double n1 = -4.5, n2 = 3.9, n3 = 2.5;

if( n1 >= n2 && n1 >= n3)

System.out.println(n1 + " is the largest number.");

else if (n2 >= n1 && n2 >= n3)

System.out.println(n2 + " is the largest number.");

else

System.out.println(n3 + " is the largest number.");

OUTPUT: 3.9 is the largest number.


2. Write a Java program to find out the sum of command line arguments.

Program: class SumTest {

public static void main(String[] values) {

int sum = 0;

System.out.println("Calculates Sum for below Integers");

for(int i=0;i<values.length;i++){

System.out.println(values[i]);

sum = sum + Integer.parseInt(values[i]);

System.out.println("Sum :" + sum);

OUTPUT: D:\Java_Programs>javac SumTest.java

D:\Java_Programs>java SumTest 10 20 30 40 50

Calculates Sum for below Integers

10

20

30

40

50

Sum :150
Lab Assignment 2
Write the basic programing program with a switch case to find

1: Printing the table

2: Digit sum

3: Reverse a number

4: to Check the Armstrong number of three digit

PROGRAM: package pack1;

import java.util.scanner;

public class SwitchCase {

static void table(int n) {

System.out.println("table:");

for(int i=1;i<=10;i++) {

system.out.print(n*i+"\t");

void digitsum(int n) {

int sum=0;

for(;n!=0;n=n/10) {

sum=n%10;

}
void reverseNumber(int n){

int r,reverse=0;

for(;n!=0;n=n/10) {

r=n%10;

reverse=reverse*10+r;

public static void main(String[] args) {

System.out.Println("Menu\n1,table2,digit sum\n3,reverse number\n4,check armstong


number\n");

Scanner sc= new Scanner(System.in);

System.out.print("enter choice:");

int a=sc.nextInt();

System.out.print("Enter number:");

int n=sc.nextInt();

switch (a) {

case 1:table(n);

break;

case 2:digitSum(n);

break;

case 3:reverseNumber(n);

break;

default:System.out.println("wrong choice");
}

OUTPUT: Enter a number


5299
Sum of digits of a number is 25

Reversed Number: 4321


371 is an Armstrong number.
LabAssignment 3
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 setData and display that data using
displayData() method.

PROGRAM:

package firstprogram;

public class Roomone {

int roomNo;

String roomType;

float roomArea;

int acRoom;

void setData(int roomNo,String roomType,float roomArea,int acRoom){

this.roomNo=roomNo;

this.roomType=roomType;

this.roomArea=roomArea;

this.acRoom=acRoom;

void displayData() {

System.out.println("Roomno,"+this.roomNo+"roomType:"+this.roomType+"roomarea"+this.roomArea+
"AC/Non"+this.acRoom);

}
public static void main(String args[]){

Roomone R1=new Roomone();

R1.setData(42,"AC",340,1);

R1.displayData();

OUTPUT:
. LabAssignment4

Program to demonstrate static variables, methods, and blocks.

PROGRAM: package demo1;

public class Static {

public static int x;

int y=100;

//static block

static{

x=100;

System.out.println("Ststic value of x"+x);

//instance block

System.out.println("Instance block");

public static void show() {

System.out.println(x);

public static void main(String[] args) {

Static s1=new Static();


Static s2=new Static();

Static.show();

System.out.println(Static.x);

OUTPUT: Running static initialization block.

x = 10

y = 15

z=8
LabAssignment5
Program to Implement Inheritance.

class Animal {

// field and method of the parent class


String name;
public void eat() {
System.out.println("I can eat");
}
}

// inherit from Animal


class Dog extends Animal {

// new method in subclass


public void display() {
System.out.println("My name is " + name);
}
}

class Main {
public static void main(String[] args) {

// create an object of the subclass


Dog labrador = new Dog();

// access field of superclass


labrador.name = "Rohu";
labrador.display();

// call method of superclass


OUTPUT: My name is Rohu
I can eat
LabAssignment6
Programs to implement Abstraction.

// Abstraction in Java
abstract class ElectricityBill
{
//abstract method
abstract float computeBill();
}

class Commercial extends ElectricityBill


{
@Override
float computeBill() {
return 1.25*100;
}
}

class Domestic extends ElectricityBill


{
@Override
float computeBill() {
return 0.25*75;
}
}
OUTPUT:
Lab Assignment 7
A)implementation of object cloning

class Student18 implements Cloneable{

int rollno;

String name;

Student18(int rollno,String name){

this.rollno=rollno;

this.name=name;

public Object clone()throws CloneNotSupportedException{

return super.clone();

public static void main(String args[]){

try{

Student18 s1=new Student18(101,"amit");

Student18 s2=(Student18)s1.clone();
System.out.println(s1.rollno+" "+s1.name);

System.out.println(s2.rollno+" "+s2.name);

}catch(CloneNotSupportedException c){}

OUTPUT: 101 amit

101 amit

B)implementation inner classes:

1: Private inner class

class Outer_Demo {

int num;

// inner class

private class Inner_Demo {

public void print() {

System.out.println("This is an private inner class");

}
// Accessing he inner class from the method within

void display_Inner() {

Inner_Demo inner = new Inner_Demo();

inner.print();

public class My_class {

public static void main(String args[]) {

// Instantiating the outer class

Outer_Demo outer = new Outer_Demo();

// Accessing the display_Inner() method.

outer.display_Inner();

OUTPUT: This is an Private inner class.

2: Static Inner class

class Outer {
private static void outerMethod() {

System.out.println("inside outerMethod");

// A static inner class

static class Inner {

public static void main(String[] args) {

System.out.println("inside inner class Method");

outerMethod();

OUTPUT: inside inner class Method


inside outerMethod

3: Local Method Inner Class

class Outer {

void outerMethod() {

System.out.println("inside outerMethod");
// Inner class is local to outerMethod()

class Inner {

void innerMethod() {

System.out.println("inside innerMethod");

Inner y = new Inner();

y.innerMethod();

class MethodDemo {

public static void main(String[] args) {

Outer x = new Outer();

x.outerMethod();

OUTPUT: inside outerMethod

inside innerMethod

4: Annonymous Inner class

abstract class AnonymousInner {

public abstract void mymethod();

}
public class Outer_class {

public static void main(String args[]) {

AnonymousInner inner = new AnonymousInner() {

public void mymethod() {

System.out.println("This is an example of anonymous inner class");

};

inner.mymethod();

OUTPUT: This is an example of anonymous inner class


LabAssignment 8
Programs to implement Exception Handling.

1: Basic Example for ArithematicException.

package demo1;

public class ArithmeticExceptionExample{

public static void main(String[]args){

//TODO auto generated method stub

try{

int a=10,b=0;

System.out.println("Result:"+a/b);

}catch(ArithmeticException ae){

System.out.println("Arithmetic exception:cannot divide 0");

System.out.println("Continuing execution...");

OUTPUT:

2:Write a program in Java to initialize an array of 10 integers. Handle


ArrayIndexOutOfBoundsException, so that any such problem doesn't cause abnormal
termination of program.
class ExceptionDemo{

public static void main(String args[])

try{

int a[]=new int[10];

a[11]=9;

catch(ArrayIndexOutofBoundsException e){

System.out.println("ArrayIndexOutofBounds");

OUTPUT: ArrayIndexOutofBounds

3:Write a java program with a method that throws an exception but not handled inside.
Call the method from main. Let the main method handle the exception appropriately.

package ExceptionHandling;

public class ExceptionThrowDemo{

static void display(String a)throws NullPointerException{

if(a!=null){

System.out.println("String not null");

else{
throw new NullPointerException();

public static void main(string args[]){

string a=null;

try{

display(a);

System.out.println("No Exception found!");

catch(NullPointerException np){

System.out.println("Null value is found for string");

System.out.println("error!"+np.getmessage());

OUTPUT:Null value is found for string

error!null

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

class InvalidInputException extends Exception{


public String toString() {
return "Invalid Input";
}
}
class Customer{
private String custNo;
private String custName;
private String category;
public Customer(String custNo, String custName, String category) throws InvalidInputException {
if(custNo.charAt(0)=='c'||custNo.charAt(0)=='C') {
this.custNo = custNo;
}
else {
throw new InvalidInputException();
}

this.custName = custName;
this.category = category;
}
public String getCustNo() {
return custNo;
}
public String getCustName() {
return custName;
}
public String getCategory() {
return category;
}
}
public class TestCustomer {
public static void main(String[] args) {
try {
Customer c = new Customer("c123", "Rohit", "gold");
System.out.println(c.getCustNo());
}
catch(InvalidInputException ip) {
System.out.println(ip);
}
}
}

OUTPUT:
LabAssignment 9
Implementation of IO Streams:

Write a java program for read/ write operations into files using byte stream
classes.

import java.io.*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

OUTPUT:

Write a java program for read/ write operations into files using character stream
classes.

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();
}
}
}
}

OUTPUT:

Write a java program for copying data from one file into another file

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyExample


{
public static void main(String[] args)
{
FileInputStream instream = null;
FileOutputStream outstream = null;

try{
File infile =new File("C:\\MyInputFile.txt");
File outfile =new File("C:\\MyOutputFile.txt");

instream = new FileInputStream(infile);


outstream = new FileOutputStream(outfile);

byte[] buffer = new byte[1024];

int length;
/*copying the contents from input stream to
* output stream using read and write methods
*/
while ((length = instream.read(buffer)) > 0){
outstream.write(buffer, 0, length);
}

//Closing the input/output file streams


instream.close();
outstream.close();

System.out.println("File copied successfully!!");

}catch(IOException ioe){
ioe.printStackTrace();
}
}
}

OUTPUT: File copied successfully!!


LabAssignment 10
1: 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.

2: Demonstrate the use of transient keyword in serialization.

Program: import java.io.FileOutputStream;

import java .io.IoException;

import java.io.ObjectOutputStream;

import java.io.Serializable;

import java.util.Scanner;

class Employee implements Serializable{

private int empNo;

private String empName;

private int empBasic;


Employee(int empNo,String empName,int empBasic){

this.empNo = empNo;

this.empName = empName;

this.empBasic = empBasic;

public int getEmpNo(){

return empNo;

public String getEmpName(){

return empName;

public int getEmpBasic(){

return empBasic;

public class WriteEmployee{

public static void main (Sting[]args)throws IoException{

FileOutputStream fout = new FileOutputStream("employee.txt");

Employee e = new Employee(34, "Shreya",50000);

ObjectOutputStream obj= new ObjectOutputStream(fout);

obj.writeObject(e);

obj.close();
fout.close();

System.out.println("Object Serialized”);

OUTPUT: Object Serialized

DESERIALIZATION

Program : import java.io.FileInputStream;

import java.io.ObjectInputStream;

public class DeserializationDemo{

public static void main (String[]args)throws Exception{

FileInputStream fin = new FileInputStream("employee.txt");

ObjectInputStream obj= new ObjectInputStream(fin);

Employee.e1 =(Employee)obj.readObject();

System.out.println(e1.getEmpNo());

System.out.println(e1.getEmpName());

System.out.println(e1.getEmpBasic());

obj.close();

fin.close();

//TODO Auto-generated method stub

}
}
Lab Assignment 11
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 behaviour of threads.

Modify the above to create MyThread class by implementing Runnable


interface and observe the behaviour of threads.

Program: class MyThread extends Thread

public void run () {

for (int i=0; i<3; i++)

System.out.println(i);

public class ThreadDemo {

public static void main(String[] args) {

MyThread th1 =new MyThread();

th1.start();

MyThread th2=new MyThread();


th2.start();

}
LabAssignment 12
Implementation of Synchronization

Program:
//example of java synchronized method
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}

}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}

}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

public class TestSynchronization2{


public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
LabAssignment 13
1: Write a program for the URL parsing.

Program:
package MyPackage
import java.net.*;

public class URLParser {


public static void main(String[] args) throws Exception {
URL aURL = new URL(" https://www.kiet.edu/home/department_wise_detail/OQ==/about ");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());

}
}

2: Write a program for the URL reader.

Program: import java.io.BufferedReader;


import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class URLReader {

public static void main(String[] args) throws IOException {


// TODO Auto-generated method stub
URL aajtak = new URL("https://www.aajtak.in");
InputStreamReader is = new InputStreamReader(aajtak.openStream());
BufferedReader br = new BufferedReader(is);
String str;
while((str=br.readLine())!=null) {
System.out.println(str);
}

}
3: Program for Client server communication using socket.

Program:

import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAddressDemo{

public static void main(String[] args) throws UnknownHostException{

InetAddress add=InetAddress.getLocalHost();

System.out.println(add);

add=InetAddress.getByName("google.com");

System.out.println(add);

InetAddress id[]=InetAddress.getAllByName("www.yahoo.com");

for(int i=0;i<id.length;i++){

System.out.println(id[i]);
}
}
}

• import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class MyClient {

public static void main(String[] args) throws UnknownHostException, IOException {


// TODO Auto-generated method stub
Socket s = new Socket("localhost",9999);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello from Client side");
dout.flush();
dout.close();
s.close();

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {

public static void main(String[] args) throws IOException {


// TODO Auto-generated method stub
ServerSocket ss = new ServerSocket(9999);
Socket s = ss.accept();
DataInputStream din = new DataInputStream(s.getInputStream());
String msg =din.readUTF();
System.out.println(msg);
din.close();
s.close();
ss.close();
}

}
Assignment No 14
Create a Generic class and instantiate it with different types of instance variables.

package checkingJava;

public class SampleGenricClass<T> {


T x;
public SampleGenricClass(T x)
{
this.x=x;
}
void show()
{
System.out.println(this.x);
}
public static void main(String ars[])
{
SampleGenricClass<Integer> obj1=new SampleGenricClass(123);
obj1.show();
SampleGenricClass<String> obj2=new SampleGenricClass("SHUBHAM");
obj2.show();
SampleGenricClass<Double> obj3=new SampleGenricClass(87.987);
obj3.show();
}

Create a class with the generic method and invoke the method with different types of
arguments.

package checkingJava;
class GenericMthod2 {
<T> void showData(T x)
{
System.out.println(x);
}
public static void main(String[] args) {
GenericMthod2 obj=new GenericMthod2(); // TODO Auto-generated method stub
obj.showData(123);
obj.showData("shreya");
obj.showData("67.8889");
}
}
AssignmentNo 15
Write a java program for the generic class and that class must be restricted to only
numbers.

public class RestrictionNumber <T extends String>{

T data;

public RestrictionNumber(T data) {

this.data = data;

void displayData() {

System.out.println(this.data);

System.out.println(data.getClass().getName());

public static void main(String[] args) {

// TODO Auto-generated method stub

RestrictionNumber<String> ob3 = new RestrictionNumber<String>("First


name:="+Shreya\n");

ob3.displayData();

RestrictionNumber<String> ob5 = new RestrictionNumber<String>("Last


name:="+"Gaur");

ob5.displayData();

RestrictionNumber<String> ob6 = new RestrictionNumber<String>("Father


name:="+"Mr Sri Nath Sharma");
ob6.displayData();

/*RestrictionNumber ob1 = new RestrictionNumber(123);

ob1.displayData();

RestrictionNumber<Integer> ob2 = new RestrictionNumber<Integer>(0001);

ob2.displayData();

RestrictionNumber<Double> ob4 = new RestrictionNumber<Double>(10.1111);

ob4.displayData();*/

// numeric value show error

}
Write a java program for the generic class and that class must be restricted to
specific subtypes using bounds.

class Bound<T extends Ani>

private T objRef;

public Bound(T obj){

this.objRef = obj;

public void doRunTest(){

this.objRef.displayData();

class Ani

public void displayData()

System.out.println("Animal eat");

System.out.println("Veg and non veg both");

class Elephant extends Ani


{

public void displayData()

System.out.println("Elephant eat");

System.out.println("Veg");

class Fox extends Ani

public void displayData()

System.out.println("Fox eat");

System.out.println("nonveg");

public class GenClassRestriction {

public static void main(String a[])

// Creating object of sub class Fox and

// passing it to Bound as a type parameter.


Bound<Fox> obj = new Bound<Fox>(new Fox());

obj.doRunTest();

// Creating object of sub class Elephant and

// passing it to Bound as a type parameter.

Bound<Elephant> obj1 = new Bound<Elephant>(new Elephant());

obj1.doRunTest();

// similarly passing super class Ani

Bound<Ani> obj2 = new Bound<Ani>(new Ani());

obj2.doRunTest();

}
LAB ASSIGNMENT 16

PROGRAM 1: Deisgn an awt application for the implementaion of FlowLayout, BorderLayout,


GridLayout.

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

public class Border {


JFrame f;
Border(){
f=new JFrame();

JButton b1=new JButton("NORTH");;


JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;

f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Grid layout: import java.awt.*;
import javax.swing.*;

public class MyGridLayout{


JFrame f;
MyGridLayout(){
f=new JFrame();

JButton b1=new JButton("1");


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

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);

f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Flow Layout: import java.awt.*;
import javax.swing.*;

public class MyFlowLayout{


JFrame f;
MyFlowLayout(){
f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);

f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}

PROGRAM 2:
Deisgn a small calculator with basic operations like plus,minus,division,multiplication.

import java.util.Scanner;
class Main {

public static void main(String[] args) {

char operator;

Double number1, number2, result;

// create an object of Scanner class

Scanner input = new Scanner(System.in);

// ask users to enter operator

System.out.println("Choose an operator: +, -, *, or /");

operator = input.next().charAt(0);

// ask users to enter numbers

System.out.println("Enter first number");

number1 = input.nextDouble();

System.out.println("Enter second number");

number2 = input.nextDouble();

switch (operator) {

// performs addition between numbers

case '+':

result = number1 + number2;

System.out.println(number1 + " + " + number2 + " = " + result);

break;
// performs subtraction between numbers

case '-':

result = number1 - number2;

System.out.println(number1 + " - " + number2 + " = " + result);

break;

// performs multiplication between numbers

case '*':

result = number1 * number2;

System.out.println(number1 + " * " + number2 + " = " + result);

break;

// performs division between numbers

case '/':

result = number1 / number2;

System.out.println(number1 + " / " + number2 + " = " + result);

break;

default:

System.out.println("Invalid operator!");

break;

input.close();

OUTPUT1: Output 1
Choose an operator: +, -, *, or /
*
Enter first number
3
Enter second number
9
3.0 * 9.0 = 27

Output 2

Choose an operator: +, -, *, or /
+
Enter first number
21
Enter second number
8
21.0 + 8.0 = 29.

Output 3

Choose an operator: +, -, *, or /
-
Enter first number
9
Enter second number
3
9.0 - 3.0 = 6.0

Output 4

Choose an operator: +, -, *, or /
/
Enter first number
24
Enter second number
8
24.0 / 8.0 = 3.0
AssignmentNo 17
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
inputted. This should also determine the order of the conversion: F to C or C to F. [C/5 =
(F -32)/9]

package convertFtoC;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class ConvertCelsiusToFahrenheit implements ActionListener {


JTextField tf;
JLabel l2;
public ConvertCelsiusToFahrenheit()
{
JFrame jf=new JFrame();
jf.setSize(700,800);
JLabel l=new JLabel("enter value");
l.setBounds( 50,50,180,180);
tf=new JTextField();
tf.setBounds( 150,100,50,50);
JButton bt1=new JButton("Convert C to F");
bt1.addActionListener(this);
bt1.setBounds(50,300,100,60);
JButton bt2=new JButton("Convert F to C");
bt2.addActionListener(this);
bt2.setBounds(160,300,100,60);
l2=new JLabel();
l2.setBounds(350,400,100,60);
jf.add( l);
jf.add( tf);
jf.add( bt1);
jf.add(bt2);
jf.add( l2);
jf.setLayout(null);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new ConvertCelsiusToFahrenheit();
}
public void actionPerformed(ActionEvent e)
{
JButton obj=(JButton)e.getSource();
if(obj.getText().equals("Convert C to F"))
{
String s=tf.getText();
int c=Integer.parseInt(s);
float F;
F=(c*9/5)+32;
l2.setText(""+F);
}
if(obj.getText().equals("Convert F to C"))
{
String s=tf.getText();
int F=Integer.parseInt(s);
float C;
C=(F-32)*5/9;
l2.setText(""+C);
}
}
}
Design and implement a GUI application for Calculator same as Windows OS calculator

// Java program to create a simple calculator

// with basic +, -, /, * using java swing elements


import java.awt.event.*;

import javax.swing.*;

import java.awt.*;

class calculator extends JFrame implements ActionListener {

// 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.getSystemLookAndFeelClassNa
me());

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:

You might also like