Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
55 views

Java Lab

The document contains code for several Java programs: 1) A program to find prime numbers between 1 to n using nested for loops. 2) A program to solve quadratic equations using the quadratic formula and print real or imaginary solutions. 3) A program to generate electricity bills by calculating amounts due based on consumption tier and customer type (domestic or commercial). 4) A program to multiply two matrices by iterating through the rows and columns and summing the products of corresponding elements.

Uploaded by

kuruvakavyapriya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Java Lab

The document contains code for several Java programs: 1) A program to find prime numbers between 1 to n using nested for loops. 2) A program to solve quadratic equations using the quadratic formula and print real or imaginary solutions. 3) A program to generate electricity bills by calculating amounts due based on consumption tier and customer type (domestic or commercial). 4) A program to multiply two matrices by iterating through the rows and columns and summing the products of corresponding elements.

Uploaded by

kuruvakavyapriya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

Java program to find prime numbers between 1 to n.


1) We are finding the prime numbers within the limit.
2) Read the “n” value using scanner object sc.nextInt()and store it in the variable n.
3) The for loop iterates from j=2 to j=given number. then count assigned to 0, the inner loop finds the divisors of each j
value, count value represents no.of divisors. If count=2, then that number is a prime number.

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;

public class Quadratic {


public static void main(String[] args)
{

Prepared by: Priyanka PM.Tech., Asst. Professor Page 1


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 2


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 3


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 4


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

}
class ElectBillGen
{
public static void main (String[] args)
{
ElectBill b=new ElectBill();
b.input_data();
b.calculate_bill();
b.display();
}
}

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


// Java program to multiply two matrices.

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 5


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

static void readMatrix(int M[][],int rowSize,int colSize)


{
Scanner s = new Scanner(System.in);

System.out.println("Enter Matrix Elements: ");


for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++)
M[i][j]=s.nextInt();

System.out.println();
}
}
static void multiplyMatrix( int row1, int col2, int row2,int A[][],int B[][],int C[][])
{
int i, j, k;

for (i = 0; i < row1; i++) {


for (j = 0; j < col2; j++) {
for (k = 0; k < row2; k++)
C[i][j] += A[i][k] * B[k][j];
}
}
}

public static void main(String[] args)


{
int row1,col1,row2,col2;
Scanner s = new Scanner(System.in);

System.out.println("\nEnter First Matrix row size: ");


row1 = s.nextInt();
System.out.println("\nEnter First Matrix col size: ");
col1 = s.nextInt();

System.out.println("\nEnter Second Matrix row size: ");


row2 = s.nextInt();
System.out.println("\nEnter Second Matrix col size: ");
col2 = s.nextInt();
if (row2 != col1) {
System.out.println( "\nMatrix Multiplication is Not Possible");
return;
}
int A[][] = new int[row1][col1];
int B[][] = new int[row2][col2];

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

int C[][] = new int[row1][col2];


multiplyMatrix(row1, col2, row2, A,B,C);

// Print the result


System.out.println("\nResultant Matrix:");
printMatrix(C, row1, col2);
}
}

Prepared by: Priyanka PM.Tech., Asst. Professor Page 7


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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:

Prepared by: Priyanka PM.Tech., Asst. Professor Page 8


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

i+j+k: 24

2 b) Write a java program to prevent inheritance using final keyword.


class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
public class PreventInheritance {
public static void main(String a[])
{
A a1=new A();
B b1=new B();
a1.meth();
b1.meth();
}
}
Output: Compilation error.

2 c) Write a java program to demonstrate abstract methods and classes.


abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {

Prepared by: Priyanka PM.Tech., Asst. Professor Page 9


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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.

Write a java program to demonstrate Dynamic binding.


class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");

Prepared by: Priyanka PM.Tech., Asst. Professor Page 10


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Write a java program to demonstrate method overloading concept.


// Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// Overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;

Prepared by: Priyanka PM.Tech., Asst. Professor Page 11


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

// call all versions of test()


ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}

Output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625

Write a java program to demonstrate method Overriding concept.


class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
/*

Prepared by: Priyanka PM.Tech., Asst. Professor Page 12


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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;

Prepared by: Priyanka PM.Tech., Asst. Professor Page 13


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

System.out.println("Enter your choice: ");


choice = input.nextInt();
System.out.println("Please enter the current exchange rate: ");
CurrentExchange = input.nextDouble();
CurrencyClass cc=new CurrencyClass(CurrentExchange);
switch(choice)
{
case 1:
System.out.print("Enter Dollars :");
double dollar=input.nextDouble();

Prepared by: Priyanka PM.Tech., Asst. Professor Page 14


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

System.out.println (dollar+" dollars are converted to


"+cc.DollarToINR(dollar)+" Rs.");
break;
case 2:
System.out.print("Enter INR :");
inr=input.nextDouble();
System.out.println(inr+" Rs. are converted to
"+cc.INRToDollar(inr)+" Dollars");
break;
case 3:
System.out.print("Enter Euro :");
double euro=input.nextDouble();
System.out.println(euro+" Euros are converted to
"+cc.EuroToINR(euro)+" Rs.");
break;
case 4:
System.out.print("Enter INR :");
inr=input.nextDouble();
System.out.println(inr+" Rs. are converted to "+cc.INRToEuro(inr)
+" Euros");
break;
case 5:
System.out.print("Enter Yen :");
double yen=input.nextDouble();
System.out.println(yen+" Yens are converted to
"+cc.YenToINR(yen)+" Rs.");
break;
case 6:
System.out.print("Enter INR :");
inr=input.nextDouble();
System.out.println(inr+" Rs. are converted to "+cc.INRToYen(inr)
+" Yens");
break;
default:
System.out.println("Wrong choice, Try again...");
}
System.out.println("Do You want to go to Currency Conversion Menu?
(y/n) ");
ans = input.next().charAt(0);
}while(ans=='y');
}
}

Prepared by: Priyanka PM.Tech., Asst. Professor Page 15


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

Prepared by: Priyanka PM.Tech., Asst. Professor Page 16


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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;

public class week3b


{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sid[] = new int[5];

int count = 0;
int x = 0;
int num = 0;

while (x < sid.length)


{
System.out.println(“Enter number: “);
num = input.nextInt();

if ((num >= 10) && (num <= 100))


{

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


{ if (sid[i] == num)
digit = true;
}

if (!digit)
{

System.out.println(“the number is” + num);


sid[count] = num;
count++;
x++;
}
else
System.out.printf(“The entered number already exist, Try again.. \n”);
}
else
System.out.println(“number must be between 10 and 100, Try again..”);

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 17


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

abstract class Shape {


double dim1;
double dim2;
Shape(double a, double b) {
dim1 = a;
dim2 = b;
}
abstract double printArea();
}
class Rectangle extends Shape {
Rectangle(double l, double b) {
super(l, b);

Prepared by: Priyanka PM.Tech., Asst. Professor Page 18


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Shape ref; // this is OK, no object is created


ref = r;
System.out.println("Area is " + ref.printArea());
ref = t;
System.out.println("Area is " + ref.printArea());
ref = c;
System.out.println("Area is " + ref.printArea());
}
}

Prepared by: Priyanka PM.Tech., Asst. Professor Page 19


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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;

public class week3c {

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


// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int cnt;

do{
System.out.println(“Enter User Time in hh:hh format:- “);
String mytime = br.readLine();

System.out.println(“User Entered Time: “+mytime);

DateFormat df = new SimpleDateFormat(“hh:mm”);


Date date = new Date();
String systime = df.format(date);

System.out.println(“System Time: “+systime);

StringTokenizer st1 = new StringTokenizer(mytime,”:”);


StringTokenizer st2 = new StringTokenizer(systime,”:”);
cnt=0;
while(st1.hasMoreTokens() && st2.hasMoreTokens())
{
int n1 = Integer.parseInt(st1.nextToken());
int n2 = Integer.parseInt(st2.nextToken());

if(n1 == n2)

Prepared by: Priyanka PM.Tech., Asst. Professor Page 20


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

{
cnt++;
}
else
{
System.out.println(“Given time is out of the range, Try
Again...”);
break;
}
}
}while(cnt < 2);

System.out.println(“Given time is within the range”);


}
}

Prepared by: Priyanka PM.Tech., Asst. Professor Page 21


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

b) Write a java program to create user-defined exception class.


class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";

Prepared by: Priyanka PM.Tech., Asst. Professor Page 22


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

public class week3b


{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sid[] = new int[5];

int count = 0;
int x = 0;
int num = 0;

while (x < sid.length)


{
System.out.println(“Enter number: “);
num = input.nextInt();

Prepared by: Priyanka PM.Tech., Asst. Professor Page 23


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

if ((num >= 10) && (num <= 100))


{

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


{ if (sid[i] == num)
digit = true;
}

if (!digit)
{

System.out.println(“the number is” + num);


sid[count] = num;
count++;
x++;
}
else
System.out.printf(“The entered number already exist, Try again.. \n”);
}
else
System.out.println(“number must be between 10 and 100, Try again..”);

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


{
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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 24


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

Duplicate value
enter 5 integers between 10 and 100
55
The elements are: 12
33
55

Prepared by: Priyanka PM.Tech., Asst. Professor Page 25


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

/*<applet code=”week5a” width=500 height=500>


</applet>*/

public class week5a extends Applet implements ActionListener {


String msg;
TextField num1,num2,res;Label l1,l2,l3;
Button div;
public void init()
{
l1=new Label(“Number 1”);
l2=new Label(“Number 2”);
l3=new Label(“result”);
num1=new TextField(10);
num2=new TextField(10);
res=new TextField(10);
div=new Button(“DIV”);
div.addActionListener(this);
add(l1);
add(num1);
add(l2);
add(num2);
add(l3);
add(res);
add(div);
}
public void actionPerformed(ActionEvent ae)
{
String arg=ae.getActionCommand();
if(arg.equals(“DIV”))
{
String s1=num1.getText();
String s2=num2.getText();
int num1=Integer.parseInt(s1);
int num2=Integer.parseInt(s2);
if(num2==0)

Prepared by: Priyanka PM.Tech., Asst. Professor Page 26


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

class A extends Thread


{
synchronized public void run()
{
try
{

Prepared by: Priyanka PM.Tech., Asst. Professor Page 27


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 28


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

C t3=new C();

t1.start();
t2.start();
t3.start();
}
}

Prepared by: Priyanka PM.Tech., Asst. Professor Page 29


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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 sizeOfFiles =(int)fsize/n;


byte[] buffer = new byte[sizeOfFiles];

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));


String name = f.getName();

int tmp = 0;
while ((tmp = bis.read(buffer)) > 0) {

File newFile = new File(f.getParent(), name + “.” + “part”+String.format(“%03d”, partCounter+


+));

FileOutputStream out = new FileOutputStream(newFile);


out.write(buffer, 0, tmp);
out.close();

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.

Prepared by: Priyanka PM.Tech., Asst. Professor Page 30


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

File exists: true


File is readable: true
File is writable: true
Is a directory: false
length of the file: 20 bytes

Prepared by: Priyanka PM.Tech., Asst. Professor Page 31


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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:

Enter File name: temp.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.

/Program to print the contents of the file along with line number
import java.util.*;
import java.io.*;
class week7b

Prepared by: Priyanka PM.Tech., Asst. Professor Page 32


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

{
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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 33


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 34


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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 Week18
{
public static void main(String[] args)
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-c to stop");
}
}

Output:
Put:0

Prepared by: Priyanka PM.Tech., Asst. Professor Page 35


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

Press Control-c to stop


Got:0
enter data
65
Put:65
Got:65
enter data
33
Put:33
Got:33
enter data
8
Put:8
Got:8

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

import javax.swing.JOptionPane;

public class week8b


{
public static void main (String args [])
{
Stack s = new Stack ();
String choice;
bVinodn done = false;

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:

Prepared by: Priyanka PM.Tech., Asst. Professor Page 36


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

JOptionPane.showMessageDialog(null, "The value peeked at is " + s.peek());


break;
case 4:
if (s.empty()) {
JOptionPane.showMessageDialog(null, "The stack is empty.");
}
else {
JOptionPane.showMessageDialog(null, "The stack is not empty.");
}
break;
case 5:
JOptionPane.showMessageDialog(null, s.printStack());
break;
case 6:
JOptionPane.showMessageDialog(null, "...exiting");
done = true;
break;
default:
JOptionPane.showMessageDialog(null, "You entered an invalid choice. \n"
+ "Please try again!");
}
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(
null,
"You must type an integer. Please Try again!");
}

}
}
}

c. Develop a Java application to perform Addition, Division, Multiplication and substraction


using JOption Pane dialog Box and Text fields.

import java.util.Scanner;
import javax.swing.JoptionPane;

public class week8c


{
public static void main(String [] args)
{
Scanner norbel = new Scanner(System.in);

int answer;

String Fnumber = JoptionPane.showInputDialog(“Enter first Integer: “);


int fnum = Integer.parseInt(Fnumber);

Prepared by: Priyanka PM.Tech., Asst. Professor Page 37


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 38


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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;

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 {

Prepared by: Priyanka PM.Tech., Asst. Professor Page 39


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 40


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 41


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 42


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

}
}

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="week10bapplet.class" height=300 width=300></applet>


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
public class week10bapplet 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;

Prepared by: Priyanka PM.Tech., Asst. Professor Page 43


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 44


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 45


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

b. Develop a Java application to demonstrate the key event handlers.

Prepared by: Priyanka PM.Tech., Asst. Professor Page 46


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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:

Prepared by: Priyanka PM.Tech., Asst. Professor Page 47


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

Week-12
a. Develop a Java application to find the maximum value from the given type of elements
using a generic function.

public class MainClass {


// determines the largest of three Comparable objects
public static <T extends Comparable<T>> T maximum(T x, T y, T z) {
T max = x; // assume x is initially the largest

if (y.compareTo(max) > 0)
max = y; // y is the largest so far

if (z.compareTo(max) > 0)
max = z; // z is the largest

return max; // returns the largest object


} // end method maximum

public static void main(String args[]) {


System.out.printf("Maximum of %d, %d and %d is %d\n\n", 3, 4, 5, maximum(3, 4, 5));
System.out.printf("Maximum of %.1f, %.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7,
maximum(6.6, 8.8, 7.7));
System.out.printf("Maximum of %s, %s and %s is %s\n", "pear", "apple", "orange",
maximum(
"pear", "apple", "orange"));
}
}
OUTPUT
Maximum of 3, 4 and 5 is 5

Maximum of 6.6, 8.8 and 7.7 is 8.8

Maximum of pear, apple and orange is pear

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 48


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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:

c. Develop a Java application for handling mouse events.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="Week11b" width=500 height=500></applet> */
public class Week13 extends Applet

Prepared by: Priyanka PM.Tech., Asst. Professor Page 51


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 52


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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:

Prepared by: Priyanka PM.Tech., Asst. Professor Page 53


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 54


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 55


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 56


20A05303P OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

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

Prepared by: Priyanka PM.Tech., Asst. Professor Page 57

You might also like