Java Lab
Java Lab
import java.util.Scanner;
class PrimeExample
{
public static void main(String arg[])
{
int i,count;
System.out.print("Enter n value : ");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.println("Prime numbers between 1 to "+n+" are ");
for(int j=2;j<=n;j++)
{
count=0;
for(i=1;i<=j;i++)
{
if(j%i==0)
{
count++;
}
}
if(count==2)
System.out.print(j+" ");
}
}
}
b. Write a Java program that prints all real solutions to the quadratic equation ax 2+bx+c=0. Read
in a, b, c and use the quadratic formula.
import java.io.*;
import java.util.Scanner;
double x1,x2,disc,a,b,c;
double xr,xi;
Scanner sc=new Scanner(System.in);
System.out.println("enter a,b,c values");
a=Double.parseDouble(sc.next());
b=Double.parseDouble(sc.next());
c=Double.parseDouble(sc.next());
disc=(b*b)-(4*a*c);
if(disc==0)
{
System.out.println("roots are real and equal");
x1=x2=b/(2.0*a);
System.out.println("roots are"+x1 +","+x2);
}
else if(disc>0)
{
System.out.println("roots are real and unequal");
x1=(-b+Math.sqrt(disc))/(2.0*a);
x2=(-b-Math.sqrt(disc))/(2.0*a);
System.out.println("rootsare"+x1 +","+x2);
}
else
{
xr=(-b/(2.0*a));
disc=Math.abs(disc);
xi=(Math.sqrt(disc)/(2.0*a));
System.out.println("roots are imaginary");
System.out.println("root1:"+xr+"+"+xi+"i,");
System.out.println("root2:"+xr+"-"+xi+"i,");
}
}
}
Output:
enter a,b,c values
123
roots are imaginary
root1:-1.0+1.4142135623730951i,
root2:-1.0-1.4142135623730951i,
enter a,b,c values
1 -2 -3
roots are real and unequal
rootsare3.0,-1.0
enter a,b,c values
121
roots are real and equal
roots are1.0,1.0
c. Develop a Java application to generate Electricity bill. Create a class with the following
members: Consumer no., consumer name, previous month reading, current month reading, type
of EB connection
(i.e domestic or commercial). Commute the bill amount using the following tariff.
If the type of the EB connection is domestic, calculate the amount to be paid as follows:
First 100 units - Rs. 1 per unit
101-200 units - Rs. 2.50 per unit
201 -500 units - Rs. 4 per unit
> 501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid as follows:
First 100 units - Rs. 2 per unit
101-200 units - Rs. 4.50 per unit
201 -500 units - Rs. 6 per unit
> 501 units - Rs. 7 per unit
import java.util.Scanner;
class ElectBill
{
int ConsumerNo;
String ConsumerName;
int PrevReading;
int CurrReading;
int ActualReading;
String EBConn;
double Bill;
void input_data()
{
Scanner sc = new Scanner(System.in);
System.out.println("\n Enter Consumer Number: ");
ConsumerNo = sc.nextInt();
System.out.println("\n Enter Consumer Name: ");
ConsumerName = sc.next();
System.out.println("\n Enter Previous Units: ");
PrevReading = sc.nextInt();
do{
System.out.println("Enter Current Units consumed:");
CurrReading = sc.nextInt();
}while(CurrReading < PrevReading);
ActualReading = CurrReading - PrevReading;
System.out.println("Enter the types of EB Connection(domestic or commercial)");
EBConn = sc.next();
}
double calculate_bill()
{
int choice;
if(EBConn=="domenstic")
choice=1;
else
choice=2;
switch(choice)
{
case 1:
if(ActualReading>=0 && ActualReading<=100)
Bill=ActualReading*1;
else if(ActualReading>100 && ActualReading <= 200)
Bill=(100*1)+((ActualReading-100)*2.50);
else if(ActualReading>200 && ActualReading <= 500)
Bill=(100*1)+(100*2.50)+((ActualReading-200)*4);
else
Bill=(100*1)+(100*2.50)+(300*4)+((ActualReading-
500)*6);
break;
case 2:
if(ActualReading>=0 && ActualReading<=100)
Bill=ActualReading*2;
else if(ActualReading>100 && ActualReading <= 200)
Bill=(100*1)+((ActualReading-100)*4.50);
else if(ActualReading>200 && ActualReading <= 500)
Bill=(100*1)+(100*2.50)+((ActualReading-200)*6);
else
Bill=(100*1)+(100*2.50)+(300*4)+((ActualReading-
500)*7);
break;
}
return Bill;
}
void display()
{
System.out.println(" ");
System.out.println("ELCTRICITY BILL");
System.out.println(" ");
System.out.println("Consumer Number: "+ConsumerNo);
System.out.println("Consumer Name: "+ConsumerName);
System.out.println("Consumer Previous Units: "+PrevReading);
System.out.println("Consumer Current Units: "+CurrReading);
System.out.println("Consumer Actual Units: "+ActualReading);
System.out.println("Type of EBConnection: "+EBConn);
System.out.println(" ");
System.out.println("Total Amount(Rs.): "+Bill);
}
}
class ElectBillGen
{
public static void main (String[] args)
{
ElectBill b=new ElectBill();
b.input_data();
b.calculate_bill();
b.display();
}
}
import java.io.*;
import java.util.Scanner;
class MatrixMultiplication
{
static void printMatrix(int M[][],int rowSize,int colSize)
{
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++)
System.out.print(M[i][j] + " ");
System.out.println();
}
}
System.out.println();
}
}
static void multiplyMatrix( int row1, int col2, int row2,int A[][],int B[][],int C[][])
{
int i, j, k;
readMatrix(A,row1,col1);
readMatrix(B,row2,col2);
Prepared by: Priyanka PM.Tech., Asst. Professor Page 6
20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB
System.out.println("\nMatrix A:");
printMatrix(A, row1, col1);
System.out.println("\nMatrix B:");
printMatrix(B, row2, col2);
Week -2
a) write a java program that uses inheritance concept.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args []) {
A superOb = new A();
B subOb = new B();
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Output:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
/*
Output:
Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 40.0
b. Write Java program on dynamic binding, differentiating method overloading and overriding.
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
Output:
Inside A's callme method
Inside B's callme method
Inside C's callme method
Output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
Output:
i and j: 1 2
k: 3
//Currency Exchange
import java.io.*;
import java.util.Scanner;
interface CurrencyInterface
{
public double DollarToINR(double Dollars);
public double INRToDollar(double INR);
public double EuroToINR(double Euros);
public double INRToEuro(double INR);
public double YenToINR(double Yens);
public double INRToYen(double INR);
}
class CurrencyClass implements CurrencyInterface
{
double ER = 0;
public CurrencyClass(double CurrentExchange)
{
ER = CurrentExchange;
}
public double DollarToINR(double Dollars)
{
double INR = 0;
INR = Dollars * ER;
return INR;
}
public double INRToDollar(double INR)
{
double Dollars = 0;
Dollars = INR / ER;
return Dollars;
}
public double EuroToINR(double Euros)
{
double INR = 0;
INR = Euros * ER;
return INR;
}
public double INRToEuro(double INR)
{
double Euros = 0;
Euros = INR / ER;
return Euros;
}
public double YenToINR(double Yens)
{
double INR = 0;
INR = Yens * ER;
return INR;
}
public double INRToYen(double INR)
{
double Yens = 0;
Yens = INR / ER;
return Yens;
}
}
class CurrencyConverter
{
public static void main(String[] args) throws NoClassDefFoundError
{
double CurrentExchange;
int choice;
double inr;
char ans='y';
Scanner input = new Scanner(System.in);
do
{
System.out.println("Menu For Currency Conversion");
System.out.println("1. Dollar to INR");
System.out.println("2. INR to Dollar");
System.out.println("3. Euro to INR");
System.out.println("4. INR to Euro");
System.out.println("5. Yen to INR");
System.out.println("6. INR to Yen");
Week-3
a. Write Java program that inputs 5 numbers, each between 10 and 100 inclusive. As each
number is read display it only if it’s not a duplicate of any number already read display the
complete set of unique values input after the user enters each new value.
import java.io.*;
import java.util.Scanner;
int count = 0;
int x = 0;
int num = 0;
if (!digit)
{
{
System.out.print(sid[i] +” “);
}
} //End of while loop
}
}
Output:
enter 5 integers between 10 and 100
12
The elements are: 12
enter 5 integers between 10 and 100
33
The elements are: 12
33
enter 5 integers between 10 and 100
1000
invalid range
The elements are: 12
33
Duplicate value
enter 5 integers between 10 and 100
55
The elements are: 12
33
55
b. Write a Java Program to create an abstract class named Shape that contains two integers
and an empty method named print Area(). Provide three classes named Rectangle, Triangle
and Circle such that each one of the classes extends the class Shape. Each one of the classes
contains only the method print Area () that prints the area of the given shape.
}
double printArea() {
System.out.println("Inside Rectangle Class.");
return dim1 * dim2;
}
}
class Triangle extends Shape {
Triangle(double b, double h) {
super(b, h);
}
// override area for right triangle
double printArea() {
System.out.println("Inside Triangle Class.");
return dim1 * dim2 / 2;
}
}
class Circle extends Shape {
Circle(double pi, double r) {
super(pi, r);
}
double printArea() {
System.out.println("Inside Circle Class.");
return dim1 * (dim2 * dim2);
}
}
class AbstractShape {
public static void main(String args[]) {
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Circle c = new Circle(2,3);
c. Write a Java program to read the time intervals (HH:MM) and to compare system time if
the system Time between your time intervals print correct time and exit else try again to
repute the same thing. By using String Toknizer class.
import java.io.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.StringTokenizer;
do{
System.out.println(“Enter User Time in hh:hh format:- “);
String mytime = br.readLine();
if(n1 == n2)
{
cnt++;
}
else
{
System.out.println(“Given time is out of the range, Try
Again...”);
break;
}
}
}while(cnt < 2);
Week-4
a. Write a Java program to implement user defined exception handling.
class NestTry{
public static void main(String args[])
{
try
{
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try {
if(a==1)
a = a/(a-a);
if(a==2) {
int c[] = { 1 };
c[42] = 99;
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
Output:
C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a=2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}
Output:
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]
b. Write java program that inputs 5 numbers, each between 10 and 100 inclusive. As each
number is read display it only if it‘s not a duplicate of any number already read. Display the
complete set of unique values input after the user enters each new value.
import java.io.*;
import java.util.Scanner;
int count = 0;
int x = 0;
int num = 0;
if (!digit)
{
}
} //End of while loop
}
}
Output:
enter 5 integers between 10 and 100
12
The elements are: 12
enter 5 integers between 10 and 100
33
The elements are: 12
33
enter 5 integers between 10 and 100
1000
invalid range
The elements are: 12
33
Duplicate value
enter 5 integers between 10 and 100
55
The elements are: 12
33
55
Week-5
a. Write a Java program that creates a user interface to perform integer division. The user
enters two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2
is displayed in the Result field when the Divide button is clicked. If Num1 and Num2 were
not integers, the program would throw a Number Format Exception. If Num2 were zero,
the program would throw an Arithmetic Exception Display the exception in a message
dialog box.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
{
try
{
System.out.println(“ “);
}
catch(Exception e)
{
System.out.println(“ArithematicException”+e);
}
msg=”Arithemetic Exception”;
repaint();
}
else if((num1<0)||(num2<0))
{
try
{
System.out.println(“”);
}
catch(Exception e)
{
System.out.println(“NumberFormat”+e);
}
msg=”NumberFormat Exception”;
repaint();
}
else
{
int num3=num1/num2;
res.setText(String.valueOf(num3));
}
}
}
public void paint(Graphics g)
{
g.drawString(msg,30,150);
}
}
b. Write a Java program that creates three threads. First thread displays ―Good Morningǁ
every one second, the second thread displays ―Helloǁ every two seconds and the third thread
displays ―Welcomeǁ every three seconds.
while(true)
{
sleep(1000);
System.out.println(“Good Morning”);
}
}
catch(Exception e)
{ System.out.println(“Exception: “+e);}
}
}
class B extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(2000);
System.out.println(“Hello”);
}
}
catch(Exception e)
{ System.out.println(“Exception: “+e);}
}
}
class C extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(3000);
System.out.println(“welcome”);
}
}
catch(Exception e)
{ System.out.println(“Exception: “+e);}
}
}
class Week4c
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
t1.start();
t2.start();
t3.start();
}
}
Week-6
a. Write a java program to split a given text file into n parts. Name each part as the name of
the original file followed by .part where n is the sequence number of the part file.
import java.io.*;
class FileSplit {
public static void splitFile(File f) throws IOException {
int partCounter = 1;
long fsize = f.length();
System.out.println(“The file size is: “+fsize);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(“How many file parts you want: “);
int n = Integer.parseInt(br.readLine());
int tmp = 0;
while ((tmp = bis.read(buffer)) > 0) {
bis.close();
}
public static void main(String[] args)throws IOException {
// TODO Auto-generated method stub
splitFile(new File(“d:\\Vinu.txt”));
}
b. Write a Java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, or writable, the type of file and the length
of the file in bytes.
import java.io.*;
import java.swing.*;
class FileDemo
{
public static void main(String args[])
{
String filename = JOptionPane.showInputDialog("Enter filename: ");
File f = new File(filename);
System.out.println("File exists: "+f.exists());
System.out.println("File is readable: "+f.canRead());
System.out.println("File is writable: "+f.canWrite());
System.out.println("Is a directory: "+f.isDirectory());
System.out.println("length of the file: "+f.length()+" bytes");
try
{
char ch;
StringBuffer buff = new StringBuffer("");
FileInputStream fis = new FileInputStream(filename);
while(fis.available()!=0)
{
ch = (char)fis.read();
buff.append(ch);
}
System.out.println("\nContents of the file are: ");
System.out.println(buff);
fis.close();
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOException i)
{
System.out.println("Cannot read file...");
}
}
}
OUTPUT
File name: sample.txt
Week-7
a. Write a java program that displays the number of characters, lines and words in a text file.
//Program to count number of lines,characters,and words in a text file
import java.util.*;
import java.io.*;
class week7a
{
public static void main(String args[])throws IOException
{
int nl=1,nw=0;
char ch;
Scanner scr=new Scanner(System.in);
System.out.print("\nEnter File name: ");
String str=scr.nextLine();
FileInputStream f=new FileInputStream(str);
int n=f.available();
for(int i=0;i<n;i++)
{
ch=(char)f.read();
if(ch=='\n')
nl++;
else if(ch==' ')
nw++;
}
System.out.println("\nNumber of lines : "+nl);
System.out.println("\nNumber of words : "+(nl+nw));
System.out.println("\nNumber of characters : "+n);
}
}
Output:
b. Write a java program that reads a file and displays the file on the screen with line number
before each line.
/Program to print the contents of the file along with line number
import java.util.*;
import java.io.*;
class week7b
{
public static void main(String args[])throws IOException
{
int j=1;
char ch;
Scanner scr=new Scanner(System.in);
System.out.print("\nEnter File name: ");
String str=scr.next();
FileInputStream f=new FileInputStream(str);
System.out.println("\nContents of the file are");
int n=f.available();
System.out.print(j+": ");
for(int i=0;i<n;i++)
{
ch=(char)f.read();
System.out.print(ch);
if(ch=='\n')
{
System.out.print(++j+": ");
}
}
}
Output:
Enter File name: temp.txt
Contents of the file are :
1: aaaaa
2: bbbb
3: cccc
Week-8
a. Write a Java program that correctly implements producer consumer problem using the
concept of inter thread communication.
import java.util.Scanner;
class Q
{
int n;
Scanner sc=new Scanner(System.in);
boolean valueSet=false;
String d="";
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
System.out.println("Got:"+n);
valueSet=false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet)
try
{
wait();
System.out.print("enter data");
n=Integer.parseInt(sc.next());
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
this.n=n;
valueSet=true;
System.out.println("Put:"+n);
notify();
}
}
Output:
Put:0
b. Develop a Java application for stack operation using Buttons and JOptionPane input and
Message dialog box.
import javax.swing.JOptionPane;
while (!done) {
try{
choice = JOptionPane.showInputDialog(
"1. push \n" +
"2. pop \n" +
"3. peek \n" +
"4. check empty \n" +
"5. print the stack \n" +
"6. exit \n \n" +
"choose one:");
switch (Integer.parseInt(choice)){
case 1:
String temp = JOptionPane.showInputDialog("Input integer to push:");
s.push(Integer.parseInt(temp));
break;
case 2:
JOptionPane.showMessageDialog(null, "The value popped is " + s.pop());
break;
case 3:
}
}
}
import java.util.Scanner;
import javax.swing.JoptionPane;
int answer;
fnum = norbel.nextInt();
String operator = JoptionPane.showInputDialog(“Operation:n 1.Additionn 2.Subtractionn
3.Multiplicationn 4.Divisionn”);
Integer opt = Integer.parseInt(operator);
if(opt == 1)
{
String opt1 = JoptionPane.showInputDialog(“Enter second Integer: “);
int snum = Integer.parseInt(opt1);
snum = norbel.nextInt();
answer = fnum + snum;
String ans = “Answer” +answer+ “!”;
JoptionPane.showMessageDialog(null,answer);
if(opt == 2)
{
String opt2 = JoptionPane.showInputDialog(“Enter second Integer: “);
int snum = Integer.parseInt(opt2);
snum = norbel.nextInt();
answer = fnum - snum;
String ans = “Answer” +answer+ “!”;
JoptionPane.showMessageDialog(null,ans);
}
if(opt == 3)
{
String opt3 = JoptionPane.showInputDialog(“Enter second Integer: “);
int snum = Integer.parseInt(opt3);
snum = norbel.nextInt();
answer = fnum * snum;
String ans = “Answer” +answer+ “!”;
JoptionPane.showMessageDialog(null,ans);
}
if(opt == 4)
{
String opt4 = JoptionPane.showInputDialog(“Enter second Integer: “);
int snum = Integer.parseInt(opt4);
snum = norbel.nextInt();
answer = fnum / snum;
String ans = “Answer” +answer+ “!”;
JoptionPane.showMessageDialog(null,ans);
}
else
{
String error = “Error”;
JoptionPane.showMessageDialog(null, error);
}
}
}
Week-9
a. Develop a Java application for the blinking eyes and mouth should open while blinking.
import java.applet.Applet;
//<applet code="A.class" width=200 height=200></applet>
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
if (flag == 0) {
System.out.println(flag);
g.drawOval(40, 40, 120, 150);// face
g.drawRect(57, 75, 30, 5);// left eye shut
g.drawRect(110, 75, 30, 20);// right eye
g.drawOval(85, 100, 30, 30);// nose
g.fillArc(60, 125, 80, 40, 180, 180);// mouth
g.drawOval(25, 92, 15, 30);// left ear
g.drawOval(160, 92, 15, 30);// right ear
flag = 1;
} else {
System.out.println(flag);
g.drawOval(40, 40, 120, 150);// face
g.drawOval(57, 75, 30, 20);// left eye
g.drawOval(110, 75, 30, 20);// right eye
g.fillOval(68, 81, 10, 10);// left pupil
g.fillOval(121, 81, 10, 10);// right pupil
g.drawOval(85, 100, 30, 30);// nose
g.fillArc(60, 125, 80, 40, 180, 180);// mouth
g.drawOval(25, 92, 15, 30);// left ear
g.drawOval(160, 92, 15, 30);// right ear
flag = 0;
}
try {
Thread.sleep(900);
} catch (Exception e) {
System.out.println("killed while sleeping");
}
this.repaint(100);
}
}
public void init() {
this.C = new MyCanvas();
this.setLayout(new BorderLayout());
this.add(C, BorderLayout.CENTER);
C.setBackground(Color.GRAY);
}
private MyCanvas C;
}
b. Develop a Java application that simulates a traffic light. The program lets the user select
one of three lights: Red, Yellow or Green with radio buttons. On selecting a button an
appropriate message with ―STOPǁ or ―READYǁ or ǁGOǁ should appear above the
buttons in selected color. Initially, there is no message shown.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/*
* <applet code = "TrafficLightsExample" width = 1000 height = 500>
* </applet>
* */
redLight.addItemListener(this);
yellowLight.addItemListener(this);
greenLight.addItemListener(this);
add(redLight);
add(yellowLight);
add(greenLight);
add(msg);
msg.setFont(new Font("Serif", Font.BOLD, 20));
}
public void itemStateChanged(ItemEvent ie) {
redLight.setForeground(Color.BLACK);
yellowLight.setForeground(Color.BLACK);
greenLight.setForeground(Color.BLACK);
if(redLight.getState() == true) {
redLight.setForeground(Color.RED);
msg.setForeground(Color.RED);
msg.setText("STOP");
}
else if(yellowLight.getState() == true) {
yellowLight.setForeground(Color.YELLOW);
msg.setForeground(Color.YELLOW);
msg.setText("READY");
}
else{
greenLight.setForeground(Color.GREEN);
msg.setForeground(Color.GREEN);
msg.setText("GO");
}
}
}
OUTPUT
Week-10
a. Develop a Java application to implement the opening of a door while opening man should
present before hut and closing man should disappear.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Animation extends JFrame implements ActionListener
{
ImageIcon ii1, ii2;
Container c;
JButton b1,b2;
JLabel lb1;
Animation()
{
c = getContentPane();
c.setLayout(null);
ii1 = new ImageIcon("house0.jpg");
ii2 = new ImageIcon("house1.jpg");
lb1 = new JLabel(ii1);
lb1.setBounds(50,10,500,500);
b1 = new JButton("Open");
b2 = new JButton("Close");
b1.addActionListener(this);
b2.addActionListener(this);
b1.setBounds(650,240,70,40);
b2.setBounds(650,320,70,40);
c.add(lb1);
c.add(b1);
c.add(b2);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if( str.equals("Open") )
lb1.setIcon(ii2);
else
lb1.setIcon(ii1);
}
public static void main(String args[])
{
Animation ob = new Animation();
ob.setTitle("Animation");
ob.setSize(800,600);
ob.setVisible(true);
ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
b. Develop a Java application by using JtextField to read decimal value and converting a
decimal number into binary number then print the binary value in another JtextField.
conversion[counter]=String.valueOf(dec);
complete[0]=conversion[counter]+complete[0];
user=user/2;
counter+=1;
}
while(user !=0);
q2.setText(String.valueOf(complete[user]));
}
}
}
Week-11
a. Develop a Java application that handles all mouse events and shows the event name at the
center of the window when a mouse event is fired. Use adapter classes.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="Week11a" width=500 height=500></applet> */
public class Week11a extends Applet
implements MouseListener,MouseMotionListener
{
int X=0,Y=20;
String msg="MouseEvents";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
setForeground(Color.red);
}
public void mouseEntered(MouseEvent m)
{
setBackground(Color.magenta);
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent m)
{
setBackground(Color.black);
showStatus("Mouse Exited");
repaint();
}
public void mousePressed(MouseEvent m)
{
X=10;
Y=20;
msg="NEC";
setBackground(Color.green);
repaint();
}
public void mouseReleased(MouseEvent m)
{
X=10;
Y=20;
msg="Engineering";
setBackground(Color.blue);
repaint();
}
public void mouseMoved(MouseEvent m)
{
X=m.getX();
Y=m.getY();
msg="College";
setBackground(Color.white);
showStatus("Mouse Moved");
repaint();
}
public void mouseDragged(MouseEvent m)
{
msg="CSE";
setBackground(Color.yellow);
showStatus("Mouse Moved"+m.getX()+" "+m.getY());
repaint();
}
public void mouseClicked(MouseEvent m)
{
msg="Students";
setBackground(Color.pink);
showStatus("Mouse Clicked");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
Output:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyboardEventsPro" width=300 height=100>
</applet>
*/
public class KeyboardEventsPro extends Applet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}
Output:
Week-12
a. Develop a Java application to find the maximum value from the given type of elements
using a generic function.
if (y.compareTo(max) > 0)
max = y; // y is the largest so far
if (z.compareTo(max) > 0)
max = z; // z is the largest
b. Develop a Java application that works as a simple calculator. Use a grid layout to arrange
buttons for the digits and for the +, -,*, % operations. Add a text field to display the result.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=calc width=200 height=200></applet>*/
public class calc extends Applet implements ActionListener
{
TextField t1;
String a="",b;
String oper="",s="",p="";
int first=0,second=0,result=0;
Panel p1;
Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9;
Button add,sub,mul,div,mod,res,space;
public void init()
{
Panel p2,p3;
p1=new Panel();
p2=new Panel();
p3=new Panel();
t1=new TextField(a,20);
p1.setLayout(new BorderLayout());
p2.add(t1);
b0=new Button("0");
b1=new Button("1");
b2=new Button("2");
b3=new Button("3");
b4=new Button("4");
b5=new Button("5");
b6=new Button("6");
b7=new Button("7");
b8=new Button("8");
b9=new Button("9");
add=new Button("+");
sub=new Button("-");
mul=new Button("*");
div=new Button("/");
mod=new Button("%");
res=new Button("=");
space=new Button("c");
p3.setLayout(new GridLayout(4,4));
b0.addActionListener(this);
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);
Prepared by: Priyanka PM.Tech., Asst. Professor Page 49
20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
res.addActionListener(this);
space.addActionListener(this);
p3.add(b0);
p3.add(b1);
p3.add(b2);
p3.add(b3);
p3.add(b4);
p3.add(b5);
p3.add(b6);
p3.add(b7);
p3.add(b8);
p3.add(b9);
p3.add(add);
p3.add(sub);
p3.add(mul);
p3.add(div);
p3.add(mod);
p3.add(res);
p3.add(space);
p1.add(p2,BorderLayout.NORTH);
p1.add(p3,BorderLayout.CENTER);
add(p1);
}
public void actionPerformed(ActionEvent ae)
{
a=ae.getActionCommand();
if(a=="0"||a=="1"||a=="2"||a=="3"||a=="4"||a=="5"||a=="6"||a=="7"||a=="8"||a=="9")
{
t1.setText(t1.getText()+a);
}
if(a=="+"||a=="-"||a=="*"||a=="/"||a=="%")
{
first=Integer.parseInt(t1.getText());
oper=a;
t1.setText("");
}
Prepared by: Priyanka PM.Tech., Asst. Professor Page 50
20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB
if(a=="=")
{
if(oper=="+")
result=first+Integer.parseInt(t1.getText());
if(oper=="-")
result=first-Integer.parseInt(t1.getText());
if(oper=="*")
result=first*Integer.parseInt(t1.getText());
if(oper=="/")
result=first/Integer.parseInt(t1.getText());
if(oper=="%")
result=first%Integer.parseInt(t1.getText());
t1.setText(result+"");
}
if(a=="c")
t1.setText("");
}
}
Output:
implements MouseListener,MouseMotionListener
{
int X=0,Y=20;
String msg="MouseEvents";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
setForeground(Color.red);
}
public void mouseEntered(MouseEvent m)
{
setBackground(Color.magenta);
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent m)
{
setBackground(Color.black);
showStatus("Mouse Exited");
repaint();
}
public void mousePressed(MouseEvent m)
{
X=10;
Y=20;
msg="NEC";
setBackground(Color.green);
repaint();
}
public void mouseReleased(MouseEvent m)
{
X=10;
Y=20;
msg="Engineering";
setBackground(Color.blue);
repaint();
}
public void mouseMoved(MouseEvent m)
{
X=m.getX();
Y=m.getY();
msg="College";
setBackground(Color.white);
showStatus("Mouse Moved");
repaint();
}
public void mouseDragged(MouseEvent m)
{
msg="CSE";
setBackground(Color.yellow);
showStatus("Mouse Moved"+m.getX()+" "+m.getY());
repaint();
}
public void mouseClicked(MouseEvent m)
{
msg="Students";
setBackground(Color.pink);
showStatus("Mouse Clicked");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
Output:
Week-13
a. Develop a Java application to establish a JDBC connection, create a table student with
properties name, register number, mark1, mark2, mark3. Insert the values into the table by
using the java and display the information of the students at front end.
import java.awt.*;
import javax.swing.*;
import java.sql.*;
c.add(l2);
t2.setBounds(95,70,108,20);
c.add(t2);
l3.setBounds(40,100,50,20);
c.add(l3);
t3.setBounds(95,100,108,20);
c.add(t3);
b1.setBounds(10,140,65,40);
c.add(b1);
b2.setBounds(77,140,65,40);
c.add(b2);
//b3.setBounds(144,140,65,40);
//c.add(b3);
//b4.setBounds(211,140,65,40);
//c.add(b4);
Info=new Label(“Getting connected to the database”);
Info.setFont(new Font(“Dialog”,Font.BOLD,15));
Info.setBounds(20,190,330,30);
c.add(info);
b1.addActionListener(new InsertListener());
b2.addActionListener(new DisplayListener());
setVisible(true);
getConnection();
}
Void getConnection()
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String url=”jdbc:odbc:student”;
Con=DriverManager.getConnection(url,”scott”,”tiger”);
Info.setText(“Connection is established with the database”);
insertps=con.prepareStatement(“Insert into student values(?,?,?,?,?)”);
selectps=con.prepareStatement(“select * from student where studentno=?”);
}
Catch(ClassNotFoundExceptoin e)
{
System.out.println(“Driver class not found….”);
System.out.println(e);
}
Catch(SQLExceptoin e)
{
Info.setText(“Unable to get connected to the database”);
}
}
class insertListener implements ActionListener
{
Public void actionPerformed(ActionEvent e)
{
Try
{
Int sno=Integer.parseInt(t1.getText());
String name=t2.getText();
Int m1= Integer.parseInt(t3.getText());
Int m2=Integer.parseInt(t1.getText());
Int m3=Integer.parseInt(t1.getText());
Insertps.setInt(1,sno);
Insertps.setString(2,name);
Insertps.setInt(3,m1);
Insertps.setInt(4,m2);
Insertps.setInt(5,m3);
Insertps.executeUpdate();
Info.setText(“One row inserted successfully”);
Insertps.clearParameters();
T1.setText(“”);
T2.setText(“”);
T3.setText(“”);
T4.setText(“”);
T5.setText(“”);
}
Catch(SQLException se)
{
Info.setText(“Failed to insert a record…”);
}
Catch(Exception de)
{
Info.setText(“enter proper data before insertion….”);
}
}
}
Class DisplayListener implements ActionListener
{
Public void actionPerformed(ActionEvent e)
{
Try
{
Int
sno=Integer.parseInt(t1.getText());
Selectps.setInt(1,sno);
Selectps.execute();
ResultSet rs=selectps.getResultSet();
rs.next();
t2.setText(rs.getString(2));
t3.setText(“”+rs.getFloat(3));
info.setText(“One row displayed successfully”);
selectps.clearPameters();
}
Catch(SQLException se)
{
Info.setText(“Failed to
show the record…”);
}
Catch(Exception de)
{
Info.setText(“enter proper student no before selecting
show..”);
}
}
}
Public static void main(String args[])
{
New StudentForm();
}
}