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

Java Record Programs

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

Java Record Programs

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

JAVA LAB RECORD

AY 2024-25 Sem-1

1. Write a program to print prime numbers within range

2. Write a program to find min, max and average of array elements read from

the user dynamically.

3. Write a program to implement matrix multiplication.

4. Write a Program to demonstrate jagged arrays.

5. Write a Program to read n numbers and display them in sorted order.

6. Write a program to demonstrate bitwise operators

7. Program to demonstrate type casting.

8. Create a class Student with attributes such as name,rollnumber, and marks.

9. Write a program to create five student objects and display details as a

report.

10. Write a program to demonstrate method overloading.

11. Program to demonstrate Product class to implement Constructor

overloading

12. Write a program to implement Single Inheritance with super keyword.

13. Write a program to demonstrate Hierarchical inheritance. 14. Write a

program to demonstrate MultiLevel Inheritance.

15. Write a program to implement Run time Polymorphism usingDynamic

MethodDispatch(DMD)concept.

16. Program to demonstrate Abstract class.

17. Program to implement multiple inheritance using interfaces. Create an


ArrayStack class which implements Arr (disp() method) and Stack (push()

and pop() methods) interfaces.

18. Program to implement user defined package

19.Write a program to handle any two predefined exceptions using try catch

blocks.

20. Write a program to demonstrate user defined exception (AgeException)

21. Write a program to create three user threads by implementing Runnable

interface.

22. Write a Program to create Two threads by extending thread class. (One

thread finding the square of given array, other thread converts every character

of string to uppercase)

23. Write a Java program that correctly implements producer consumer

problem using the concept of inter thread communication.

24. Develop an AWT program to demonstrate List control with Event Handling.

25. Develop an AWT program to demonstrate Radio buttons with Event

handling.

26. Write a program to demonstrate Adapter classes

27. Write an AWT program to implement a simple calculator with two TextFields,

four Buttons (named Add, Sub, Mul, Div) and a Label to display result. Use

ActionListener to handle events.

28. Program to demonstrate Mouse Events & Key events.

29. Write a Java program to illustrate collection classes like Array List,

LinkedList, TreeMap and HashMap.

30. Write a Java program to implement iteration over Collection using Iterator
interface and Listlterator interface.

31. Write a Java program that reads a file name from the user, and then

displays information about whether the file exists, whether the file is readable,

whether the file is writable, the type of file and the length of the file in bytes. 32.

Write a Java program to implement serialization concept 33. Write a Java

program to perform following CRUD operations on student data using JDBC.

i. create & insert a student record

ii. retrieve and display the existing student records

iii. update & delete a student record


Java Lab Record
AY 2023-24 Sem-2
________________________________________________________________________

1. Write a program to print prime numbers within range

public class PrimeNumbersInRange {


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

System.out.print("Enter the lower bound (x): ");


int x = scanner.nextInt();

System.out.print("Enter the upper bound (y): ");


int y = scanner.nextInt();

System.out.println("Prime numbers between " + x + " and " + y +


":"); for (int num = x; num <= y; num++) {
boolean isPrime = true;

for (int i = 2; i <= num/2; i++) {


if (num % i == 0) {
isPrime = false;
break;
}
}

if (isPrime)
System.out.println(num);
}
}
}

2. Write a program to find min, max and average of array elements read
from the user dynamically.

import java.util.*;
class GroupOper
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
System.out.println("enter the number of elements");
int n= sc.nextInt();
int min=32767, max=-32768;
int sum=0;
int avg=0;
for(int i=0;i<n;i++)
{
System.out.println("enter element:"+(i+1));
int a = sc.nextInt();
if(a<min)
min=a;
if(a>max)
max=a;
sum+=a;
avg=avg+(sum/n);
}
System.out.println("MAX value :"+max);
System.out.println("MIN value:"+min);
System.out.println("SUM=" +sum);
System.out.println("AVG=" +avg);

}
}

3. Write a program to implement matrix multiplication.

import java.util.Scanner;

public class MatrixMultiplication {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read dimensions and elements of the first matrix


System.out.println("Enter the number of rows and columns of the
first matrix:");
int rowsA = scanner.nextInt();
int colsA = scanner.nextInt();
int[][] matrixA = new int[rowsA][colsA];
System.out.println("Enter the elements of the first matrix:");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsA; j++) {
matrixA[i][j] = scanner.nextInt();
}
}

// Read dimensions and elements of the second matrix


System.out.println("Enter the number of rows and columns of the second
matrix:");
int rowsB = scanner.nextInt();
int colsB = scanner.nextInt();
if (colsA != rowsB) {
System.out.println("Matrices cannot be multiplied due to incompatible
dimensions.");
return;
}
int[][] matrixB = new int[rowsB][colsB];
System.out.println("Enter the elements of the second
matrix:"); for (int i = 0; i < rowsB; i++) {
for (int j = 0; j < colsB; j++) {
matrixB[i][j] = scanner.nextInt();
}
}

// Perform the multiplication


int[][] result = multiplyMatrices(matrixA, matrixB);

// Print the result


System.out.println("Resultant Matrix:");
printMatrix(result);
}

public static int[][] multiplyMatrices(int[][] firstMatrix, int[][] secondMatrix) {


int r1 = firstMatrix.length;
int c1 = firstMatrix[0].length;
int c2 = secondMatrix[0].length;
int[][] result = new int[r1][c2];

for (int i = 0; i < r1; i++) {


for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
result[i][j] += firstMatrix[i][k] *
secondMatrix[k][j]; }
}
}

return result;
}

public static void printMatrix(int[][] matrix) {


for (int[] row : matrix) {
for (int col : row) {
System.out.print(col + " ");
}
System.out.println();
}
}
}
4. Write a Program to demonstrate jagged arrays.

import java.util.*;
class Array3
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int a[][]=new int[3][];
a[0]=new int[3];
a[1]=new int[2];
a[2]=new int[4];
System.out.println("enter elemnts");
for(int i=0; i<a.length;i++)
{

for(int j=0;j<a[i].length;j++)
{
a[i][j]= sc.nextInt();
}
}

System.out.println("elemnts are");
for(int i=0; i<a.length;i++)
{

for(int j=0;j<a[i].length;j++)
{

System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}
5. Write a Program to read n numbers and display them in sorted order.

import java.util.*;
class BubbleSort
{

public static void main(String args[])

Scanner sc= new Scanner(System.in);


System.out.println("enetr the size of the array");
int n=sc.nextInt();
int a[]=new int[n];
System.out.println("enter the elemnts");
for(int i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}

int temp=0;
for(int i=0;i<n;i++)
{
for(int j=1;j<(n-i);j++)
{
if(a[j-1]>a[j])
{
temp= a[j-1];
a[j-1]=a[j];
a[j]=temp;
}
}
}

System.out.println("After sorting");
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]+" ");
}
}
}

6. Write a program to demonstrate bitwise operators

import java.util.Scanner;

public class BitwiseOperatorsDemo {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read two integers from the user


System.out.println("Enter the first
integer:"); int num1 = scanner.nextInt();

System.out.println("Enter the second integer:");


int num2 = scanner.nextInt();

// Bitwise AND
int andResult = num1 & num2;
System.out.println("Bitwise AND of " + num1 + " and " + num2 + " is: " +
andResult);

// Bitwise OR
int orResult = num1 | num2;
System.out.println("Bitwise OR of " + num1 + " and " + num2 + " is: " +
orResult);

// Bitwise XOR
int xorResult = num1 ^ num2;
System.out.println("Bitwise XOR of " + num1 + " and " + num2 + " is: " +
xorResult);

// Bitwise NOT
int notResult1 = ~num1;
int notResult2 = ~num2;
System.out.println("Bitwise NOT of " + num1 + " is: " + notResult1);
System.out.println("Bitwise NOT of " + num2 + " is: " +
notResult2);

// Left Shift
int leftShiftResult = num1 << 2;
System.out.println("Left Shift of " + num1 + " by 2 positions is: " +
leftShiftResult);

// Right Shift
int rightShiftResult = num1 >> 2;
System.out.println("Right Shift of " + num1 + " by 2 positions is: " +
rightShiftResult);

// Unsigned Right Shift


int unsignedRightShiftResult = num1 >>> 2;
System.out.println("Unsigned Right Shift of " + num1 + " by 2 positions is: " +
unsignedRightShiftResult);
}
}
7. Program to demonstrate type casting.

public class TypeCastingDemo {

public static void main(String[] args) {


// Implicit Casting (Widening Casting)
int intValue = 100;
double doubleValue = intValue; // int to double
System.out.println("Implicit Casting (int to
double):"); System.out.println("int value: " +
intValue);
System.out.println("double value: " + doubleValue);

// Explicit Casting (Narrowing Casting)


double largeDoubleValue = 100.99;
int narrowedIntValue = (int) largeDoubleValue; // double to
int System.out.println("\nExplicit Casting (double to int):");
System.out.println("double value: " + largeDoubleValue);
System.out.println("int value: " + narrowedIntValue);
// Casting char to int
char charValue = 'A';
int charToIntValue = (int) charValue; // char to int
System.out.println("\nCasting char to int:");
System.out.println("char value: " + charValue);
System.out.println("int value: " + charToIntValue);

// Casting int to char


int anotherIntValue = 66;
char intToCharValue = (char) anotherIntValue; // int to char
System.out.println("\nCasting int to char:");
System.out.println("int value: " + anotherIntValue);
System.out.println("char value: " + intToCharValue);

// Casting long to float


long longValue = 1000000000L;
float floatValue = longValue; // long to float (implicit)
System.out.println("\nImplicit Casting (long to
float):"); System.out.println("long value: " + longValue);
System.out.println("float value: " + floatValue);
// Explicit Casting from float to byte
float largeFloatValue = 123.45F;
byte byteValue = (byte) largeFloatValue; // float to byte
System.out.println("\nExplicit Casting (float to byte):");
System.out.println("float value: " + largeFloatValue);
System.out.println("byte value: " + byteValue);
}
}

8. Create a class Student with attributes such as name,rollnumber, and


marks.

import java.util.Scanner;
class Stu
{
String name;
int rno;
double per;
int marks[];

Stu(String a,int b,int c[])


{
name=a;
rno=b;
marks=c;
}

void calcper()
{
double sum=0;
for(int p:marks)
sum=sum+p;
per=sum/marks.length;
}

void disp()
{
calcper();
System.out.println("Student name:"+name);
System.out.println("Roll no:"+rno);
System.out.println("Percentage:"+per);
}

}
class TestStu2
{
public static void main(String[] args)
{
int m[]={76,66,75,85,88};
Stu x=new Stu("teststu",111,m);
x.disp();

}
}
9. Write a program to create five student objects and display details as a
report.
class Student {
String name;
int rno;
Student() {
name="abc";
rno=101;
}
void display() {
System.out.println("name is"+name);
System.out.println("roll no is"+rno);
}
}
class Constructor {
public static void main(String args[]) {
Student s1= new Student();
s1.display();
}
}
10. Write a program to demonstrate method overloading.

class MethodOverload {
void add(int a, int b) {
System.out.println("The sum of two numbers is:"+(a+b));
}
void add(int a[],int b[]) {
int c[]=new int[a.length];

for(int i=0;i<a.length;i++)
c[i]=a[i]+b[i];

System.out.println("The sum of arrays are:");


for(int x:c) System.out.print(x+" ");
}
}
class MethodOv
{
public static void main(String[] args)
{
MethodOverload x=new MethodOverload();
x.add(10,20);
x.add(new int[]{1,2,3},new int[]{4,5,6});
}
}

11. Program to demonstrate Product class to implement Constructor


overloading
class Product
{
int pid,qty;
String pname;
double price;

Product(int a,String b,double c,int d)


{
pid=a;
pname=b;
price=c;
qty=d;
}

Product()
{
pid=999;
pname="keyboard";
price=100;
qty=50;
}

void purchase(int x)
{
if(qty>=x)
{
double t=x*price;
qty=qty-x;
System.out.println("-----ITEM-----:"+pname);
System.out.println("YOUR BILL AMOUNT FOR QTY-"+x+" IS:"+t);
}
else
System.out.println("Purchase not possible..Available qty:"+qty);
}

}
class ProdTest
{
public static void main(String[] args)
{
Product p=new Product(1001,"pendrive",250,25);

p.purchase(10);
p.purchase(5);
p.purchase(20);
Product p1=new Product();
p1.purchase(5);
p1.purchase(20);

System.out.println("Thank you for using");


}
}

12. Write a program to implement Single Inheritance with super


keyword.
class Vehicle
{
String brand;
void disp()
{
System.out.println("brand="+brand);
}

Vehicle(String x)
{
brand=x;
}
}

class Car extends Vehicle


{
String model;
int cc;
Car(String a ,int b, String c)
{
super(a);
cc=b; model=c;
}
void dispcar()
{
disp();
System.out.println("capacity="+cc);
System.out.println("model="+model);
}
}

class SingleInh
{

public static void main(String args[])


{

Car x=new Car("Hyundai", 1000,"creta");


x.dispcar();
}
}
13. Write a program to demonstrate Hierarchical inheritance.

class Employee
{
String name;
int id;
float sal;
Employee(String n, int r, float s)
{
name=n;
id=r;
sal=s;
}

void empdet()
{
System.out.println("Name:"+name);
System.out.println("id is:"+id);
System.out.println("salary is:"+sal);
}
}

class Manager extends Employee


{
String dept;
Manager(String a,int b,float c, String d)
{

super(a,b,c);
dept=d;
}

void display()
{
System.out.println("Name:"+name);
System.out.println("id is:"+id);
System.out.println("salary is:"+sal);
System.out.println("department
is:"+dept); }
}

class Developer extends Employee


{
String proglang;

Developer(String a,int b,float c, String d)


{
super(a,b,c);
proglang=d;
}

void show()
{
System.out.println("Name:"+name);
System.out.println("id is:"+id);
System.out.println("salary is:"+sal);
System.out.println("programming lang
is:"+proglang); }
}

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

Employee emp= new Employee("Steve",101,20000);


Manager m= new Manager("Alice",102, 40000,”HR”);
Developer x= new Developer("Smith",103,
50000,"java"); System.out.println("Employee details
are:");
emp.empdet();
System.out.println("manager details are:");
m.display();
System.out.println("developer details are:");
x.show();
}
}

14. Write a program to demonstrate MultiLevel Inheritance.

class Person
{
String name;
int age;
Person(String a,int b)
{
name=a;
age=b;
}
void disp()
{
System.out.println("Name:"+name);
System.out.println("Age:"+age);
}
}
class Emp extends Person
{
double sal;
Emp(String a, int b, double c)
{
super(a,b);
sal=c;
}
void disp()
{
super.disp();
System.out.println("Salary:"+sal);
}
}
class Manager extends Emp
{
int teamsize;
Manager(String a, int b, double c,int d)
{
super(a,b,c);
teamsize=d;
}
void disp()
{
super.disp();
System.out.println("Teamsize:"+teamsize);
}
}
class MultiLevel
{
public static void main(String[] args)
{
Manager m=new Manager("Rajiv",43,120000,23);
m.disp();
}
}

15. Write a program to implement Run time Polymorphism


usingDynamic MethodDispatch(DMD)concept.

class Figure
{
double pi=3.14156;
void area()
{
System.out.println("Area is undefined");
}
}
class Circle extends Figure
{
double r=4.5;
//override area for Circle
void area()
{
System.out.println("The area of circle
is:"+pi*r*r); }
}
class Rectangle extends Figure
{
double l=4.5,b=7.8;
//override area for rectangle
void area()
{
System.out.println("The area of rectangle is:"+l*b);
}

}
class PolyEx
{
public static void main(String[] args)
{
Figure f=new Figure();

f.area();
f= new Circle();
f.area();

f=new Rectangle();
f.area();
}

}
16. Program to demonstrate Abstract
class. abstract class Figure
{
double pi=3.14156;
abstract void area();
void xyz()
{
System.out.println("other method");
}
}
class Circle extends Figure
{
double r=4.5;
//override area for Circle
void area()

{
System.out.println("The area of circle
is:"+pi*r*r); }
}
class Rectangle extends Figure
{
double l=4.5,b=7.8;
//override area for rectangle
void area()
{
System.out.println("The area of rectangle
is:"+l*b); }

}
class AbstractEx
{
public static void main(String[] args)
{
Figure f;

f= new Circle();
f.area();
f.xyz();

f=new Rectangle();
f.area();
}

17. Program to implement multiple inheritance using interfaces. Create


an ArrayStack class which implements Arr (disp() method) and Stack
(push() and pop() methods) interfaces.
interface Arr
{
void print();
}

interface MyStack
{
void push(int x);
int pop();
}
class StackArr implements Arr, MyStack
{
int st[];
int n,top;
StackArr()
{
n=5;
top=-1;
st=new int[n];
}
public void push(int x)
{
if(top==4)
{
System.out.println("Stack Full");
return;
}
else
st[++top]=x;
}
public int pop()
{
return st[top--];

}
public void print()
{
System.out.print("[");
for(int i=0;i<=top;i++)
System.out.print(st[i]+" ");
System.out.println("]");
}
}
class MultiInh
{
public static void main(String[] args)
{
StackArr ob=new StackArr();
System.out.println("Empty stack: " );
ob.print();
ob.push(10);
ob.push(20);
ob.push(30);
System.out.println("Contents of stack after push
operations"); ob.print();
System.out.println("popped element is "+ob.pop());
System.out.println("contents of Stack after pop operation:");
ob.print();
System.out.println("popped element is " +ob.pop());
System.out.println("Contents of stack after pop
operation:"); ob.print();

}
}

18. Program to implement user defined package


//Operations.java
package bnk;
import java.time.Year;
public class Operations
{
double roi;
int year;
public Operations()
{
roi=7.5;
year=Year.now().getValue();
}
public int getAge(int x)
{
return year-x;
}
public double getSimpleIntr(double amt,int t)
{
double val=(amt*t*roi)/100;
return val;
}
}

command to compile a package: javac - d . Operations.java

//BankTest.java

import bnk.Operations;
import java.util.Scanner;
class BankTest
{
public static void main(String[] args)
{
Operations x=new Operations();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the birth year:");
int yr=sc.nextInt();
System.out.println("Age="+x.getAge(yr));

System.out.println("Enter the Amount:");


double amt=sc.nextDouble();
System.out.println("Enter the Time period (in years):");
int t=sc.nextInt();
System.out.println("The Simple interest value on given
Amount="+x.getSimpleIntr(amt,t));
}
}
compile: javac BankTest.java

19.Write a program to handle any two predefined exceptions using try catch blocks.

class Excep5
{
public static void main(String args[])
{
int a[]={1,2,3};
int sum;
int c=20,d=0,x;
try
{
sum=0;
sum=a[0]+a[1]+a[2]+a[3];
System.out.println("The array sum is:"+sum);

}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index exceeded");
System.out.println(e);
}

System.out.println("---another try-catch block--------");


try
{
x=c/d;
System.out.println(x);
}
catch (ArithmeticException e)
{
System.out.println("Division problem");
System.out.println(e);
}
System.out.println("after catch block");
}
}
20. Write a program to demonstrate user defined exception
(AgeException)

import java.util.Scanner;
class AgeException extends Exception
{
AgeException(String desc)
{
super(desc);
}
}
class UserExc
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

try
{
System.out.println("enter age:");
int age=sc.nextInt();
if(age<18) throw new AgeException("Invalid age for Vaccination");
System.out.println("Your are eligible for COVID vaccination");
System.out.println("Vaccination Given");
}
catch (AgeException e)
{
System.out.println(e.getMessage());
}
}
}

21. Write a program to create three user threads by implementing


Runnable interface.

class Demo implements Runnable


{
Thread t;
Demo(String s)
{
t=new Thread(this,s);
}
public void run()
{
String s=t.getName();
for(int i=0;i<10;i++)
System.out.println(s+":"+i);
}
}
class UserThrRunnable
{
public static void main(String[] args)
{

Demo x=new Demo("Demo Thread");


x.t.start();

String s="Main";
for(int i=0;i<10;i++)
System.out.println(s+":"+i);
}
}

22. Write a Program to create Two threads by extending thread class. (One
thread finding the square of given array, other thread converts every
character of string to uppercase)

class Thr1 extends Thread


{
int a[];
Thr1(int x[])
{
a=x;
}
public void run()
{
for(int i=0;i<a.length;i++)
{
int r=a[i]*a[i];
System.out.println("The square of "+a[i]+" is:"+r);
try
{
Thread.sleep(10);
}
catch (Exception e)
{
}
}
}
}

class Thr2 extends Thread


{
String s;
Thr2(String x)
{
s=x;
}
public void run()
{
for(int i=0;i<s.length();i++)
{
String ch=""+s.charAt(i);
System.out.println("Character at position "+i+"
is:"+ch.toUpperCase());
try
{
Thread.sleep(10);
}
catch (Exception e)
{
}
}
}
}
class MultiTask
{
public static void main(String[] args) throws Exception
{
int x[]={45,66,123,456,76};
Thr1 t1=new Thr1(x);

String y="Welcome";
Thr2 t2=new Thr2(y);
t1.start();
t2.start();
System.out.println("Bye from main");
}
}

23. Write a Java program that correctly implements producer consumer


problem using the concept of inter thread communication.

class Resource {
int data=-1;
public synchronized void produce() throws InterruptedException {
if(data!=-1)
{
System.out.println("Producer is waiting");
wait();
}
System.out.println("Item Produced:200");
data=200;
notify(); // Notify the waiting thread that data is available
}

public synchronized void consume() throws InterruptedException {


if (data==-1) {
System.out.println("Consumer is waiting");
wait(); // Wait for data to be produced
}
System.out.println("Consumed data is:"+data);
data=-1;
notify();
}
}
class Producer extends Thread
{
Resource r;
Producer(Resource x)
{
r=x;
}
public void run()
{
try {
for(int i=0;i<10;i++)
r.produce();

} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Consumer extends Thread
{
Resource r;
Consumer(Resource x)
{
r=x;
}
public void run()
{
try {
for(int i=0;i<10;i++)

r.consume();

} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class WaitNotifyExample1 {
public static void main(String[] args) {
Resource s = new Resource();
Producer p=new Producer(s);
Consumer c=new Consumer(s);
p.start();
c.start();
}
}

24. Develop an AWT program to demonstrate List control with Event


Handling.

import java.awt.event.*;
import java.applet.*;
/*
<applet code="ListDemo" width=600 height=600>
</applet>
*/
public class ListDemo extends Applet implements ActionListener {
Label l;
List dm;
String msg = "";
public void init() {
Font f= new Font("Courier", Font.BOLD, 20);
setFont(f);
l=new Label("Select the hobbies:");
dm = new List(3,true);
dm.add("Watching TV");
dm.add("Reading ");
dm.add("Online games");
dm.add("Cricket");
dm.add("Music");
add(l);
add(dm);
dm.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
repaint();
}
// Display current selections.
public void paint(Graphics g) {
int v[];
msg = "Selected value(s): ";
v = dm.getSelectedIndexes();
for(int i=0; i<v.length; i++)
msg += dm.getItem(v[i]) + " ";
g.drawString(msg, 6, 120);
}
}

25. Develop an AWT program to demonstrate Radio buttons with Event


handling.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="RadioButton" width=500 height=500>
</applet>
*/
public class RadioButton extends Applet implements ItemListener
{ String msg = "";
Font f;
Checkbox c1,c2,c3,c4;
CheckboxGroup cb;
public void init() {
Font f= new Font("Courier", Font.BOLD, 20);
setFont(f);
cb=new CheckboxGroup();

c1 = new Checkbox("Hyderabad", cb,true);


c2 = new Checkbox("Banglore",cb, false);
c3 = new Checkbox("Delhi",cb,false);
c4 = new Checkbox("Mumbai",cb,false);

add(c1);
add(c2);
add(c3);
add(c4);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {

String s=cb.getSelectedCheckbox().getLabel(); //Returns the label of


selected radio button
g.drawString("Location selected: "+s, 50, 80);
}
}

26. Write a program to demonstrate Adapter classes


import java.awt.*;
import java.awt.event.*;
public class AdapterDemo1 extends Frame {

String msg = "";


int mouseX = 0, mouseY = 0;
Font f;

public AdapterDemo1() {
Font f= new Font("Courier", Font.BOLD, 20);
setFont(f);
setLayout(new FlowLayout());
addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "Clikced";
repaint();
}
});//anonymous class, object is created for the mouse
adapter class.+

addWindowListener (new WindowAdapter() {


public void windowClosing (WindowEvent e) {
dispose();
}
});
}
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
public static void main(String x[])
{
AdapterDemo1 s=new AdapterDemo1();
s.setSize(800,800);
s.setVisible(true);
}
}
27. Write an AWT program to implement a simple calculator with two
TextFields, four Buttons (named Add, Sub, Mul, Div) and a Label to
display result. Use ActionListener to handle events.

import java.awt.*;

import java.awt.event.*;

public class Calc extends Frame implements ActionListener

Label l1; Label l2; Label l3;

TextField t1,t2;

Button b1,b2,b3,b4;;

public Calc()

setSize(400,400);

l1=new Label("Number-1:");

l2=new Label("Number-2:");

l3=new Label("---------------------------------");

t1=new TextField(30);

t2=new TextField(30);

b1=new Button("ADD");

b2=new Button("SUB");

b3=new Button("MUL");

b4=new Button("DIV");

setLayout(new FlowLayout());

add(l1); add(t1);

add(l2); add(t2);
add(b1); add(b2);
add(b3); add(b4);

add(l3);

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

b4.addActionListener(this);

setVisible(true);

public void actionPerformed(ActionEvent

ae) {

String

s=ae.getActionCommand(); int

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

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

c=0;

if(s.equals("ADD"))

c=a+b;

if(s.equals("SUB"))

c=a-b;

if(s.equals("MUL"))

c=a*b;

if(s.equals("DIV"))

c=a/b;

l3.setText(c+"");

public static void main(String[]

args) {
Calc x=new Calc();

}
}

28. Program to demonstrate Mouse Events & Key events.

Mouse Events:

import java.awt.*;

import java.awt.event.*;

public class MouseEvents extends Frame

implements MouseListener, MouseMotionListener {

String msg = "";

int mouseX = 0, mouseY = 0;

Label st;

Font f;

public MouseEvents() {

Font f= new Font("Courier", Font.BOLD, 20);

setFont(f);

setLayout(new FlowLayout());

st=new Label(" ");

add(st);

addMouseListener(this);

addMouseMotionListener(this);

public void mouseClicked(MouseEvent me) {

st.setText("Mouse clicked.");

}
public void mouseEntered(MouseEvent me) {

st.setText("Mouse entered.");
}

public void mouseExited(MouseEvent me) {

st.setText("Mouse exited.");

public void mousePressed(MouseEvent me) {

st.setText("Mouse Down");

public void mouseReleased(MouseEvent me) {

st.setText("Mouse Up");

public void mouseDragged(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "*";

st.setText("Dragging mouse at " + mouseX + ", " +

mouseY); repaint();

public void mouseMoved(MouseEvent me) {

mouseX = me.getX();

mouseY = me.getY();

msg = "Demo";
st.setText("Moving mouse at " + me.getX() + ", " +

me.getY()); repaint();

public void paint(Graphics g) {


g.drawString(msg, mouseX, mouseY);

public static void main(String x[])

MouseEvents s=new MouseEvents();

s.setSize(800,800);

s.setVisible(true);

Key Events:

import java.awt.*;

import java.awt.event.*;

public class SimpleKey extends Frame implements KeyListener {

String msg = "";

Label st;

public SimpleKey() {

super("SimpleKey Frame");

setLayout(new FlowLayout());

st=new Label(" ");

add(st);

setSize(700, 700);

addKeyListener(this);

public void keyPressed(KeyEvent ke) {


st.setText("Key Down");

System.out.println("Key Pressed");

public void keyReleased(KeyEvent ke) {


st.setText("Key Up");

System.out.println("Key released");

public void keyTyped(KeyEvent ke) {

System.out.println("Key typed");

msg += ke.getKeyChar();

repaint();

// Display keystrokes.

public void paint(Graphics g) {

g.drawString(msg, 100, 100);

public static void main(String[] args) {

SimpleKey frame = new SimpleKey();

frame.setVisible(true);

}
29. Write a Java program to illustrate collection classes like Array List,
LinkedList, TreeMap and HashMap.

a) ArrayList

import java.util.ArrayList;

import java.util.Scanner;
public class ArrayListDemo {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

ArrayList<Object> list = new ArrayList<>();

System.out.println("List=" + list);

list.add(10);

list.add(20);

list.add(45.6);

list.add(5.7);

list.add("abc");

list.add("xyz");

System.out.println("List after insertion=" + list);

System.out.println("Enter a positive index to fetch an

item:"); int i = sc.nextInt();

System.out.println("Element at " + i + "=" + list.get(i));

System.out.println("Enter a positive index to remove

item:"); i = sc.nextInt();
list.remove(i);

System.out.println("List after removing " + i + "=" + list);

list.set(i, 100);

System.out.println("List after updating value at " + i + "=" + list);


list.clear();

System.out.println("Now list=" + list);

b) LinkedList

import java.util.LinkedList;

import java.util.Scanner;

public class LinkedListDemo {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

LinkedList<Object> list = new LinkedList<>();

System.out.println("Linked List=" + list + ", size=" + list.size());

list.add(10);

list.add(20);

list.add(45.6);

list.add(5.7);

list.add("abc");

list.add("xyz");

System.out.println("Linked List after insertion=" + list + ", size=" + list.size());


list.addFirst("first item");

list.addLast("last item");

list.add(3, 50);
System.out.println("Linked List after inserting at first, last and 3rd

index\n===="); System.out.println(list + ", size=" + list.size());

System.out.println("Enter a positive index to fetch an item:");

int i = sc.nextInt();

System.out.println("Element at " + i + "=" + list.get(i));

System.out.println("Enter a positive index to remove item:");

i = sc.nextInt();

list.remove(i);

list.removeFirst();

list.removeLast();

System.out.println("Linked List after removing " + i + ", first, last items=" + list +

", size=" + list.size());

list.set(i, 100);

System.out.println("List after updating value at " + i + "=" + list);

list.clear();

System.out.println("Now list=" + list + ", size=" + list.size());

c) TreeMap

import java.util.Scanner;
import java.util.TreeMap;

public class TreeMapDemo {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

TreeMap<Integer, String> tm = new TreeMap<>();

System.out.println("TreeMap: " + tm);

tm.put(121, "john");

tm.put(156, "smith");

tm.put(101, "Dennis");

tm.put(145, "James");

System.out.println("TreeMap: " + tm + ", size=" + tm.size());

System.out.println("Enter a key to fetch its

value:"); int key = sc.nextInt();

System.out.println("Value for " + key + ": " + tm.get(key));

System.out.println("First entry in Treemap: " + tm.firstEntry());

System.out.println("Last entry in TreeMap: " + tm.lastEntry());

System.out.println("Higher entry than 101: " +

tm.higherEntry(101)); System.out.println("Lower entry than 145: " +

tm.lowerEntry(145));

tm.replace(101, "Rossum");

System.out.println("TreeMap after replacing 101: " + tm);


tm.remove(101);

System.out.println("TreeMap after removing 101: " + tm);

tm.clear();

System.out.println("TreeMap: " + tm + ", size=" + tm.size());


}

d) HashMap

import java.util.*;

public class HashMapDemo {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

HashMap<Integer, String> hm = new

HashMap<>(); System.out.println("HashMap: " +

hm);

hm.put(121, "John");

hm.put(156, "Smith");

hm.put(101, "Dennis");

hm.put(145, "James");

System.out.println("HashMap: " + hm + ", size = " + hm.size());


System.out.println("Enter a key to fetch its

value:"); int key = sc.nextInt();

System.out.println("Value for " + key + ": " + hm.get(key));

hm.replace(101, "Rossum");

System.out.println("HashMap after replacing 101: " + hm);

hm.remove(101);

System.out.println("HashMap after removing 101: " + hm);


System.out.println("Enter a key to check if it exists or not:");

int searchKey = sc.nextInt();

boolean exists = hm.containsKey(searchKey);

System.out.println("Search status = " + exists);

hm.clear();

System.out.println("HashMap: " + hm + ", size = " + hm.size());

30. Write a Java program to implement iteration over Collection using


Iterator interface and Listlterator interface.

import java.util.*;

public class IteratorDemo {

public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<>();


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

list.add(i);

System.out.println("Items in ArrayList: " + list);

// Traversing ArrayList using Iterator

System.out.println("Traversing ArrayList using

Iterator\n==============="); Iterator<Integer> it = list.iterator();

while (it.hasNext()) {

System.out.print(it.next() + "\t");

System.out.println("\n\nTraversing ArrayList in forward direction using

ListIterator\n===========");

ListIterator<Integer> lit = list.listIterator();

while (lit.hasNext()) {

System.out.print(lit.next() + "\t");

System.out.println("\n\nTraversing ArrayList in backward direction using

ListIterator\n===========");

while (lit.hasPrevious()) {

System.out.print(lit.previous() + "\t");

System.out.println();

}
}

31. Write a Java program that reads a file name from the user, and then
displays information about whether the file exists, whether the file is
readable, whether the file is writable, the type of file and the length of
the file in bytes.

import java.util.Scanner;

import java.io.File;

public class FileDemo {


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter file name with extension:");

String fname = sc.nextLine();

File file = new File(fname);

if (file.exists()) {

System.out.println(fname + " exists");

System.out.println("File location: " +

file.getAbsolutePath()); System.out.println("File readable? "

+ file.canRead());

System.out.println("File writable? " + file.canWrite());

System.out.println("Length of the file: " + file.length() + " bytes");

int index = fname.lastIndexOf(".");

if (index > 0) {

String ext = fname.substring(index + 1);

System.out.println("File type: " + ext);

}
} else {

System.out.println(fname + " does not exist");

32. Write a Java program to implement serialization concept

import java.io.*;

class Person implements Serializable {

String name;

int age;

long mobileno;
Person(String name, int age, long mobileno) {

this.name = name;

this.age = age;

this.mobileno = mobileno;

class SerializationDemo {

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

Person p1 = new Person("abc", 20, 123456);

Person p2 = new Person("xyz", 23, 456789);

// Serialization

try (FileOutputStream fos = new FileOutputStream("serialize.txt");

ObjectOutputStream oos = new ObjectOutputStream(fos)) {

oos.writeObject(p1);

oos.writeObject(p2);

System.out.println("Person objects serialized in file

serialize.txt"); }
}

// Deserialization

import java.io.*;

public class DeSerializationDemo

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

System.out.println("Performing

Deserialization\n======="); Person t1, t2;

try (FileInputStream fis = new FileInputStream("serialize.txt");

ObjectInputStream ois = new ObjectInputStream(fis)) {

t1 = (Person) ois.readObject();

t2 = (Person) ois.readObject();

System.out.println("Person 1 data from serialize.txt\n======");

System.out.println("Name: " + t1.name);

System.out.println("Age: " + t1.age);

System.out.println("Mobile No: " + t1.mobileno);

System.out.println("Person 2 data from serialize.txt\n======");

System.out.println("Name: " + t2.name);

System.out.println("Age: " + t2.age);

System.out.println("Mobile No: " + t2.mobileno);

33. Write a Java program to perform following CRUD operations on


student data using JDBC.

Prerequisite for this program:


1. Create a folder with the name “jdbc” in Desktop .

2. Download and Copy mysql.jar file in “jdbc” folder.

3. Start mysql database using below command

sudo /opt/lampp/lampp start

4. Login into mysql database using below command

mysql --host=127.0.0.1 --user=root

5. Change database to test using below command

use test;

6. Use the below command to check for tables.

7. Ensure the database “test” should be empty.

i) Creating a Student Record in database


import java.sql.*;

public class StudentDBCreation {

public static void main(String[] args) {

String dbUrl = "jdbc:mysql://localhost:3306/test";

String user = "root";

String password = "";


try {

// Load MySQL JDBC driver

Class.forName("com.mysql.cj.jdbc.Driver");

// Establish database connection

Connection con = DriverManager.getConnection(dbUrl, user,

password); System.out.println("Database connection successful");

// Create SQL query for table creation

String query = "CREATE TABLE student (" +

"rno INT PRIMARY KEY, " +

"name VARCHAR(20), " +

"branch VARCHAR(10), " +

"marks DOUBLE)";

// Execute the query

Statement st = con.createStatement();

st.execute(query);

System.out.println("Student table created successfully");

// Close the connection

con.close();

} catch (Exception e) {

System.out.println("Database error: " +

e.getMessage()); }

Procedure:
Step-1: Save the file as StudentDBCreation.java in the jdbc folder.

Step-2: Open Terminal and Change directory to jdbc folder Step-3:

Compile using below command javac StudentDBCreation.java Step-4:

Run the program using below command

java -cp :./mysql.jar StudentDBCreation

II. Inserting a Student Record in database

import java.sql.*;

import java.util.*;
public class StudentDBInsertion {

public static void main(String[] args) {

String dbUrl = "jdbc:mysql://localhost:3306/test";

String user = "root";

String password = "";

try {

// Load MySQL JDBC driver

Class.forName("com.mysql.cj.jdbc.Driver");

// Establish database connection

Connection con = DriverManager.getConnection(dbUrl, user,

password); System.out.println("Database connection successful");

// Prepare SQL query for insertion

String query = "INSERT INTO student VALUES (?, ?, ?, ?)";

PreparedStatement pst = con.prepareStatement(query);

// Input student details

Scanner sc = new Scanner(System.in);

System.out.println("Enter Student details:");


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

int rno = sc.nextInt();

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

String name = sc.next();

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

String branch = sc.next();

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


double marks = sc.nextDouble();

// Set parameters and execute the query

pst.setInt(1, rno);

pst.setString(2, name);

pst.setString(3, branch);

pst.setDouble(4, marks);

int count = pst.executeUpdate();

System.out.println(count + " record inserted into database");

// Close the resources

pst.close();

con.close();

} catch (Exception e) {

System.out.println("Database error: " +

e.getMessage()); }

Procedure:

Step-1: Save the file as StudentDBInsertion.java in the jdbc

folder. Step-2: Open Terminal and change directory to jdbc


folder Step-3: Compile using below command

javac StudentDBInsertion.java

Step-4: Run the program using below command

java -cp :./mysql.jar StudentDBInsertion

III. Retrieve and display the student records from database

import java.util.*;

import java.sql.*;

public class StudentDBRetrieval {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

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

int rno = sc.nextInt();

String dbUrl = "jdbc:mysql://localhost:3306/test";

String user = "root";

String password = "";

try {

// Load MySQL JDBC driver

Class.forName("com.mysql.cj.jdbc.Driver");

// Establish database connection

Connection con = DriverManager.getConnection(dbUrl, user,

password); System.out.println("Database connection successful");

// Prepare SQL query for retrieval


String query = "SELECT * FROM student WHERE rno = ?";

PreparedStatement pst = con.prepareStatement(query);

pst.setInt(1, rno);

// Execute the query and retrieve results

ResultSet rs = pst.executeQuery();

boolean result = rs.next();


System.out.println("Student

Details:\n==========="); if (result) {

System.out.println("Roll

No\tName\tBranch\tMarks\n======\t=====\t======\t=====")

; System.out.printf("%d\t%s\t%s\t%.2f%n",

rs.getInt(1),

rs.getString(2),

rs.getString(3),

rs.getDouble(4));

} else {

System.out.println("Record doesn't exist");

// Close resources

rs.close();

pst.close();

con.close();

} catch (Exception e) {

System.out.println("Database error: " +

e.getMessage()); }

}
Procedure:

Step-1: Save the file as StudentDBRetreival.java in the jdbc

folder. Step-2: Open Terminal and change directory to jdbc

folder Step-3: Compile using below command

javac StudentDBRetreival.java

Step-4: Run the program using below command


java -cp :./mysql.jar StudentDBRetreival

You might also like