Java Lab
Java Lab
…………………………………………………
LABORATORY RECORD
NAME OF THE LABORATORY……………………………………………………………..
BRANCH………………………………SEMESTER…………………........................................
ROLL.NO………………………………...YEAR…………………………………….................
CERTIFICATE
Staff-in-Charge
Date…………
Place……….. Internal Examiner External Examiner
Experiment No:- 1
PRIME OR NOT
Aim :- To write a program to find whether the given number is a prime or not.
Algorithm
Step 1: start
Step 2: Read a number,n
Step 3: Initialize c=0
Step 4: if(n===1 or n==0), then print “ Not a prime number”
else if (n<0), then print “ Enter +ve number only!”
else,
for i=2 to n/2
if (n%i==0), then set c=1 and break the loop
Step 5: if(c==0),then print “ It’s prime ”
else, print “ It’s not a prime ”
Step 6: Stop
Result
Thus the program to check whether the given number is prime or not is executed successfully.
Program
import java.util.Scanner;
class prime{
public static void main(String ar[])
{
Scanner s=new Scanner(System.in);
int c=0;
System.out.print("Enter a +ve number : ");
int n=s.nextInt();
if ((n==0) ||( n==1))
System.out.println(n+" is not a prime ");
else if(n<0)
System.out.println(“Enter +ve numbers only !”);
else{
for(int i=2;i<=n/2;i++)
{
if(n%i==0)
{c=1;break;}
}
if (c==0)
System.out.println(n+" is prime");
else
System.out.println(n+" is not a prime");
}
}
}
Output
Enter a +ve number : 5
5 is prime
Reverse of a string
Algorithm
Step 1: Start
Step 2: Read a string, str
Step 3: Initialize rev=“”
Step 4: Initialize l = length of str,with using str.length() function.
Step 5: for i=l-1 to 0,do
rev=rev+str.charAt(i)
Step 6: Print rev
Step 7: Stop
Result
Thus the program to display the reverse of a string is executed successfully.
Program
import java.util.Scanner;
class rev{
public static void main (String ar[]){
Scanner s=new Scanner(System.in);
System.out.print("Enter string : ");
String str;
str=s.nextLine();
String dstr=str,rev="";
int l=str.length();
for(int i=l-1;i>=0;i--)
rev=rev+str.charAt(i);
System.out.println("reverse : "+rev);
}
}
Output
Enter string : godson
reverse : nosdog
Experiment No:- 4
Aim:- Write a Java Program to find the frequency of a given character in a string.
Algorithm
Step 1: Start
Step 2: Input the string from the user and store in variable str.
Step 3: Input the character whose frequency needs to be computed. Store it in variable c
Step 4: Find the length of the string str and store in variable n.
Step 5: Initialize start index ‘s’ to 0. Initialize the count variable to 0
Step 6: Repeat the steps 6 to 8 until the start index ‘s’ is equal to or greater than n.
Step 7: If str[s] is the same as character in c, then count=count+1
Step 8: Increment s by 1
Step 9: Print Frequency of the character in string is value in count.
Step 10: Stop
Result
Thus the program to find a letter’s frequency in a sting is executed successfully.
Program
import java.util.Scanner;
class freq{
public static void main (String ar[]){
Scanner s=new Scanner(System.in);
System.out.print("Enter string : ");
String str;
str=s.nextLine();
System.out.print("enter a letter: ");
char c=s.next().charAt(0);
int f=0;
for(int i=0;i<str.length();i++)
{
if(c==str.charAt(i))
f++;
}
System.out.println("frequency : "+f);
}
}
Output
Palindrome Check
Aim:- Write a Java program that checks whether a given string is a palindrome or not.
Algorithm
Step 1: Start
Step 2: Enter a string str
Step 3: Find length of str and store in variable n.
Step 4: Initialize start ‘s’ and end indexes ‘e’ as 0 and n-1 respectively.
Step 5: Repeat the steps 6 and 7 until the start index ‘s’ is greater than the end index ‘e’.
Step 6: If str[s] is not same as str[e], then go to step 9.
Step 7: Increment s and decrement e by 1
Step 8: Print- The string is palindrome. Go to step 10
Step 9: Print- The string is not palindrome.
Step10:Stop.
Result
Thus the program to check a string is palindrome or not is executed successfully.
Program
import java.util.Scanner;
class Sp
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a String: ");
String str=s.nextLine();
String org_str=str;
String rev="";
int len=str.length();
for(int i=len-1;i>=0;i--)
{
rev=rev+str.charAt(i);}
if(org_str.equals(rev))
System.out.print("The string is palindrome");
else
{
System.out.println("The string is not palindrome");
}
}
}
Output
Sample Input and Output 1
Aim:- To write a program to find the second smallest element in a given array.
Algorithm
Step 1: Start
Step 2: Read the number of elements in array,n
Step 3: Read the elements of array,a[]
Step 4: for i=0 to n-1
for j=i+1 to n-1
if(a[i]>a[j]),then do
t=a[i]
a[i]=a[j]
a[j]=t
Step 5: print “The second smallest element is”a[1]
Step 6: Stop
Result
Thus the program to find the second smallest element in a given array is executed successfully.
Program
import java.util.Scanner;
class Array
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int n,t,i,j;
System.out.print("Enter the limit: ");
n=s.nextInt();
int a[]=new int[n];
System.out.println("Enter the elements:");
for(i=0;i<n;i++)
{
a[i]=s.nextInt();
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
System.out.println("Second smallest element is: "+a[1]);
}
}
Output
Enter the limit: 5
Enter the elements: 4 8 1 3 9
Second smallest element is: 3
Experiment No:- 6
Transpose of a matrix
Algorithm
Step 1: Start
Step 2: Read the number of rows ‘r’ & coloumn ‘c’ of the matrix.
Step 3: Read the matrix element in array ‘a[][]’.
Step 4: for i=0 to r-1,do
for j=0 to c-1,do
t[j][i]=a[i][j]
Step 5: Print the array ‘t[][]’,using for loop.
Step 6: Stop
Result
Thus the program to print the transpose of a matrix is executed successfully.
Program
import java.util.Scanner;
class trans{
public static void main (String ar[]){
Scanner s=new Scanner(System.in);
int r,i,j,c;
System.out.print("Enter the row & coloumn size : ");
r=s.nextInt();
c=s.nextInt();
}
}
Output
Enter the row & coloumn size : 3 2
Enter the elements of matrix
23
34
11
Transpose Matrix
231
341
Experiment No:- 7
Matrix multiplication
Algorithm
Step 1: Start
Step 2: Read the number of rows r1 and column c1 in first matrix
Step 3: Read the number of rows r2 and column c2 in second matrix
Step 4: Repeat step 2&3,while c1 not equal to r2, and then goto step 6.
Step 5: Read elements of matrices A and B.
Step 6: for i=0 to r1-1,do
for j=0 to c2-1,do
mult[i][j]=0
for k=0 to c2-1,do
mult[i][j]+= a[i][k]*b[k][j]
Step 7: Print matrix mult[][]
Step 8: Stop.
Result
Thus the program to find the product of two matrices is executed successfully.
Program
import java.util.Scanner;
class mmultiple{
public static void main (String ar[]){
Scanner s=new Scanner(System.in);
System.out.print("Enter row & coloum size of 1st matrix : ");
int r1=s.nextInt();
int c1=s.nextInt();
System.out.print("Enter row & coloum size of 2nd matrix : ");
int r2=s.nextInt();
int c2=s.nextInt();
if (c1==r2)
{
System.out.println("Enter the elements of 1st matrix: ");
int a[][]=new int[r1][c1];
for(int i=0;i<r1;i++)
{
for(int j=0;j<c1;j++)
a[i][j]=s.nextInt();
}
System.out.println("Enter the elements of 2nd matrix: ");
int b[][]=new int[r2][c2];
for(int i=0;i<r2;i++)
{
for(int j=0;j<c2;j++)
b[i][j]=s.nextInt();
}
int m[][]=new int[r1][c2];
System.out.println("product of these matrixes: ");
for(int i=0;i<r1;i++)
{
for(int j=0;j<c2;j++)
m[i][j]=0;
}
int i,j,k;
for (i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
for(k=0;k<c1;k++)
m[i][j]+= a[i][k]*b[k][j];
}
}
for (i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
System.out.print(m[i][j]+" ");
System.out.println();
}
}
else
System.out.println("not possible");
}
}
Output
Enter row & coloum size of 1st matrix : 3 2
Enter row & coloum size of 2nd matrix : 2 3
Enter the elements of 1st matrix:
12
23
12
Enter the elements of 2nd matrix:
121
333
product of these matrixes:
787
11 13 11
787
Experiment No:-8
Inheritance 1
Aim:-Write a java program which creates a class named ‘Employee’ having the following
members name, age, phone number, address, salary. It also has a method named printSalary()
which prints the salary of the employee. Two classes ‘Officer’ and ‘Manager’ inherit the class
‘Employee’. The ‘Officer’ and ‘Manager’ classes have data members ‘specialization’ and
‘department’ respectively. Now assign name, age, phone number, address, salary to an ‘Officer’
and ‘Manager’ by making an object of both of these classes and print the same.
Algorithm
Step 1:Create a class ‘Employee’ with given variables and method printSalary() to print the salary.
Step 2:Create two subclasses of class ‘Employee’ named ‘Officer’ and ‘Manager’. Include the
variable ‘Specialization’ in ‘Officer’ class and ‘department’ in ‘Manager’ class.
Step 3:Create a class with the main function. Inside the main function do the following steps.
Step 4:Create an object to ‘Officer’ class and assign appropriate value to the variables.
Step 5:Create an object of ‘Manager’ class and assign appropriate values to the variables.
Step 6:Print the values of the variables using objects.
Step 7:Involves the function ‘printSalary()’ using object to print salary.
Step 8:Stop
Result
The program was executed successfully and the output was verified.
Program
class Employee{
String name,address;
int age,no;
float salary;
Employee(String name,int age,int no,String address,float salary){
this.name=name;
this.age=age;
this.no=no;
this.address=address;
this.salary=salary;
}
void printSalary(){
System.out.println("The salary is "+salary+"\n");
}
}
class Officer extends Employee{
String spec;
Officer(String name,int age,int no,String address,float salary,String spec){
super(name,age,no,address,salary);
this.spec=spec;
}
void printInfo(){
System.out.println("Name: "+name+"\n"+"Age: "+age+"\n"+"Address: "+address+"\
n"+"Number: "+no+"\n"+"Salary: "+salary+"\n"+"Specialization: "+spec+"\n");
}
}
class Manager extends Employee{
String dept;
Manager(String name,int age,int no,String address,float salary,String dept){
super(name,age,no,address,salary);
this.dept=dept;
}
void printInfo(){
System.out.println("Name: "+name+"\n"+"Age: "+age+"\n"+"Address: "+address+"\
n"+"Number: "+no+"\n"+"Salary: "+salary+"\n"+"Department: "+dept+"\n");
}
}
class Test{
public static void main(String[]args){
Officer o=new Officer("Robert",21,54321,"ABC House",60000.0f,"Design");
Manager m=new Manager("Smith",23,45678,"XYZ House",15000f,"HR");
System.out.println("Officer Details");
System.out.println("_______________");
o.printInfo();
o.printSalary();
System.out.println("Manager Details");
System.out.println("_______________");
m.printInfo();
m.printSalary();
}
}
Output
Officer Details
_______________
Name: Robert
Age: 21
Address: ABC House
Number: 54321
Salary: 60000.0
Specialization: Design
Manager Details
_______________
Name: Smith
Age: 23
Address: XYZ House
Number: 45678
Salary: 15000.0
Department: HR
Aim:-
Where two java classes employee and engineer,engineer should inherit from employee
class. Employee class to have two methods display() and calculate salary.Write a program to
display the engineer salary and to display from employee class using a single object instantation
[i.e. only one object creation is allowed ]. display() only prints the name of the class and doesn’t
return any values. Eg- “name of class is employee”.
calc_salary() in employee display “salary of employee is 10000” and calc_salary() in engineer
display “salary of employee is 20000”
Algorithm
Step 1: Start
Step 2: Create a class employee with given variables and method print salary() to print the salary.
Step 3: Create a subclass of employee named engineer include the variable calcsalary.
Step 4: Create a class with the main function inside the main function, do the following steps
Step 5: Create an object to engineer class and assign appropriate value to the variable
Step 6: Print the values of variables using objects
Step 7: Invoke the function print calc_salary() using object to print the salary
Step 8: Stop.
Result
Output
Name of class is Engineer
the salary of Engineer is 50000
the salary of Employee is 25000
Experiment No:-10
Polymorphism
Aim:-Write a java program to create an abstract class named ‘Shape’ that contains an empty
method ‘named_no_sides()’.Provide the classes named Rectangle, Triangle and Hexagon such that
each one of these classes extends the class ‘Shape’.Each one of the classes contain only the
method ‘number_of_sides()’ that shows the number of sides in the given geometrical structure.
Algorithm
Step 1:Start
Step 2:Create class Shape with method ‘no_of_sides()’ without definition.
Step 3:Create three subclass of ‘Shape’ namely Rectangle, Triangle and Hexagon.
Step 4:Define the ‘no_of_sides()’in all these subclass Rectangle, Triangle and Hexagon that
display the sides 4,5,6 respectively.
Step 5:Invoke ‘no_of_sides()’ by creating reference variable of class ‘Shape’ which refers to each
of these subclass.
Step 6:Stop
Result
The program was executed successfully and the output was verified.
Program
abstract class Shape{
abstract void no_of_sides();
}
class Rectangle extends Shape{
void no_of_sides(){
System.out.println("No of sides=4");
}
}
class Triangle extends Shape{
void no_of_sides(){
System.out.println("No of sides=3");
}
}
class Hexagon extends Shape{
void no_of_sides(){
System.out.println("No of sides=6");
}
}
class Test{
public static void main(String args[]){
Shape r=new Rectangle();
Shape t=new Triangle();
Shape h=new Hexagon();
r.no_of_sides();
t.no_of_sides();
h.no_of_sides();
}
}
Output
No of sides=4
No of sides=3
No of sides=6
Experiment No:-11
Method Overloading
Aim:-Write a java program to calculate the area of triangle, rectangle, square and circle using
method overloading.
Algorithm
Step 1:Start
Step 2:Declare the different classes for rectangle, triangle, square, circle.
Step 3:Declare two methods of the same name but with different number of arguments or with
different data types.
Step 4:Call these methods using objects.
Step 5:Call the corresponding method as per the number of arguments or their data types.
Step 6:Display the results.
Step 6:Stop
Result
The program was executed successfully and the output was verified.
Program
class Overload{
void area(int x){
int y=x*x;
System.out.println("The area of the square is :"+y);
}
void area(int x,int y){
System.out.println("The area of the rectangle is :"+(x*y));
}
void area(double x){
double z=3.14*x*x;
System.out.println("The area of the circle is :"+z);
}
void area(float x,float y){
System.out.println("The area of the triangle is :"+(0.5*x*y));
}
}
class Demo{
public static void main(String args[]){
Overload o=new Overload();
o.area(5);
o.area(5,6);
o.area(4.0);
o.area(5,5);
}
}
Output
The area of the square is: 25
The area of the rectangle is: 30
The area of the circle is: 50.24
The area of the rectangle is: 25
Experiment No:-12
Garbage Collection
Output
Method 1:
Obj created!
Obj destroyed!
Method 2:
Obj created!
Obj created!
Obj destroyed!
Method 3:
Obj created!
Obj destroyed!
Experiment No:-13
File Handling I
Aim:-Write a java program that read form a file and write to another file handling and all related
exception.
Algorithm
Step 1:Start.
Step 2:Import to java to classes.
Step 3:Throws at exception.
Step 4:Initialize FileInputStream object fin on “Input file”.
Step 5:Initialize FileOutputStream object fout on “Output file”.
Step 6:Try
Step 7:While((i=fin.read())!=-1)
fout.write(i)
Step 8:End while
Step 9:Catch
Step 10:Print IOException
Step 11:End Try
Step 12:Stop.
Result
The program was executed successfully and the output was verified.
Program
import java.io.*;
class FileH{
public static void main(String[]args)throws IOException{
try{
FileInputStream fin=new FileInputStream("a.txt");
FileOutputStream fout=new FileOutputStream("a.txt");
int i=0;
while((i=fin.read())!=-1){
fout.write(i);
}
}
catch(IOException e){
}
}
}
Output
File 1: a.txt
hello
File 2: b.txt
hello
Experiment No:-14
File Handling II
Output
File 1: a.txt
hello
world
File 2: b.txt
hello
world
Experiment No:-15
String Tokenizer
Aim:-Write a java program that read a line of integers and display each integers and sum of all
integers.
Algorithm
Step 1:Start.
Step 2:Import all classes at package java.util.
Step 3:Create object of stringTokenizer class using constructor with determiner arrangement or
space for separating tokens.
Step 4:Enter numbers separated by space.
Step 5:Using appropriate method to separate token.
Step 6:Display the token and sum of all integers.
Step 7:Stop.
Result
The program was executed successfully and the output was verified.
Program
import java.util.*;
class stringTokenizer{
public static void main(String[]args){
int sum=0;
Scanner sc=new Scanner(System.in);
System.out.println("enter the integer");
String s=sc.nextLine();
StringTokenizer st=new StringTokenizer(s," ");
while(st.hasMoreTokens()){
String temp=st.nextToken();
int n=Integer.parseInt(temp);
System.out.println(n);
sum=sum+n;
}
System.out.println("Sum of integer is "+sum);
}
}
Output
enter the integer
18 14 2 69 420
18
14
2
69
420
Sum of integer is 523
Experiment No:-16
Exception Handling
Aim:-Write a java program that show usage of try, catch and finally.
Algorithm
Step 1:Start.
Step 2:Class Demo define main method.
Step 3:Read a and b.
Step 4:Perform arithmetic operation a/b in try catch block.
Step 5:Print result if Exception occurs catch it and print message.
Step 6:Execute finally block print message.
Step 7:Stop.
Result
The program was executed successfully and the output was verified.
Program
import java.util.*;
class Demo{
public static void main(String args[]){
try{
Scanner s=new Scanner(System.in);
System.out.println("Enter two Numbers: ");
int a= s.nextInt();
int b= s.nextInt();
int c=a/b;
System.out.println(c);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
finally{
System.out.println("Execution is done");
}
}
}
Output
Enter two Numbers:
87
1
Execution is done
Multi Threading I
Aim:-Write a java program to print odd and even using two threads in 1 to 100.
Algorithm
Step 1:Start.
Step 2:Extend the Thread class to Odd and Even classes.
Step 3:In Odd class, in run() method i=0 to 100,if (i%2==1),print i.
Step 4:In Even class, in run() method i=0 to 100, if(i%2==0),print i.
Step 5:In main class Demo create two objects Odd and Even classes ‘o’ and ‘e’ respectively.
Step 6:Execute o.start(); e.start();
Step 7:Stop.
Result
The program was executed successfully and the output was verified.
Program
class odd extends Thread{
public void run(){
for(int i=0;i<100;i++){
if(i%2==1)
System.out.println("odd:"+i);
}
}
}
class even extends Thread{
public void run(){
for(int i=0;i<100;i++){
if(i%2==0)
System.out.println("even:"+i);
}
}
}
class demo{
public static void main(String[]args){
odd o=new odd();
o.start();
even e=new even();
e.start();
}
}
Output
odd:1
even:0
odd:3
even:2
odd:5
odd:7
odd:9
odd:11
even:4
even:6
even:8
odd:13
odd:15
odd:17
even:10
even:12…………..
Experiment No:-18
Multi Threading II
Aim:-Write a java program that implements a multi-threaded program which uses 3 thread,1st
thread generates a random integer in every one sec. If the value is even the second thread computes
the square of the number and prints if the value of odd. The third thread will print the value of
cube of the number.
Algorithm
Step 1:Start.
Step 2:Initialize a random number.
Step 3:Create a ‘NumberThread’ thread, the run() method in it generate random number.
Step 4:For each random integer create a ‘Square’ and a ‘Cube’ thread.
Step 5:In the run() method in the ‘Square’ thread calculate square of the given integer and print it.
Step 6:In the run() method in the ‘Cube’ thread calculate cube of the given integer and print it.
Step 7:In the run() method of the ‘NumberThread’ , pause execution for one sec before generating
next integer.
Step 8:Execute the ‘NumberThread’.
Step 9:Stop.
Result
The program was executed successfully and the output was verified.
Program
import java.util.Random;
class NumberThread extends Thread {
public void run() {
Random random = new Random();
for (int i = 0; i < 10; i++) {
int rInt = random.nextInt(100);
System.out.println("Random Integer generated : " + rInt);
if((rInt%2) == 0) {
Square s = new Square(rInt);
s.start();
}
else {
Cube c = new Cube(rInt);
c.start();
}
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
class Square extends Thread {
int no;
Square(int randomNumbern) {
no = randomNumbern;
}
public void run() {
System.out.println("Square of " + no + " = " + (no * no));
}
}
class Cube extends Thread {
int no;
Cube(int randomNumber) {
no = randomNumber;
}
public void run() {
System.out.println("Cube of " + no + " = " + no * no * no);
}
}
class MultiThreadingTest {
public static void main(String args[]) {
NumberThread rnThread = new NumberThread();
rnThread.start();
}
}
Output
Random Integer generated : 3
Cube of 3 = 27
Random Integer generated : 61
Cube of 61 = 226981
Random Integer generated : 58
Square of 58 = 3364
Random Integer generated : 12
Square of 12 = 144
Random Integer generated : 5
Cube of 5 = 125
Random Integer generated : 80
Square of 80 = 6400
Random Integer generated : 78
Square of 78 = 6084
Random Integer generated : 48
Square of 48 = 2304
Random Integer generated : 26
Square of 26 = 676
19
Experiment No:-18
Thread Synchronization
Output
[Hello]
[Java Programming]
Experiment No:-18
20
Swing Calculator
Aim:-Write a java program that works as a simple calculator. Arrange button for digit and the +,
-, *, %, / operations properly. Add text field to display the result. Handle any possible exception
like divide by zero with swing.
Algorithm
Step 1:Start.
Step 2:Create class calculator, extends the frame and implements ActionListener.
Step 3:Create refrence for TextField and Buttons.
Step 4:Using constructor create components JtextField, Jbutton specify their size.
Step 5:Add each component to JFrame.
Step 6:Register each button to ActionListiner.
Step 7:Specify Layout and size at JFrame.
Step 8.1:Create a function action performed and cross each JButton content store the values for
JtextField.
8.2:Jbutton specify any operation such as add, subtract, multiply, divide etc. Then call to
Acton method
Step 9:Function doAction() contains the parameter ‘op’ the specifies the operator.
9.1:If the operation = null , then set operation = op . And convert JtextField vale to integer
and store the value into its variable.
9.2:else this function perform switch case.
9.2.1:If case is ‘+’do addition, If case is ‘-’do subtraction, If case is ‘*’do multiplication, If
case is ‘/’do division, check ArithmeticException, If case is ‘%’do modulus operations.
9.2.2:Result is stored in its variable.
Step 10:Create an object of calculator and specify setVisible as true.
Step 11:Stop.
Result
The program was executed successfully and the output was verified.
Program
import javax.swing.*;
import java.awt.event.*;
class Calc extends JFrame implements ActionListener{
//JFrame f;
JTextField t;
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b0,bdiv,bmul,bsub,badd,bdec,beq,bdel,bclr;
static double a=0,b=0,result=0;
static int operator=0;
Calc(){
//f=new JFrame("Calculator");
t=new JTextField();
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");
b0=new JButton("0");
bdiv=new JButton("/");
bmul=new JButton("*");
bsub=new JButton("-");
badd=new JButton("+");
bdec=new JButton(".");
beq=new JButton("=");
bdel=new JButton("Delete");
bclr=new JButton("Clear");
t.setBounds(30,40,280,30);
b7.setBounds(40,100,50,40);
b8.setBounds(110,100,50,40);
b9.setBounds(180,100,50,40);
bdiv.setBounds(250,100,50,40);
b4.setBounds(40,170,50,40);
b5.setBounds(110,170,50,40);
b6.setBounds(180,170,50,40);
bmul.setBounds(250,170,50,40);
b1.setBounds(40,240,50,40);
b2.setBounds(110,240,50,40);
b3.setBounds(180,240,50,40);
bsub.setBounds(250,240,50,40);
bdec.setBounds(40,310,50,40);
b0.setBounds(110,310,50,40);
beq.setBounds(180,310,50,40);
badd.setBounds(250,310,50,40);
bdel.setBounds(60,380,100,40);
bclr.setBounds(180,380,100,40);
add(t);
add(b7);
add(b8);
add(b9);
add(bdiv);
add(b4);
add(b5);
add(b6);
add(bmul);
add(b1);
add(b2);
add(b3);
add(bsub);
add(bdec);
add(b0);
add(beq);
add(badd);
add(bdel);
add(bclr);
setLayout(null);
setVisible(true);
setSize(350,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b0.addActionListener(this);
badd.addActionListener(this);
bdiv.addActionListener(this);
bmul.addActionListener(this);
bsub.addActionListener(this);
bdec.addActionListener(this);
beq.addActionListener(this);
bdel.addActionListener(this);
bclr.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1)
t.setText(t.getText().concat("1"));
if(e.getSource()==b2)
t.setText(t.getText().concat("2"));
if(e.getSource()==b3)
t.setText(t.getText().concat("3"));
if(e.getSource()==b4)
t.setText(t.getText().concat("4"));
if(e.getSource()==b5)
t.setText(t.getText().concat("5"));
if(e.getSource()==b6)
t.setText(t.getText().concat("6"));
if(e.getSource()==b7)
t.setText(t.getText().concat("7"));
if(e.getSource()==b8)
t.setText(t.getText().concat("8"));
if(e.getSource()==b9)
t.setText(t.getText().concat("9"));
if(e.getSource()==b0)
t.setText(t.getText().concat("0"));
if(e.getSource()==bdec)
t.setText(t.getText().concat("."));
if(e.getSource()==badd){
a=Double.parseDouble(t.getText());
operator=1;
t.setText("");
}
if(e.getSource()==bsub){
a=Double.parseDouble(t.getText());
operator=2;
t.setText("");
}
if(e.getSource()==bmul){
a=Double.parseDouble(t.getText());
operator=3;
t.setText("");
}
if(e.getSource()==bdiv){
a=Double.parseDouble(t.getText());
operator=4;
t.setText("");
}
if(e.getSource()==beq){
b=Double.parseDouble(t.getText());
switch(operator){
case 1: result=a+b;break;
case 2: result=a-b;break;
case 3: result=a*b;break;
case 4: result=a/b;break;
default: result=0;
}
t.setText(""+result);
}
if(e.getSource()==bclr)
t.setText("");
if(e.getSource()==bdel){
String s=t.getText();
t.setText("");
for(int i=0;i<s.length()-1;i++)
t.setText(t.getText()+s.charAt(i));
}
}
public static void main(String...s){
new Calc();
}
}
Output
Experiment No:-21
Traffic Light
Aim:-Write a java program that stimulate traffic lights. The program let the user select one of the
3 traffic lights reed, green, yellow when the radio button is selected the light is turned on and only
one light can be on at a time. No light is on when the program is started.
Algorithm
Step 1:Start.
Step 2:Create class TrafficLight, extends Jframe and implements ActionListener.
Step 3:Create refrence for JTextField, JradioButton, ButtonGroup, container.
Step 4:Using constructor to specify objects of components components.
Step 5:Add each component to the container.
Step 6:Each RadioButton add to ButtonGroup.
Step 7:Each RadioButton register with listiner through add ActionListiner method.
Step 8:Set size, set visible, set Background color of JFrame.
8.1:print function,fill the colour to the traffic light.
Step 9:Function Action performed.
9.1:Initialize all TrafficLight to write. If select Red, RadioButton will fill red color, then
display message ‘Stop’.
9.2: If select Yellow, RadioButton will fill yellow color, then display message ‘Wait’.
9.3:If select Green, RadioButton will fill green color, then display message ‘Go’.
Step 10:Create main method and object of class ‘TrafficLight’.
Step 11:Stop.
Result
The program was executed successfully and the output was verified.
Program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class TrafficLight extends JFrame implements ActionListener{
String msg=" ";
JLabel label;
private JTextField display;
private JRadioButton r1,r2,r3;
private ButtonGroup bg;
private Container c;
public TrafficLight(){
setLayout(new FlowLayout());
c=getContentPane();
label=new JLabel(" Traffic Light");
display =new JTextField(10);
r1=new JRadioButton("RED");
r2=new JRadioButton("GREEN");
r3=new JRadioButton("YELLOW");
bg=new ButtonGroup();
c.add(label);
c.add(r1);
c.add(r2);
c.add(r3);
c.add(display);
bg.add(r1);
bg.add(r2);
bg.add(r3);
r1.addActionListener(this);
r2.addActionListener(this);
r3.addActionListener(this);
setSize(400,400);
setVisible(true);
c.setBackground(Color.pink);
}
public void actionPerformed(ActionEvent ie){
msg=ie.getActionCommand();
if (msg.equals("RED")){
c.setBackground(Color.RED);
display.setText(msg+ " :TURN ON");
}
else if (msg.equals("GREEN")){
c.setBackground(Color.GREEN);
display.setText(msg+ " :TURN ON");
}
else if (msg.equals("YELLOW")){
c.setBackground(Color.YELLOW);
display.setText(msg+ " :TURN ON");
}
}
public static void main(String args[]){
TrafficLight light=new TrafficLight();
light.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output
Experiment No:-22
Binary search
Output