0% found this document useful (0 votes)
349 views69 pages

R20 JAVA LAB MANUAL - With Outputs

Week 1 tasks include: 1. Installing Java software and learning an IDE like Eclipse or NetBeans 2. Creating a test project and class to find prime numbers between 1 to n 3. Writing a program to solve quadratic equations using the quadratic formula 4. Developing an application to generate electricity bills based on units consumed and connection type

Uploaded by

kumardhadi1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
349 views69 pages

R20 JAVA LAB MANUAL - With Outputs

Week 1 tasks include: 1. Installing Java software and learning an IDE like Eclipse or NetBeans 2. Creating a test project and class to find prime numbers between 1 to n 3. Writing a program to solve quadratic equations using the quadratic formula 4. Developing an application to generate electricity bills based on units consumed and connection type

Uploaded by

kumardhadi1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

Week-1

A. Installation of Java software, study of any Integrated development


environment, Use Eclipse or Netbean platform and acquaint with the various
menus. Create a test project, add a test class and run it. See how you can use auto
suggestions, auto fill. Try code formatter and code refactoring like renaming
variables, methods and classes. Try debug step by step with java program to find
prime numbers between 1 to n.
IMPLEMENTATION

class PrimeNumbers
{

public static void main(String[] jbrec)


{
try
{
System.out.println("***** PRIME NUMBERS *****");

Scanner objScanner = new Scanner(System.in);

System.out.print("\nEnter n Value:");

long n = objScanner.nextInt();

for (long i = 2; i <= n; i++)


{
boolean isprime = isNumPrime(i);
if (isprime)
{
System.out.print(i + " ");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static boolean isNumPrime(long number)
{
boolean result = true;

for (long i = 2; i <= number / 2; i++)


{
if ((number % i) != 0)
{
result = true;
}
else
{
result = false;
break;
}
}

return result;
}
}

B. Write a Java program that prints all real solutions to the quadratic equation
ax2+bx+c=0. Read in a, b, c and use the quadratic formula.

IMPLEMENTATION
import java.util.*;
class Roots
{
public static void main(String args[])
{
int a,b,c,d,f=0;
Scanner scr=new Scanner(System.in);
System.out.println("\nEnter the values of a ,b ,c : ");
a=scr.nextInt();
b=scr.nextInt();
c=scr.nextInt();
d=(b*b)-(4*a*c);
if(d==0)
{
System.out.println("Roots are real and Equal");
f=1;
}
else if(d>0)
{
System.out.println("Roots are real and UnEqual");
f=1;
}
else
System.out.println("Roots are imaginary");
if(f==1)
{
float r1=(float)(-b+Math.sqrt(d))/(2*a);
float r2=(float)(-b-Math.sqrt(d))/(2*a);
System.out.println("Roots are : "+r1+" ,"+r2);
}
}
}
Output:
Enter the values of a ,b ,c :
1
2
-3
Roots are real and UnEqual

Roots are : 1.0 ,-3.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

IMPLEMENTATION
import java.util.Scanner;
class ElectBill
{
int ConsumerNo;
String ConsumerName;
int PrevReading;
int CurrReading;
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();
System.out.println("Enter Current Units consumed:");
CurrReading = sc.nextInt();
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(CurrReading>=0 && CurrReading<=100)
Bill=CurrReading*1;
else if(CurrReading>100 && CurrReading <= 200)
Bill=(100*1)+((CurrReading-100)*2.50);
else if(CurrReading>200 && CurrReading <= 500)
Bill=(100*1)+(100*2.50)+((CurrReading-200)*4);
else
Bill=(100*1)+(100*2.50)+(300*4)+((CurrReading-500)*6);
break;
case 2:
if(CurrReading>=0 && CurrReading<=100)
Bill=CurrReading*2;
else if(CurrReading>100 && CurrReading <= 200)
Bill=(100*1)+((CurrReading-100)*4.50);
else if(CurrReading>200 && CurrReading <= 500)
Bill=(100*1)+(100*2.50)+((CurrReading-200)*6);
else
Bill=(100*1)+(100*2.50)+(300*4)+((CurrReading-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("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();
}
}
Output
Enter Consumer Number:
101
Enter Consumer Name:
AAA
Enter Previous Units:
310
Enter Current Units consumed:
480
Enter the types of EB Connection(domestic or commercial)
domestic
----------------------------------
ELCTRICITY BILL
----------------------------------
Consumer Number: 101
Consumer Name: AAA
Consumer Previous Units: 310
Consumer Current Units: 480
Type of EBConnection: domestic
----------------------------------
Total Amount(Rs.): 2030.0

D. Write a Java program to multiply two given matrices.

IMPLEMENTATION

public class MatrixMultiplicationExample


{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices


for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}
}

Output:
666
12 12 12
18 18 18
WEEK 2:
A. Write Java program on use of inheritance, preventing inheritance using final, abstract
classes.

IMPLEMENTATION

/*program without final*/

abstract class A
{
abstract void displayInfo() ;

}
class B extends A
{
public void displayInfo()
{
System.out.println("Welcome");
}

}
class C extends B
{
public void displayInfo()
{
System.out.println("CSE");
}
}
class Hello {
public static void main(String[] args) {
C c1 = new C();
c1.displayInfo();
}
}
/* program using final*/
abstract class A
{
abstract void displayInfo() ;

final class B extends A


{
public void displayInfo()
{
System.out.println("Welcome");
}

}
class C extends B
{
public void displayInfo()
{
System.out.println("CSE");
}
}
class Hello {
public static void main(String[] args) {
C c1 = new C();
c1.displayInfo();
}
}
b. Write Java program on dynamic binding, differentiating method overloading and
overriding.

IMPLEMENTATION
class Animals
{
public void sound()
{
System.out.println("This is parent class.");
}
}

class Dogs extends Animals


{
public void sound()
{
System.out.println("Dogs bark");
}
}
class Cats extends Animals
{
public void sound(int a)
{
System.out.println("a="+a);
}
}
class Monkeys extends Animals
{
public void sound()
{
System.out.println("Monkeys whoop.");
}
}
class Demo
{
public static void main(String[] args)
{
Dogs e=new Dogs();
Animals d = new Dogs();
Cats c = new Cats();
Animals m = new Monkeys();

e.sound();
d.sound();
c.sound(5);
m.sound();
}
}

C. Develop a java application to implement currency converter (Dollar to INR, EURO to INR,
Yen) using Interfaces.

IMPLEMENTATION
import java.util.*;
import java.util.*;
import java.io.*;
interface Currency
{
public void dollartorupee();
public void rupeetodollar();
public void eurotorupee();
public void rupeetoeuro();
public void yentorupee();
public void rupeetoyen();
}
class CurrencyDemo implements Currency
{
double inr,usd;
double euro,yen;
Scanner in=new Scanner(System.in);
public void dollartorupee()
{
System.out.println("Enter dollars to convert into Rupees:");
usd=in.nextInt();
inr=usd*67;
System.out.println("Dollar ="+usd+"equal to INR="+inr);
}
public void rupeetodollar()
{
System.out.println("Enter Rupee to convert into Dollars:");
inr=in.nextInt();
usd=inr/67;
System.out.println("Rupee ="+inr+"equal to Dollars="+usd);
}
public void eurotorupee()
{
System.out.println("Enter euro to convert into Rupees:");
euro=in.nextInt();
inr=euro*79.50;
System.out.println("Euro ="+euro +"equal to INR="+inr);
}
public void rupeetoeuro()
{
System.out.println("Enter Rupees to convert into Euro:");
inr=in.nextInt();
euro=(inr/79.50);
System.out.println("Rupee ="+inr +"equal to Euro="+euro);
}
public void yentorupee()
{
System.out.println("Enter yen to convert into Rupees:");
yen=in.nextInt();
inr=yen*0.61;
System.out.println("YEN="+yen +"equal to INR="+inr);
}
public void rupeetoyen()
{
System.out.println("Enter Rupees to convert into Yen:");
inr=in.nextInt();
yen=(inr/0.61);
System.out.println("INR="+inr +"equal to YEN"+yen);
}
}
class Converter
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int choice,ch;
CurrencyDemo c=new CurrencyDemo();
do
{
System.out.println("1.dollar to rupee ");
System.out.println("2.rupee to dollar ");
System.out.println("3.Euro to rupee ");
System.out.println("4..rupee to Euro ");
System.out.println("5.Yen to rupee ");
System.out.println("6.Rupee to Yen ");
System.out.println("Enter ur choice");
choice=s.nextInt();
switch(choice)
{
case 1:
{
c.dollartorupee();
break;
}
case 2:
{
c.rupeetodollar();
break;
}
case 3:
{
c.eurotorupee();
break;
}
case 4:
{
c.rupeetoeuro();
break;
}
case 5:
{
c.yentorupee();
break;
}
case 6 :
{
c.rupeetoyen();
break;
}

}
System.out.println("Enter 0 to quit and 1 to continue ");
ch=s.nextInt();
}while(ch==1);
}
}
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.

IMPLEMENTATION

import java.util.Scanner;

public class Duplicate


{

public static void main(String[] args)


{
int a[]={0,0,0,0,0},t,i,j,s=0,r=0;
Scanner z=new Scanner(System.in);
System.out.println("Enter 5 unique values between 10 & 100 ");
for(j=0;j<5;j++)
{
t=z.nextInt();
if(t>=10&&t<=100)
{
for(i=0;i<r;i++)
{
if(a[i]==t)
{
s++;
}
}
if(s>0)
{
System.out.println("Duplicate value found retry");
s--;
j--;
continue;
}
else
{
a[j]=t;
r++;
}
}
else
{
System.out.println("value must be in between 10 & 100");
j--;
}
}
System.out.print("The five unique values are ");
for(i=0;i<5;i++)
{
System.out.print(a[i]+" ");
}

Output:-
Enter 5 unique values between 10 & 100
0
value must be in between 10 & 100
10
20
10
Duplicate value found retry
30
40
50
The five unique values are 10 20 30 40 50
Week-3
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.

IMPLEMENTATION

abstract class shape


{
int a=3,b=4;
abstract public void print_area();
}
class rectangle extends shape
{
public int area_rect;
@Override
public void print_area()
{
area_rect=a*b;
System.out.println("The area of

rectangle is:"+area_rect);
}

}
class triangle extends shape
{
int area_tri;
@Override
public void print_area()
{
area_tri=(int) (0.5*a*b);
System.out.println("The area of

triangle is:"+area_tri);
}
}

class circle extends shape


{
int area_circle;
@Override
public void print_area()
{
area_circle=(int) (3.14*a*a);
System.out.println("The area of

circle is:"+area_circle);
}
}
public class JavaApplication3 {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {

rectangle r=new rectangle();


r.print_area();
triangle t=new triangle();
t.print_area();
circle r1=new circle();
r1.print_area();

// TODO code application logic here


// TODO code application logic here

}
/*Output:
run:
The area of rectangle is:12
The area of triangle is:6
The area of circle is:28
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.

IMPLEMENTATION
import java.util.*;
import java.text.*;
class Tokenizer
{
static int[] cal(String y)
{
String a,b,x=":";
int i[] = {0,0};
StringTokenizer st=new StringTokenizer(y,x);
a=(String) st.nextElement();
b=(String) st.nextElement();
i[0]=Integer.parseInt(a);
i[1]=Integer.parseInt(b);
return i;
}
}
public class GetCurrentDateTime
{
public static void main(String[] args) {

DateFormat dateFormat = new SimpleDateFormat("HH:mm");


Calendar cal = Calendar.getInstance();
String y=dateFormat.format(cal.getTime());

while(true)
{

String x,t1,a,b;int minute,hour;


int HH[]={0,0},MM[]={0,0};
t1=dateFormat.format(cal.getTime());
int time1[]=Tokenizer.cal(t1);
hour=time1[0];
minute=time1[1];
System.out.println("Enter the time intervels in HH MM fommat");
Scanner z=new Scanner(System.in);
String t2=z.next();
String t3=z.next();
int time2[]=Tokenizer.cal(t2);
HH[0]=time2[0];
MM[0]=time2[1];
int time3[]=Tokenizer.cal(t3);
HH[1]=time3[0];
MM[1]=time3[1];
if(HH[0]>HH[1])
{
int t=HH[0];
HH[0]=HH[1];
HH[1]=t;
}
if(HH[0]==HH[1]&&MM[0]>MM[1])
{
int t=MM[0];
MM[0]=MM[1];
MM[1]=t;
}

if((hour>=HH[0]&&hour<HH[1])||
(hour==HH[0]&&hour==HH[1])&&(minute>=MM[0]&&minute<=MM[1]))
{
System.out.println("Current time is "+hour+" : "+minute);
break;
}
else
{
System.out.println("Try again");
}

}
}
}
Week-4
a. Write a Java program to implement user defined exception handling.

IMPLEMENTATION

class JavaException{

public static void main(String args[]){

try{

throw new MyException(2);

// throw is used to create a new exception and throw it.

catch(MyException e){

System.out.println(e) ;

class MyException extends Exception{

int a;

MyException(int b) {

a=b;

public String toString(){

return ("Exception Number = "+a) ;

}
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.

IMPLEMENTATION

import java.awt.*;

import javax.swing.*;

import java.applet.Applet;

import java.awt.event.*;

public class Division extends Applet implements ActionListener{

TextField t1,t2,t3;

Button b;

Label L1,L2,L3,L4;

String s;

Division e;

public void init()

e=this;

t1=new TextField(10);

t2=new TextField(10);

t3=new TextField(10);

L1=new Label("enter num1");

L2=new Label("enter num2");


L3=new Label("Result is");

L4=new Label("Division of 2 numbers");

b=new Button("Divide");

add(L4);

add(L1);

add(t1);

add(L2);

add(t2);

add(L3);

add(t3);

add(b);

b.addActionListener(this);

public void actionPerformed(ActionEvent ae)

try

int num1=Integer.parseInt(t1.getText());

int num2=Integer.parseInt(t2.getText());

s=""+(num1/num2);

t3.setText(s);

catch(ArithmeticException a)

JOptionPane.showMessageDialog(null,"Divide by zero");

catch(NumberFormatException b)
{

JOptionPane.showMessageDialog(null,"NumberFormateException");

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.

IMPLEMENTATION

class A extends Thread


{
synchronized public void run()
{
try
{
while(true)
{
sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{ }
}
}
class B extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{ }
}
}
class C extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{ }
}
}
class ThreadDemo
{
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.

IMPLEMENTATION

import java.io.*;

import java.util.Scanner;

public class Split {

public static void main(String args[])

try{

// Reading file and getting no. of files to be generated

String inputfile = "D:\\test.txt"; // Source File Name.

double nol = 2000.0; // No. of lines to be split and saved in each output file.

File file = new File(inputfile);

Scanner scanner = new Scanner(file);

int count = 0;

while (scanner.hasNextLine())

scanner.nextLine();
count++;

System.out.println("Lines in the file: " + count); // Displays no. of lines in the input file.

double temp = (count/nol);

int temp1=(int)temp;

int nof=0;

if(temp1==temp)

nof=temp1;

else

nof=temp1+1;

System.out.println("No. of files to be generated :"+nof);

// Displays no. of files to be generated.

//---------------------------------------------------------------------------------------------------------

// Actual splitting of file into smaller files

FileInputStream fstream = new FileInputStream(inputfile);

DataInputStream in = new DataInputStream(fstream);

BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine;

for (int j=1;j<=nof;j++)

FileWriter fstream1 = new FileWriter("C:/New Folder/File"+j+".txt"); // Destination File


Location

BufferedWriter out = new BufferedWriter(fstream1);

for (int i=1;i<=nol;i++)


{

strLine = br.readLine();

if (strLine!= null)

out.write(strLine);

if(i!=nol)

out.newLine();

out.close();

in.close();

}catch (Exception e)

System.err.println("Error: " + e.getMessage());

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

Week-7
a. Write a java program that displays the number of characters, lines and words in a
text file.

IMPLEMENTATION

import java.util.*;

import java.io.*;

class Cfile
{

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:

Enter File name: raj.txt

Number of lines : 3

Number of words : 3

Number of characters : 26

b. Write a java program that reads a file and displays the file on the screen with line number
before each line

IMPLEMENTATION

import java.util.*;
import java.io.*;
class Rfile
{
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: raj.txt

Contents of the file are :

1: kotireddy
2: Santhosh

3: Vamsi

Week-8
a. Write a Java program that correctly implements producer consumer
problem using the concept of inter thread communication.
IMPLEMENTATION

class Q

int n;

boolean valueSet=false;
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();

catch(InterruptedException e)

System.out.println("Interrupted Exception caught");

}
this.n=n;

valueSet=true;

System.out.println("Put:"+n);

notify();

class Producer implements Runnable

Q q;

Producer(Q q)

this.q=q;

new Thread(this,"Producer").start();

public void run()

int i=0;

while(true)

q.put(i++);

class Consumer implements Runnable

Q q;

Consumer(Q q)
{

this.q=q;

new Thread(this,"Consumer").start();

public void run()

while(true)

q.get();

class ProdCons

public static void main(String[] args)

Q q=new Q();

new Producer(q);

new Consumer(q);

System.out.println("Press Control-c to stop");

b. Develop a Java application for stack operation using Buttons and JOptionPane
input and Message dialog box.

import java.util.*;
import javax.swing.*;

public class Calculator


{
public static void main(String[] arg)
{
String input1,input2,operator;
Double operand1,operand2;

input1 = JOptionPane.showInputDialog("Enter 1st Value");


operator = JOptionPane.showInputDialog("Enter Operator(+,-,*,%./)");
input2 = JOptionPane.showInputDialog("Enter 2nd Value");

operand1=Double.parseDouble(input1);
operand2=Double.parseDouble(input2);

double result=0.0;
if (operator.equals("+"))
result = operand1+operand2;
else if(operator.equals("-"))
result = operand1-operand2;
else if(operator.equals("*"))
result = operand1*operand2;
else if(operator.equals("/"))
result = operand1/operand2;
else if(operator.equals("%"))
result = operand1%operand2;
else
JOptionPane.showMessageDialog(null, "Inappropriate Input");

JOptionPane.showMessageDialog(null,"Your results are " + result);


}

// TODO Auto-generated method stub

private static double operand2(double result) {


// TODO Auto-generated method stub
return 0;
}
}
Week-9

A. Develop a Java application for the blinking eyes and mouth should open while blinking.

IMPLEMENTATION

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;

public class A extends Applet {

private static final long serialVersionUID = -1152278362796573663L;

public class MyCanvas extends Canvas {

private static final long serialVersionUID = -4372759074220420333L;


private int flag = 0;

public void paint(Graphics g) {

draw();

public void draw() {

Graphics g = this.getGraphics();

g.setColor(Color.BLACK);

super.paint(g);

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>

* */

public class TrafficLightsExample extends Applet implements ItemListener{

CheckboxGroup grp = new CheckboxGroup();

Checkbox redLight, yellowLight, greenLight;

Label msg;

public void init(){

redLight = new Checkbox("Red", grp, false);


yellowLight = new Checkbox("Yellow", grp, false);

greenLight = new Checkbox("Green", grp, false);

msg = new Label("");

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

}
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.

IMPLEMENTATION

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.

// <applet code="Rottenapplet.class" height=300 width=300></applet>

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
public class rottenapplet extends JApplet implements ActionListener
{
JPanel mainpanel=new JPanel(new GridLayout (3,1));
JPanel p1=new JPanel(new FlowLayout(0));
JPanel p2=new JPanel(new FlowLayout (0));
JPanel p3=new JPanel(new FlowLayout ());
JTextField q1=new JTextField (10);
JTextField q2=new JTextField (10);
JButton clickbutton = new JButton("convert");
public void init()
{
getContentPane().add(mainpanel);
mainpanel.add(p1);
mainpanel.add(p2);
mainpanel.add(p3);
p1.add(new JLabel("Insert Decimal:"));
p1.add(q1);
p2.add(clickbutton);
p3.add(new JLabel("Decimal to Binary:"));
p3.add(q2);
clickbutton.addActionListener(this);
}
public void actionPerformed(ActionEvent x)
{
if(x.getSource()==clickbutton)
{
int counter,dec,user;
user=Integer.valueOf(q1.getText()).intValue();
String[]conversion=new String[8];
String[]complete=new String[4];
counter=0;
complete[0]="";
do
{
dec=user%2;
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.

Week-12
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.awt.event.*;
import java.applet.*;
/* <applet code="Cal" width=300 height=300>
</applet>*/
public class Cal extends Applet
implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else
if(str.equals("add"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else
if(str.equals("sub"))
{
v1=Integer.parseInt(t1.getText());
OP='-';

t1.setText("");
}
else
if(str.equals("mul"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else
if(str.equals("div"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("EQ"))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else
if(OP=='-')
result=v1-v2;
else
if(OP=='*')
result=v1*v2;
else
if(OP=='/')
result=v1/v2;
else
if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}
}
c. Develop a Java application for handling mouse events.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Mouse" width=500 height=500>
</applet>
*/
public class Mouse 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);

}
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.*;

Class StudentForm extends JFrame


{

JLable l1,l2,l3,l4,l5,l6,l7;

JTextField t1,t2,t3,t4,t5,t6,t7;

JButton b1,b2;

Connection con;

PreparedStatement insert;

PreparedStatement update;

PreparedStatement delet;

PreparedStatement select;

StudentForm()

setSize(355,300);
setLocation(100,100);

Container c=getContentPane();

Title=new JLabel(“Student Details”);

Title.setFont(new Font(“Dialog”,Font.BOLD,15));

l1=new JLable(“Register No”);

l2=new JLable(“Student Name”);

l3=new JLable(“Marks1”);

l4=new JLable(“Marks2”);

l5=new JLable(“Marks3”);
t1=new JTextField(10);

t2=new JTextField(10);

t3=new JTextField(10);

t4=new JTextField(10);

t5=new JTextField(10);

b1=new JButton(“Insert”);

b2=new JButton(“Display”);

c.setLayout(null);

title.setBounds(60,10,160,20);
c.add(title);

l1.setBounds(40,40,50,20);

c.add(l1);

t1.setBounds(95,40,108,20);

c.add(t1);

l2.setBounds(40,70,50,20);

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

You might also like