0% found this document useful (0 votes)
2 views84 pages

Lab java

The document contains a series of Java programming labs, each with a specific task such as printing 'Hello World', finding the second largest element in an array, and calculating areas of geometric shapes. Each lab includes the code implementation, expected output, and sometimes additional explanations. The labs cover various programming concepts including arrays, conditionals, loops, methods, and classes.

Uploaded by

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

Lab java

The document contains a series of Java programming labs, each with a specific task such as printing 'Hello World', finding the second largest element in an array, and calculating areas of geometric shapes. Each lab includes the code implementation, expected output, and sometimes additional explanations. The labs cover various programming concepts including arrays, conditionals, loops, methods, and classes.

Uploaded by

adhikbinu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Lab-1.

Write Java program to print “Hello World”

Code:
package rabina_lab;
public class lab1 {
public static void main(String[] args){
[Link]("Hello World");
}
}

Output:

Lab-2. Write a program in java that finds second largest element in an array

Code:

import [Link];

public class lab2 {


public static void main(String[] args){
int[] numbers = new int[]{23,45,67,88,10,1,32,1001};
[Link](numbers);
[Link]("The second largest element in the array is : " +
numbers[[Link] - 2]);}}

Output:
Lab-3. Given three numbers, write a Java program to read three numbers from keyword and
print out the largest of them.

Code:
package rabina_lab;
import [Link];

public class lab3 {


public static void main(String[] args){

Scanner scanner = new Scanner([Link]);


[Link]("Enter the first number : ");
double num1 = [Link]();
double largest = num1;
[Link]("Enter the second number : ");
double num2 = [Link]();
if(num2 > largest){
largest = num2;
}
[Link]("Enter the third number : ");
double num3 = [Link]();
if(num3 > largest){
largest = num3;
}
[Link]("The largest number among the three is : " + largest);
}
}

Output:
Lab-4. Write a Java program reads a character and check if it is alphabet or not.

Code:
package rabina_lab;
import [Link];

public class lab4 {


public static void main(String[] args){
Scanner scanner = new Scanner([Link]);
[Link]("Enter a character : ");
char ch = [Link]().charAt(0);
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ){
[Link]("It is a alphabet");
}else{
[Link]("It is not a alphabet");
}}}

Output:
Lab-5. Write a program that checks if the array is sorted or not.

Code:

package rabina_lab;
public class lab5 {
public static void main(String[] args){
int[] nums = new int[] { 1,34,56,7,8};

boolean isSorted = true;


for (int i = 0; i < [Link] - 1; i++) {
if (nums[i] > nums[i + 1]) {
isSorted = false;
break;
}
if(isSorted){
[Link]("The array is sorted.");
}else{
[Link]("The array is not sorted.");
}

}
}
Output:
Lab-6. Write a Java program to read two integer values m and n and to decide whether m is a
multiple of n.

Code:

import [Link];

public class lab6 {


public static void main(String[] args){
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number 'm' : ");
int m = [Link]();
[Link]("Enter a number 'n' : ");
int n = [Link]();

if(m % n == 0){
[Link]("The number %d is multiple of %d" , m, n);
}else{
[Link]("The number %d is not multiple of %d" , m, n);
}
[Link]();
}
}
Output:
Lab-7. Write a Java program that reads radius of circle and finds area and circumference.

Code:
package rabina_lab;
import [Link];

public class lab7 {


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

[Link]("Enter the radius of the circle: ");


double radius = [Link]();

double area = [Link] * radius * radius;


double circumference = 2 * [Link] * radius;

[Link]("The area of the circle is: %.2f\n", area);


[Link]("The circumference of the circle is: %.2f\n", circumference);

[Link]();
}

Output:
Lab-8. Write a Java program that finds factorial of a positive number using recursive method.

Code:
import [Link];
public class lab8 {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Enter the number to calculate factorial : ");


int num = [Link]();
[Link]("The factorial of %d is : %d" , num , factorial(num));
}

private static int factorial(int num){


if(num == 0 || num == 1){
return 1;
}
return factorial(num - 1) * factorial(num - 2);
}
}

Output:
Lab-9. Write Java program to print prime numbers from 300 to 500 using method.

Code:

public class lab9 {


public static void main(String[] args) {
[Link]("The list of prime number are : ");
for(int i = 300 ; i <= 500 ; i++){
if(isPrime(i)){
[Link](i);
}
}
}

private static boolean isPrime(int num){


if(num <= 2){
return true;
}
for(int i = 2; i <= [Link]([Link](num)) ; i++){
if(num % i == 0){
return true;
}}
return false;
}
Output:
Lab-10. Write a Java program to find the largest number among four different numbers using
conditional operator.

Code:
import [Link];

public class lab10 {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter first number: ");
double n1 = [Link]();
[Link]("Enter second number: ");
double n2 = [Link]();
[Link]("Enter third number: ");
double n3 = [Link]();
[Link]("Enter fourth number: ");
double n4 = [Link]();

double largest = (n1 > n2 && n1 > n3 && n1 > n4) ? n1 :


(n2 > n3 && n2 > n4) ? n2 :
(n3 > n4) ? n3 : n4;

[Link]("The largest number is: " + largest);


[Link]();
}
}
Output:
Lab-11. A non-empty array A of length n is called on array of all possibilities if it contains all
numbers between 0 and [Link]-1 inclusive. Write a method named is All Possibilities that
accepts an integer array and returns 1 if the array is an array of all possiblities, otherwise it
returns 0.

Code:
public class lab11 {
public static void main(String[] args) {
int[] arr = new int[]{0,1,2,3};

[Link]("The returned output is : " + isAllPossibilities(arr));

}
public static int isAllPossibilities(int[] arr){
boolean[] found = new boolean[[Link]];

if(arr == null || [Link] == 0 ){


return 0;
}

for(int x : arr){

if(x < 0 || x > [Link]-1){


return 0;
}
if(found[x]){
return 0;
}

found[x]= true;
}

for(boolean b : found){
if(!b){
return 0 ;
}
}
return 1;
}

}
Output:
Lab-12. Write a Java program that finds sum of two and three numbers using concept of method
overloading.

Code:
class Calculator{
public int Add(int a , int b){
return a + b;
}

public int Add(int a , int b,int c){


return a + b + c;
}
}

public class lab12 {

public static void main(String[] args){


Calculator calc = new Calculator();

[Link]("The addition of two numbers : " + [Link](4, 50));


[Link]("The addition of three numbers : " + [Link](4, 4,4));
}
}
Output:
Lab-13. Write a Java program that finds areas of different geometric shapes using concept of
method overloading.

Code:
package rabina_lab;

class ShapeAreaCalculator {

public double calculateArea(double radius) {


return [Link] * radius * radius;
}
// 2. Overloaded method for Rectangle area (length * width)
public double calculateArea(double length, double width) {
return length * width;
}
public double calculateArea(float base, double height) {
return 0.5 * base * height;
}

public double calculateArea(int side) {


return side * side;
}
public class lab13{
public static void main(String[] args) {
ShapeAreaCalculator calculator = new ShapeAreaCalculator();
double circleArea = [Link](5.5);
[Link]("Area of Circle (radius 5.5): %.2f\n", circleArea);
double rectangleArea = [Link](10.0, 4.0);
[Link]("Area of Rectangle (10.0 x 4.0): %.2f\n", rectangleArea);
double triangleArea = [Link](6.0f, 7.0);
[Link]("Area of Triangle (base 6.0, height 7.0): %.2f\n", triangleArea);
double squareArea = [Link](6);
[Link]("Area of Square (side 6): %.2f\n", squareArea);
}
}

Output:
Lab-14. Create a class Number with three int instance variable x , y and z. The class will have
one constructor. The class also will contain member function getMax () that will return the
largest number. Create a main method that will create an object of Number and will print the
largest number.

Code:
package rabina_lab;
class Number{
int x,y,z;
Number(int x , int y , int z){
this.x = x;
this.y = y;
this.z = z;
}

int getMax(){
return [Link](x,[Link](y ,z));}
public class lab14 {
public static void main(String[] args){
Number numInstance = new Number(10,90,6);
[Link]("The max number is :" + [Link]());
}
}
Output:
Lab-15. Write a Java program to add two complex numbers

Code:
class ComplexNumber {
double real;
double imaginary;
public ComplexNumber(double real, double imaginary) {
[Link] = real;
[Link] = imaginary;
}
public ComplexNumber add(ComplexNumber other) {
double newReal = [Link] + [Link];
double newImaginary = [Link] + [Link];
return new ComplexNumber(newReal, newImaginary);
}
public void display() {
if ([Link] >= 0) {
[Link]([Link] + " + " + [Link] + "i");
} else {
[Link]([Link] + " - " + [Link]([Link]) + "i");
}}

public class lab15 {


public static void main(String[] args) {

ComplexNumber num1 = new ComplexNumber(4.5, 5.0);


ComplexNumber num2 = new ComplexNumber(2.5, 3.5);
[Link]("First Complex Number: ");
[Link]();
[Link]("Second Complex Number: ");
[Link]();

ComplexNumber sum = [Link](num2);


[Link]("The sum is: ");
[Link]();
}
}
Output:
Lab-16. Write a Java program to add two Time(hr,min,sec) objects.

Code:
class Time{
int hour ,min , sec;
public Time(int hour,int min , int sec){
[Link] = hour;
[Link] = min;
[Link] = sec;
}
public Time addTime(Time otherTime){
int totalHr = [Link] + [Link];
int totalMin = [Link] + [Link];
int totalSec = [Link] + [Link];
if(totalSec >= 60){
totalMin += totalSec / 60;
totalSec = totalSec % 60;
}
if(totalMin >= 60){
totalHr += totalMin / 60;
totalMin = totalMin % 60;
}
return new Time(totalHr,totalMin,totalSec);
}
public void display() {
[Link]("%02d:%02d:%02d\n", hour, min, sec);
}}
public class lab16 {
public static void main(String[] args){
Time t1 = new Time(2, 45, 50);
Time t2 = new Time(1, 20, 20);
[Link]("Time 1: ");
[Link]();
[Link]("Time 2: ");
[Link]();
Time result = [Link](t2);
[Link]("Total Time: ");
[Link]();
}
}
Output:
Lab-17. Create a class Swapper class with two integer instance variable x and y and constructor
with two parameters that initializes the two variables. Also include three member functions: A
getX () that returns x, a getY () function that returns y, a void swap () method that swaps the
values of x and y. Then define a main() method to create an object of Swapper class and swap
the value of instance variables.

Code:
package rabina_lab;

class Swapper {
int x, y;
public Swapper(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
void swap() {
int temp = this.x;
this.x = this.y;
this.y = temp;
}}
public class lab17 {
public static void main(String[] args) {
Swapper obj = new Swapper(10, 20);
[Link]("Before Swap:");
[Link]("x = " + [Link]());
[Link]("y = " + [Link]());
[Link]();
[Link]("\nAfter Swap:");
[Link]("x = " + [Link]());
[Link]("y = " + [Link]());
}
}
Output:
Lab-18. Create a class Date with three integer instance variables named day, month, year. It
has a constructor with three parameters for initializing the instance variables, and it has one-
member function named daySinceJan1 (). It computes and returns the number of days since
January 1 of the same year, including January 1 and the day in the Date object. For example, if
day is a Date object with day = 1, month = 3 and year = 2000, then the call date.daySinceJan1()
should return 61 since there are 61 days between the dates of January 1, 2000, and March 1,
2000, including January 1 and March 1. Then define main () method to handle Date class.
Don’t forget leap years.

Code:
package rabina_lab;
class Date {
int day, month, year;
public Date(int day, int month, int year) {
[Link] = day;
[Link] = month;
[Link] = year;
}
private boolean isLeapYear() {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
public int daySinceJan1() {
int[] daysInMonths = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear()) {
daysInMonths[2] = 29;
}
int totalDays = 0;
for (int i = 1; i < [Link]; i++) {
totalDays += daysInMonths[i];
}
totalDays += [Link];
return totalDays;
}
public class lab18 {
public static void main(String[] args) {
Date date1 = new Date(1, 3, 2000);
[Link]("Days since Jan 1, 2000 for March 1: " + date1.daySinceJan1());

Date date2 = new Date(1, 3, 2001);


[Link]("Days since Jan 1, 2001 for March 1: " + date2.daySinceJan1());
}
}
Output:
Lab-19. Create a USMoney class with two integer instance variables dollars and cents. Add a
constructor with two parameters for initializing a USMoney object. The constructor should
check that the cent value is between 0 and 99 and, if not, transfer some cents to the dollars
variables to make it between 0 and 99. For example, if x is a USMoney object with 5 dollars
and 80 cents, and if y is a USMoney object with 1 dollar and 90 cents, then [Link] (y) will
return a new USMoney object with 7 dollars and 70 cents. Also, create a main () method that
creates to objects of USMoney class and add them.
Code:
package rabina_lab;
class USMoney {
int dollars;
int cents;
public USMoney(int dollars, int cents) {
[Link] = dollars;
[Link] = cents;
if ([Link] >= 100) {
[Link] += [Link] / 100;
[Link] = [Link] % 100;
public USMoney plus(USMoney other) {
int totalDollars = [Link] + [Link];
int totalCents = [Link] + [Link];
return new USMoney(totalDollars, totalCents);
}
public void display() {
[Link]("$%d.%02d\n", dollars, cents);
}
}
public class lab19 {
public static void main(String[] args) {
USMoney x = new USMoney(5, 80); // $5.80
USMoney y = new USMoney(1, 90); // $1.90
[Link]("Object x: ");
[Link]();
[Link]("Object y: ");
[Link]()
USMoney result = [Link](y);
[Link]("Result of [Link](y): ");
[Link]();

Output:
Lab-20. Create a Person class with private instance variables for person’s name and birth date.
Add appropriate functions for these variables. Then create a subclass CollegeGraduate with
private instance variables for the student’s GPA and year of graduation and appropriate
functions for these variables. Don’t forget to include appropriate constructor constructors for
your classes. Then define main () method that demonstrates your classes.

Code:

package rabina_lab;

import [Link];

class Person {

private String name;

private LocalDate birthDate;

public Person(String name, LocalDate birthDate) {

[Link] = name;

[Link] = birthDate;

public String getName() {

return name;

public void setName(String name) {

[Link] = name;

public LocalDate getBirthDate() {

return birthDate;

public void setBirthDate(LocalDate birthDate) {

[Link] = birthDate;

public void displayInfo() {


[Link]("Name: " + name);

[Link]("Birth Date: " + birthDate);

class CollegeGraduate extends Person {

private double gpa;

private int graduationYear;

public CollegeGraduate(String name, LocalDate birthDate, double gpa, int graduationYear)


{

super(name, birthDate); // Calls the Person constructor

[Link] = gpa;

[Link] = graduationYear;

public double getGpa() {

return gpa;

public void setGpa(double gpa) {

[Link] = gpa;

public int getGraduationYear() {

return graduationYear;

public void setGraduationYear(int graduationYear) {

[Link] = graduationYear;

@Override

public void displayInfo() {


[Link](); // Prints Name and Birth Date from the parent class

[Link]("GPA: " + gpa);

[Link]("Graduation Year: " + graduationYear);

public class lab20 {

public static void main(String[] args) {

[Link]("--- Person Object ---");

Person person = new Person("Harry Potter", [Link](1998, 5, 15));

[Link]();

[Link]();

[Link]("--- CollegeGraduate Object ---");

CollegeGraduate grad = new CollegeGraduate("Arya Stark", [Link](2002, 11, 23),


3.85, 2024);

[Link]();

[Link]("\n--- Updating Arya's GPA ---");

[Link](3.95);

[Link]("Arya's New GPA via Getter: " + [Link]());

Output:
Lab-21. Create a class Box with fields width, height and depth. Add methods getArea () and getVolume (). Use
suitable constructors. From main () method create an object of Box class and find its area as volume.

Code:

package rabina_lab;

class Box {

double width;

double height;

double depth;

public Box(double width, double height, double depth) {

[Link] = width; [Link] = height;[Link] = depth;

public double getArea() {

return 2 * ((width * height) + (height * depth) + (depth * width)); }

public double getVolume() {

return width * height * depth; }}

public class lab21 {

public static void main(String[] args) {

Box myBox = new Box(5.0, 3.0, 4.0);

[Link]("Box Dimensions -> Width: " + [Link] + ", Height: " + [Link] + ", Depth:
" + [Link]);

double area = [Link]();

[Link]("Total Surface Area of the Box: %.2f\n", area);

double volume = [Link]();

[Link]("Volume of the Box: %.2f\n", volume);

Output:
Lab-22. Create a class Room with instance variables length and breadth. Add one function
getArea () that returns the area of the room. Create a subclass MyRoom and add one instance
variable height. Add one function getVolume () that returns the volume. Then define main ()
method that creates two MyRoom objects and find area and volumes of both rooms.

Code:

class Room {

double length;

double breadth;

public Room(double length, double breadth) {

[Link] = length;

[Link] = breadth;

public double getArea() {

return length * breadth;

}}

class MyRoom extends Room {

double height;

public MyRoom(double length, double breadth, double height) {

super(length, breadth);

[Link] = height;}

public double getVolume() {

return getArea() * height;}

public class lab22 {

public static void main(String[] args) {

MyRoom room1 = new MyRoom(12.0, 10.0, 9.0);

MyRoom room2 = new MyRoom(15.5, 12.5, 10.0);

[Link]("--- Room 1 Details ---");

[Link]("Floor Area: %.2f sq. units\n", [Link]());


[Link]("Total Volume: %.2f cu. units\n", [Link]());

[Link]();

[Link]("--- Room 2 Details ---");

[Link]("Floor Area: %.2f sq. units\n", [Link]());

[Link]("Total Volume: %.2f cu. units\n", [Link]());

Output:
Lab-23. Create a class Box with instance variables length, breadth and height. Add one method
getVolume () to compute the volume of box. Use suitable constructors. Create a subclass
BoxWeight that extends Box that add one variable weight. Add one function getWeight () that
displays the weight of box to this class. Add suitable constructors. Create one more subclass
class Shipment that extends BoxWeight. Add one function getCost () that displays the cost of
the box. Add suitable constructors. Then define main () method that creates an object of
Shipment that initializes the instance variables through constructor.

Code:

package rabina_lab;

class ShippingBox {

double length;

double breadth;

double height;

public ShippingBox(double length, double breadth, double height) {

[Link] = length;

[Link] = breadth;

[Link] = height;

public double getVolume() {

return length * breadth * height;

class BoxWeight extends ShippingBox {

double weight;

public BoxWeight(double length, double breadth, double height, double weight) {

super(length, breadth, height);

[Link] = weight;

public void displayWeight() {


[Link]("Box Weight: " + weight + " kg");

class Shipment extends BoxWeight {

double costPerKg;

public Shipment(double length, double breadth, double height, double weight, double
costPerKg) {

super(length, breadth, height, weight);

[Link] = costPerKg;

public void displayCost() {

double totalCost = weight * costPerKg;

[Link]("Total Shipping Cost: $%.2f\n", totalCost);}}

public class lab23 {

public static void main(String[] args) {

Shipment myShipment = new Shipment(5.0, 4.0, 3.0, 12.5, 2.50);

[Link]("Box Volume: " + [Link]() + " cubic units");

[Link]();

[Link]();}}

Output:
Lab-24. Create an abstract class Figure with two instance variables dim1 and dim2. Add
suitable constructors. Add one abstract function called getArea (). Create two subclass called
Rectangle and Triangle. Add function getArea () to both of the classes that will find the area of
respective figures. Then define main () method that creates an object of each classes and find
the area of triangle and rectangle.

Code:

package rabina_lab;

abstract class Figure {

double dim1; double dim2;

public Figure(double dim1, double dim2) {

this.dim1 = dim1;

this.dim2 = dim2;}

public abstract double getArea();}

class RectangleFigure extends Figure {

public RectangleFigure(double length, double width) {

super(length, width);

@Override

public double getArea() {

return dim1 * dim2;

}}

class TriangleFigure extends Figure {

public TriangleFigure(double base, double height) {

super(base, height); }

@Override

public double getArea() {

return 0.5 * dim1 * dim2;}}

public class lab24 {


public static void main(String[] args) {

RectangleFigure rect = new RectangleFigure(10.0, 5.0);

[Link]("Area of Rectangle (10 x 5): %.2f\n", [Link]());

TriangleFigure tri = new TriangleFigure(8.0, 6.0);

[Link]("Area of Triangle (Base 8, Height 6): %.2f\n", [Link]());

Figure dynamicShape;

dynamicShape = rect;

[Link]("Polymorphic call to Rectangle area: %.2f\n",


[Link]());

dynamicShape = tri;

[Link]("Polymorphic call to Triangle area: %.2f\n", [Link]());


}}

Output:
Lab-25. Write a Java program to demonstrate divide by zero exception.

Code:

package rabina_lab;

public class lab25 {

public static void main(String[] args) {

int numerator = 50;

int denominator = 0;

[Link]("--- Scenario 1: Unhandled Exception ---");

[Link]("Attempting to divide " + numerator + " by " + denominator);

[Link]("\n--- Scenario 2: Handled Exception ---");

try {

int result = numerator / denominator;

[Link]("Result: " + result);

} catch (ArithmeticException e) {

[Link]("Error caught: Cannot divide an integer by zero!");

[Link]("Exception message from Java: " + [Link]());} finally {

[Link]("The finally block executed successfully.");

[Link]("\nProgram continues running safely after the try-catch block.");}}

Output:
Lab-26. Write a Java program to demonstrate array index bounds exception

Code:

package rabina_lab;

public class lab26 {

public static void main(String[] args) {

int[] numbers = {10, 20, 30};

[Link]("Array length: " + [Link]);

[Link]("Valid index 0: " + numbers[0]);

[Link]("Valid index 2: " + numbers[2]);

[Link]("\n--- Triggering and Handling the Exception ---");

try {

[Link]("Attempting to access index 5...");

int invalidAccess = numbers[5];

[Link]("This will not print: " + invalidAccess);

} catch (ArrayIndexOutOfBoundsException e) {

[Link]("Error caught: That index is outside the array's boundaries!");

[Link]("The maximum valid index was: " + ([Link] - 1));

[Link]("You tried to access index: " + [Link]());}}

Output:
Lab-27. Write a Java Program to demonstrate null exception

Code:

package rabina_lab;

public class lab27 {

public static void main(String[] args) {

String myText = null;

[Link]("--- Triggering and Handling NullPointerException ---");

try {

[Link]("Attempting to check the length of the string...");

int length = [Link]();

[Link]("String length is: " + length);

} catch (NullPointerException e) {

[Link]("Error caught: You cannot call methods on a 'null' object


reference!");

[Link]("Java Exception Message: " + e);

Output:
Lab-28. Write a Java program to demonstrate custom exception

Code:

package rabina_lab;

class InvalidAgeException extends Exception {

public InvalidAgeException(String message) {

super(message);}

}public class lab28 {

public static void checkVotingEligibility(int age) throws InvalidAgeException {

if (age < 18) {

throw new InvalidAgeException("Age " + age + " is too young to vote! Must be 18 or
older.");

} else {

[Link]("Access Granted: Age " + age + " is eligible to vote.") }

public static void main(String[] args) {

[Link]("--- Test Case 1: Valid Input ---");

try {

checkVotingEligibility(16);

} catch (InvalidAgeException e) {

[Link]("Caught: " + [Link]());}

Output:
Lab-29. Write a Java program to reads contents of a file using character stream

Code:

package rabina_lab;

import [Link];

import [Link];

import [Link];

public class lab29 {

public static void main(String[] args) {

String filePath = "C:\\Users\\user\\OneDrive\\Documents\\[Link]";

FileReader reader = null;

try {

reader = new FileReader(filePath);

int data;

[Link]("Reading file contents character by character:");

while ((data = [Link]()) != -1) {

char character = (char) data;

[Link](character); }

} catch (FileNotFoundException e) {

[Link]("Error: The file '" + filePath + "' could not be found.");

} catch (IOException e) {

[Link]("Error: An issue occurred while reading the file data.");

} finally { try {

if (reader != null) {

[Link]();

[Link]("File reader resource closed safely.") }

} catch (IOException e) {

[Link]("Error: Failed to close the file reader.");


Output:
Lab-30. Write a Java program to write some lines of text to file using character stream.

package rabina_lab;

import [Link];

import [Link];

public class lab30 {

public static void main(String[] args){

String filePath = "C:\\Users\\user\\OneDrive\\Documents\\[Link]";

FileWriter writer = null;

try{

writer = new FileWriter(filePath, false);

[Link]("Writing some dummy data into the text file");

[Link]("Successfully written to the file.");

}catch(IOException e){

[Link]("Error: An issue occurred while writing the file data.");

[Link]();}finally{

try{ if(writer != null){

[Link]();

catch(IOException e){[Link]("Error: An issue occurred while closing the


writer ");}}}

Output:
Lab-31. Write a Java program that reads contents of same file using character stream

Code:

package rabina_lab;

import [Link];

import [Link];

import [Link];

public class lab31 {

public static void main(String[] args){

FileReader reader = null;

String filePath = "C:\\Users\\user\\OneDrive\\Documents\\[Link]";

try {

reader = new FileReader(filePath);

int data;

[Link]("Reading file contents character by character:");

[Link]("--------------------------------------------")

while ((data = [Link]()) != -1) {

char character = (char) data;

[Link](character);

[Link]("\n--------------------------------------------");

} catch (FileNotFoundException e) {

[Link]("Error: The file '" + filePath + "' could not be found.");

} catch (IOException e) {

[Link]("Error: An issue occurred while reading the file data.");

} finally {

try {

if (reader != null) {
[Link]();

[Link]("File reader resource closed safely.");

} catch (IOException e) {

[Link]("Error: Failed to close the file reader.");}}}}

Output:
Lab-32. Write a Java program that writes line of text to file using byte stream.

Code:

import [Link];

import [Link];

public class lab32 {

public static void main(String[] args){

String filePath = "C:\\Users\\user\\OneDrive\\Documents\\[Link]";

FileOutputStream os = null;

try{

os = new FileOutputStream(filePath,false);

String text = "The program imports FileOutputStream from the [Link] package to gain
access to the low-level byte stream management system.";

byte[] converted = [Link]();

[Link](converted);

[Link]("Success: Text byte data written to the file safely."


}catch(IOException e){

[Link]("Error: An issue occurred while reading the file data."); }finally{

try{

[Link]();

}catch(IOException e){

[Link]("Error: An issue occurred while reading the file data."); }

Output:
Lab-33. Write a Java program that reads contents of file using byte stream

Code:

package rabina_lab;

import [Link];

import [Link];

import [Link];

public class lab33 {

public static void main(String[] args){

String filePath = "C:\\Users\\user\\OneDrive\\Documents\\[Link]";

FileInputStream is = null;

try{

int byteData;

is = new FileInputStream(filePath);

while((byteData = [Link]()) != -1){

char character = (char) byteData;

[Link](character);

}catch(FileNotFoundException error){

[Link]("Error: File not found.");

}catch(IOException e){

[Link]("Error: An issue occurred while reading the file data.");

}finally{
try{

if (is != null){

[Link]()

}catch(IOException e){

[Link]("Error: An issue occurred while closing the reader.");}

Output:
Lab-34. Write a Java program to read-write objects to file.

package rabina_lab;

import [Link];

import [Link];

class Student2 implements Serializable {

private static final long serialVersionUID = 1L;

String name;

int rollNumber;

double gpa;

public Student2(String name, int rollNumber, double gpa) {

[Link] = name;

[Link] = rollNumber;

[Link] = gpa;

public void display() {

[Link]("Student Name: " + name + " | Roll: " + rollNumber + " | GPA: " +
gpa);

public class lab34 {

public static void main(String[] args) {

String filePath = "C:\\Users\\user\\OneDrive\\Documents\\student_data.ser"

[Link]("--- Step 1: Creating and Saving Object ---"); //writing

Student2 studentToWrite = new Student2("Rabina", 13, 3.92);

try (ObjectOutputStream oos = new ObjectOutputStream(new


FileOutputStream(filePath))) {

[Link](studentToWrite); object!

[Link]("Success: Student object successfully saved to " + filePath);

} catch (IOException e) {

[Link]("Error while writing object: " + [Link]()); }


[Link]();

[Link]("--- Step 2: Loading and Rebuilding Object ---");//reading

try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))) {

Student studentToRead = (Student) [Link]();

[Link]("Success: Object restored from file!"); [Link]();

} catch (IOException e) {

[Link]("Error while reading file: " + [Link]());

} catch (ClassNotFoundException e) {[Link]("Error: The Student class


blueprint could not be found.");}}}

Output:
Lab-35. Write a Java program that creates a class called Stack and then implements push() and
pop() operations.

Code:

package rabina_lab;

class Stack {

private int maxSize;

private int[] stackArray;

private int top;

public Stack(int size) {

[Link] = size;

[Link] = new int[maxSize];

[Link] = -1; // -1 means the stack is currently empty

public void push(int value) {

if (top >= maxSize - 1) {

[Link]("Stack Overflow! Cannot push " + value + ". The stack is full.");

} else {

top++;

stackArray[top] = value;

[Link]("Pushed: " + value);}}

public int pop() {

if (top < 0) {

[Link]("Stack Underflow! Cannot pop. The stack is empty.");

return -1; // Return a sentinel value indicating an empty stack

} else {

int poppedValue = stackArray[top];

top--;
return poppedValue;}

public int peek() {

if (top < 0) {

[Link]("Stack is empty.");

return -1; }

return stackArray[top];}}

public class lab35 {

public static void main(String[] args) {

Stack myStack = new Stack(3);

[Link]("--- Testing Push Operations ---");

[Link](10);[Link](20); [Link](30);

[Link](40);

[Link]("\nTop item right now (Peek): " + [Link]());

[Link]("\n--- Testing Pop Operations ---") [Link]("Popped item:


" + [Link]()); [Link]("Popped item: " + [Link]());
[Link]("Popped item: " + [Link]());

[Link]("Popped item: " + [Link]()); }}

Output:
Lab-36. Create an interface Exam with methods setExam(String division, int mark) and showExam(),
create a class named test that implements the interface Exam and then display the records.
Code:
package rabina_lab;
interface Exam {
void setExam(String division, int mark);
void showExam();
}
class StudentTest implements Exam {
private String division;
private int mark;
@Override
public void setExam(String division, int mark) {
[Link] = division;
[Link] = mark;
}
@Override
public void showExam() {
[Link]("--- Exam Performance Record ---");
[Link]("Division Achieved : " + [Link]);
[Link]("Total Marks Out : " + [Link]); }}
public class lab36 {
public static void main(String[] args) {
StudentTest record = new StudentTest();
[Link]("First Division", 85);
[Link]();
}}
Output:
Lab-37. Write a Java program to create a class Mobile (type, phone_no). Customize the
exception such that if the user give phone_no having less than or greater than 10 digit, then the
program has to throw an exception with message “Invalid Phone Number”.
Code:
package rabina_lab;
class InvalidPhoneNumberException extends Exception {
public InvalidPhoneNumberException(String message) {
super(message);}}
class Mobile {
private String type;
private String phoneNo;
public Mobile(String type, String phoneNo) throws InvalidPhoneNumberException {
if (phoneNo == null || [Link]() != 10) {
throw new InvalidPhoneNumberException("Invalid Phone Number");
}
[Link] = type;
[Link] = phoneNo;
}
public void displayDetails() {
[Link]("Mobile Type: " + type + " | Phone Number: " + phoneNo);}
}public class lab37 {
public static void main(String[] args) {
[Link]("--- Test Case 1: Valid 10-Digit Phone Number ---");
try {
Mobile phone1 = new Mobile("Smartphone", "9876543210");
[Link]();
} catch (InvalidPhoneNumberException e) {
[Link]("Caught Error: " + [Link]());
try {
Mobile phone2 = new Mobile("Feature Phone", "12345");[Link]();
} catch (InvalidPhoneNumberException e) {
[Link]("Caught Error: " + [Link]());
[Link]("\n--- Test Case 3: Invalid Long Phone Number ---");
try {
Mobile phone3 = new Mobile("Tablet", "123456789012");
[Link]();
} catch (InvalidPhoneNumberException e) {
[Link]("Caught Error: " +
[Link]());}}[Link]("\nProgram execution completed safely.")}

Output:
Lab-38. Create a class named Movie (id, genre). Write the object of Movie class into file named
“[Link]” having comedy as genre.
Code:
package rabina_lab;
import [Link];
import [Link];
import [Link];
class Movie implements Serializable {
int id;
String genre;
Movie(int id, String genre) {
[Link] = id;
[Link] = genre; }}
public class lab38 {
public static void main(String[] args) {
try {
Movie m = new Movie(101, "comedy");
FileOutputStream file = new FileOutputStream("[Link]");
ObjectOutputStream out = new ObjectOutputStream(file);
[Link](m);
[Link](); [Link]();
[Link]("Movie object written to [Link]");
} catch (Exception e) {
[Link](e);}}}
Output:
Lab-39. Write a program to create a class student with data member roll and name. sort the 10
objects of this class on the basis of name.
Code:
package rabina_lab;
import [Link];
import [Link];
class Student {
int roll;
String name;
Student(int roll, String name) {
[Link] = roll;
[Link] = name;
}
void display() {
[Link]("Roll: " + roll + " Name: " + name);
}
}
public class lab39{
public static void main(String[] args) {
Student[] s = {
new Student(1, "Ram"),new Student(2, "Sita"), new Student(3, "Aman"), new
Student(4, "Bikash"),new Student(5, "Hari"),new Student(6, "Gita"), new Student(7, "Nabin"),
new Student(8, "Kiran")new Student(9, "Anita"), new Student(10, "Rohan")
};

[Link](s, [Link](st -> [Link]));

[Link]("Students sorted by name:");


for (Student st : s) {

[Link](); } }}
Output:
Lab-40. Create a class named Book with instance variables tile and price. Add a method named
setVar to pass parameters for title and price. Add another method named showVar to display
values of these variables. Now in main(), declare 4 objects of book and display the records of
book that starts with “Java”.
Code:
class Book {
String title;
double price;
void setVar(String title, double price) {
[Link] = title;
[Link] = price;
}
void showVar() {
[Link]("Title: " + title);
[Link]("Price: " + price);
[Link]();}
public class lab40{
public static void main(String[] args) {
Book b1 = new Book();
Book b2 = new Book();
Book b3 = new Book();
Book b4 = new Book();
[Link]("Java Programming", 500);
[Link]("C Programming", 400);
[Link]("Java Complete Reference", 800);
[Link]("Python Basics", 600);
Book[] books = {b1, b2, b3, b4};
[Link]("Books starting with 'Java':\n");
for (Book b : books) {
if ([Link]("Java")) {
[Link]();}}}}

Output:
Lab-41. Create a Shape interface having methods area() and perimeter(). Create two subclasses,
Circle and Rectangle that implements the Shape interface. Create a class Sample with main
method and demonstrate the area and perimeters of both the Shape classes. You need to handle
the values of length, breadth and radius in respective classes to calculate their area and
perimeter.
Code:
package rabina_lab;
interface Shape {
double area();
double perimeter();
}
class Circle implements Shape {
private double radius;
public Circle(double radius) {
[Link] = radius;
}
@Override
public double area() {
return [Link] * radius * radius;
}
@Override
public double perimeter() {
return 2 * [Link] * radius;
}class Rectangle implements Shape {
private double length;
private double breadth;
public Rectangle(double length, double breadth) {
[Link] = length;
[Link] = breadth;
}
@Override
public double area() {
return length * breadth;
}
@Override
public double perimeter() {
return 2 * (length + breadth);}}
public class lab41 {
public static void main(String[] args) {
Shape myCircle = new Circle(5.0
Shape myRectangle = new Rectangle(4.0, 6.0);
[Link]("--- Circle Properties ---");
[Link]("Area: %.2f\n", [Link]());
[Link]("Perimeter: %.2f\n\n", [Link]());
[Link]("--- Rectangle Properties ---");
[Link]("Area: %.2f\n", [Link]());
[Link]("Perimeter: %.2f\n", [Link]());
}
}
Output:
Lab-42. Create a class Student with private member variables name and percentage. Write
methods to set, display and return values of private variables in the Student class. Create 10
different objects of the student class, set the values, ad display name of Student who have
highest average_marks in the main method of another class named StudentDemo .
Code:
package rabina_lab;
class Student1{
private String name;
private double percentage;
public void setStudentDetails(String name, double percentage) {
[Link] = name;
[Link] = percentage;
}
public void displayDetails() {
[Link]("Name: " + name + ", Percentage: " + percentage + "%");
}
public String getName() {
return name;
}
public double getPercentage() {
return percentage;
}public class lab42{
public static void main(String[] args) {
Student1[] students = new Student1[10];
for (int i = 0; i < [Link]; i++) {
students[i] = new Student1();
}
students[0].setStudentDetails("Alice", 85.5);
students[1].setStudentDetails("Bob", 92.3);
students[2].setStudentDetails("Charlie", 78.0);
students[3].setStudentDetails("David", 95.6); // Highest
[Link]("--- All Student Records ---");
for (Student1 s : students) {
[Link]();
}
Student1 highestScorer = students[0]; // Assume first student is highest initially
for (int i = 1; i < [Link]; i++) {
if (students[i].getPercentage() > [Link]()) {
highestScorer = students[i]; // Update tracking object

[Link]("\n--- Highest Scorer Results ---");


[Link]("The student with the highest score is: " + [Link]());
[Link]("Score: " + [Link]() + "%");
}
}
Output:
Lab-44. Write a Simple GUI program that displays “hello World” in a text field. The program
should display if user clicks a button.
Code: import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class lab44 {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello World GUI");
[Link](400, 350);
[Link](JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
[Link](new FlowLayout());
JTextField textField = new JTextField(15)
JButton button = new JButton("Click Me");
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Hello World");
} });
[Link](button); [Link](textField); [Link](panel) [Link](true);}}
Output:
Lab-45. Write GUI program using Swing components to find sum and difference of two
numbers. Use two text fields for giving input and a label for output. The program should display
sum if user presses mouse and difference if user release mouse.
Code:
package rabina_lab;
import [Link];
import [Link];
import [Link];
public class lab45 {
public static void main(String[] args) {
JFrame frame = new JFrame("Sum and Difference Calculator");
[Link](400, 150);
[Link](JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
[Link](new FlowLayout());
JTextField num1Field = new JTextField(10);
JTextField num2Field = new JTextField(10);
JLabel resultLabel = new JLabel("Click and hold the window below to see Sum/Diff");
[Link](new MouseListener() {
@Override
public void mousePressed(MouseEvent e) {
try {
double num1 = [Link]([Link]());
double num2 = [Link]([Link]());
double sum = num1 + num2;
[Link]("Sum (Pressed): " + sum);
} catch (NumberFormatException ex) {
[Link]("Error: Please enter valid numbers!");
}
@Override
public void mouseReleased(MouseEvent e) {
try {
double num1 = [Link]([Link]());
double num2 = [Link]([Link]())
double diff = num1 - num2;
[Link]("Difference (Released): " + diff);
} catch (NumberFormatException ex) {
[Link]("Error: Please enter valid numbers!");
}
}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
})
[Link](num1Field); [Link](num2Field); [Link](resultLabel); [Link](panel);
[Link](true);
}
}
Lab-46. You are hired by a reputed software company which is going to design an application
for “Movie Rental System”. Your responsibility is to design a schema named MRS and create
a table named Movie(id, Title, Genre, Language, Length). Write a program to design a GUI to
take input for this table and insert the data into table after clicking OK button.
Code:
import [Link].*;
import [Link].*;
import [Link];
public class MovieRentalGUI extends JFrame {
private JTextField txtId, txtTitle, txtGenre, txtLanguage, txtLength;
private JButton btnOk;
private static final String DB_URL = "jdbc:mysql://localhost:3306/MRS";
private static final String USER = "root";
private static final String PASS = ""; // XAMPP default password is blank
public MovieRentalGUI() {
setTitle("Movie Rental System - XAMPP");
setSize(350, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(6, 2, 10, 10));
add(new JLabel(" Movie ID:"));
txtId = new JTextField(); add(txtId);
add(new JLabel(" Title:"));
txtTitle = new JTextField(); add(txtTitle);
add(new JLabel(" Genre:"));
txtGenre = new JTextField(); add(txtGenre);
add(new JLabel(" Language:"));
txtLanguage = new JTextField(); add(txtLanguage);
add(new JLabel(" Length (mins):"));
txtLength = new JTextField(); add(txtLength);
btnOk = new JButton("OK");
add(btnOk);
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
insertMovieData();
private void insertMovieData() {
String sql = "INSERT INTO Movie (id, Title, Genre, Language, Length) VALUES (?, ?,
?, ?, ?)";
try (Connection conn = [Link](DB_URL, USER, PASS);
PreparedStatement pstmt = [Link](sql)) {
[Link](1, [Link]([Link]().trim()));
[Link](2, [Link]().trim());
[Link](3, [Link]().trim());
[Link](4, [Link]().trim());
[Link](5, [Link]([Link]().trim()));
int rowsInserted = [Link]();
if (rowsInserted > 0) {
[Link](this, "Movie added to XAMPP Database!");
clearFields();}
} catch (NumberFormatException ex) {
[Link](this, "ID and Length must be numbers.", "Input
Error", JOptionPane.ERROR_MESSAGE);
} catch (Exception ex) {
[Link](this, "Connection Failed: " + [Link](),
"Database Error", JOptionPane.ERROR_MESSAGE);
[Link](); } }
private void clearFields();[Link]("");
[Link]("");
[Link]("");
[Link]("");
[Link]("");}
public static void main(String[] args) {
[Link](() -> {
new MovieRentalGUI().setVisible(true);
Output:
Lab-47. Write an applet that reads two numbers from HTML file as parameter and displays the
sum of these two numbers.

Code:

import [Link];

import [Link];

public class lab47 extends Applet {

private double num1;

private double num2;

private double sum;

private String errorMessage = "";

@Override

public void init() {

try {

String param1 = getParameter("number1");

String param2 = getParameter("number2");

if (param1 != null && param2 != null) {

num1 = [Link](param1);

num2 = [Link](param2);

sum = num1 + num2;

} else {

errorMessage = "Parameters missing in HTML file!";

} catch (NumberFormatException e) {

errorMessage = "Invalid number format in HTML parameters!";}

@Override

public void paint(Graphics g) {


if (![Link]("")) {

// If something went wrong, draw the error message

[Link](errorMessage, 20, 40);

} else {

[Link]("First Number: " + num1, 20, 40);

[Link]("Second Number: " + num2, 20, 60);

[Link]("---------------------", 20, 75);

[Link]("The Sum is: " + sum, 20, 95);}}}

<!DOCTYPE html>

<html>

<head>

<title>Run Java Applet</title>

</head>

<body>

<h3>Displaying Applet Results:</h3>

<applet code="[Link]" width="300" height="200"/>

<param name="number1" value="45.5">

<param name="number2" value="20.5">

</applet>

</body>

</html>

Output:
Lab-48. Write a Java program in awt to create form to enter employee information (eid, ename,
salary, gender).

Code:

package rabina_lab;

import [Link];

import [Link];

import [Link].*

public class lab48 {

public static void main(String[] args) {

Frame frame = new Frame("Employee Registration Form");

[Link](300, 350);

[Link](new FlowLayout());

Label lblId = new Label("Employee ID:");

TextField txtId = new TextField(20);

Label lblName = new Label("Employee Name:");

TextField txtName = new TextField(20);

Label lblSalary = new Label("Monthly Salary:");

TextField txtSalary = new TextField(20);

Label lblGender = new Label("Gender: ");

CheckboxGroup genderGroup = new CheckboxGroup();

Checkbox chkMale = new Checkbox("Male", genderGroup, true); // Checked by default

Checkbox chkFemale = new Checkbox("Female", genderGroup, false);

Button btnSubmit = new Button("Save Employee Details");

Label lblOutput = new Label("Form Status: Waiting for submission...");

[Link](new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {


String id = [Link]();

String name = [Link]();

String salary = [Link]();

// Find out which selective radio button option is currently toggled

String gender = [Link]().getLabel();

if([Link]() || [Link]() || [Link]()) {

[Link]("Status: Error! All fields are required.");

} else {

[Link]("Saved: " + name + " (" + id + ") successfully recorded!");

[Link]("--- Logged Employee Entry ---");

[Link]("ID: " + id + "\nName: " + name + "\nSalary: " + salary +


"\nGender: " + gender);

});

[Link](new WindowAdapter() {

@Override

public void windowClosing(WindowEvent e) {

[Link](0);

});

[Link](lblId); [Link](txtId);[Link](lblName);

[Link](txtName);[Link](lblSalary);

[Link](txtSalary);[Link](lblGender);

[Link](chkMale);[Link](chkFemale);
[Link](btnSubmit); [Link](lblOutput); [Link](true);

Output:
Lab-49. Write a Java program to demonstrate FlowLayout

Code:

package rabina_lab;

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class lab49 {

public static void main(String[] args) {

JFrame frame = new JFrame("FlowLayout Demonstration");

[Link](400, 150);

[Link](JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();

[Link](new FlowLayout([Link], 10, 10));

JLabel label = new JLabel("Components arranged in a row:");

JButton btn1 = new JButton("Button 1");

JButton btn2 = new JButton("Button 2");

JButton btn3 = new JButton("Button 3");

JButton btn4 = new JButton("Button 4");

[Link](label);[Link](btn1);

[Link](btn2); [Link](btn3);[Link](btn4);

[Link](panel);

[Link](true);

Output:
Lab-50. Write a Java Program to demonstrate GridLayout

Code:

import [Link];

import [Link];

import [Link];

import [Link];

public class lab50 {

public static void main(String[] args) {

JFrame frame = new JFrame("GridLayout Demonstration");

[Link](350, 250);

[Link](JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();

[Link](new GridLayout(3, 2, 5, 5));

JButton btn1 = new JButton("Button 1 (R1, C1)");

JButton btn2 = new JButton("Button 2 (R1, C2)");

JButton btn3 = new JButton("Button 3 (R2, C1)");

JButton btn4 = new JButton("Button 4 (R2, C2)");

JButton btn5 = new JButton("Button 5 (R3, C1)");

JButton btn6 = new JButton("Button 6 (R3, C2)");

[Link](btn1); [Link](btn2);

[Link](btn3); [Link](btn4);

[Link](btn5); [Link](btn6);

[Link](panel);

[Link](true);}}

Output:
Lab-51. Write a program using swing components to add two numbers. Use text fields
for inputs and output. Your program should display the result when the user presses a
button.
Code:
package rabina_lab;
import [Link].*;
import [Link];
import [Link];
import [Link];
public class lab51 {
public static void main(String[] args)
JFrame frame = new JFrame("Addition Calculator");
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
[Link](new FlowLayout());
JLabel label1 = new JLabel("First Number:");
JTextField num1Field = new JTextField(15);
JLabel label2 = new JLabel("Second Number:");
JTextField num2Field = new JTextField(15);
JLabel label3 = new JLabel("Result:");
JTextField resultField = new JTextField(15);
[Link](false); // Make output field read-only
JButton addButton = new JButton("Add Numbers");
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
// Extract text strings and parse them into decimals
double num1 = [Link]([Link]());
double num2 = [Link]([Link]());
double sum = num1 + num2;

[Link]([Link](sum));
} catch (NumberFormatException ex) {
[Link]("Invalid Input!");
}
}
});
[Link](label1); [Link](num1Field); [Link](label2);
[Link](num2Field); [Link](addButton); [Link](label3);
[Link](resultField);
[Link](panel);[Link](true);}}
Output:
Lab-52. Write a Java program who live in Kathmandu district, assuming that the student table has four
attributes (ID, name, district and age).
Code:
package rabina_lab;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class lab52 {
private static final String URL = "jdbc:mysql://localhost:3306/school_db";
private static final String USER = "root";
private static final String PASSWORD = "";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT ID, name, district, age FROM student WHERE district = ?";
try {
[Link]("[Link]");
conn = [Link](URL, USER, PASSWORD);
pstmt = [Link](sql);
[Link](1, "Kathmandu");
rs = [Link]();
[Link]("--- Students Living in Kathmandu ---");
[Link]("ID\tName\t\tDistrict\tAge");
[Link]("------------------------------------------------");
boolean recordsFound = false;
while ([Link]()) {
recordsFound = true;
int id = [Link]("ID");
String name = [Link]("name");
String district = [Link]("district");
int age = [Link]("age");

[Link](id + "\t" + name + "\t\t" + district + "\t" + age);


}
if (!recordsFound) {
[Link]("No student records found matching Kathmandu district.");
}
} catch (ClassNotFoundException e) {
[Link]("Driver Error: Ensure MySQL JDBC Driver is added to project libraries.");
[Link]();
} catch (SQLException e) {
[Link]("Database Error: Verification or query process failed.");
[Link]();
} finally {
try {
if (rs != null) [Link]();
if (pstmt != null) [Link]();
if (conn != null) [Link]();
} catch (SQLException e) {
[Link](); }}
Output:
Lab-53. Write a Java program to insert one record to database. Assume your own database and
table.
Code:

package rabina_lab;

import [Link].*;

public class lab53 {

private static final String URL = "jdbc:mysql://localhost:3306/school_db";

private static final String USER = "root";

private static final String PASSWORD = "";

public static void main(String[] args) {

Connection conn = null;

PreparedStatement pstmt = null;

String sql = "INSERT INTO student (ID, name, district, age) VALUES (?, ?, ?, ?)";

try {

[Link]("[Link]");

[Link]("Connecting to database...");

conn = [Link](URL, USER, PASSWORD);

pstmt = [Link](sql);

[Link](1, 3);

[Link](2, "Rohan");

[Link](3, "Lalitpur");

[Link](4, 22);

int rowsInserted = [Link]();

if (rowsInserted > 0) {

[Link](" Success! One student record was inserted into the


database.");

} } catch (ClassNotFoundException e) {
[Link]("Driver Error: Ensure the MySQL Connector dependency is
configured properly.");

[Link]();

} catch (SQLException e) {

[Link]("Database Error: Failed to insert record. Check if ID already


exists.");

[Link]();

} finally {

try {

if (pstmt != null) [Link]();

if (conn != null) [Link]();

[Link]("Database connections closed.");

} catch (SQLException e) {

[Link](); }

Output:
Lab-54. Write a Java Program to delete a record from database. Assume your own database and table.

Code:

import [Link];

import [Link];

import [Link];

import [Link]

public class lab54 {

private static final String URL = "jdbc:mysql://localhost:3306/school_db";

private static final String USER = "root";

private static final String PASSWORD = "";

public static void main(String[] args) {

Connection conn = null;

PreparedStatement pstmt = null;

String sql = "DELETE FROM student WHERE ID = ?";

try {

[Link]("[Link]");

[Link]("Connecting to database...");

conn = [Link](URL, USER, PASSWORD);

pstmt = [Link](sql);

int targetIdToDelete = 2;

[Link](1, targetIdToDelete);

int rowsDeleted = [Link]();

if (rowsDeleted > 0) {

[Link](" Success! Student record with ID " + targetIdToDelete + " was


deleted.");

} else {

[Link](" Warning: No student record found with ID " + targetIdToDelete +


".");

}
} catch (ClassNotFoundException e) {

[Link]("Driver Error: Ensure the MySQL Connector dependency is configured


properly.");

[Link]();

} catch (SQLException e) {

[Link]("Database Error: Execution failed during deletion protocol.");

[Link]();

} finally {

try {

if (pstmt != null) [Link]();

if (conn != null) [Link]();

[Link]("Database connections closed cleanly.");

} catch (SQLException e) {

[Link]();

Output:
Lab-55. Create a servlet that displays two text boxes in web browser, reads number entered in
first text box, calculates factorial and displays it in second textfield.

Code:
package [Link];

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

@WebServlet("/FactorialServlet")

public class FactorialServlet extends HttpServlet {

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

[Link]("text/html;charset=UTF-8");

PrintWriter out = [Link]();

String numParam = [Link]("number");

String result = "";

if (numParam != null && ![Link]()) {

try {

long num = [Link]([Link]());

if (num < 0) {

result = "Error: Negative number";

} else {

result = [Link](factorial(num));

} catch (NumberFormatException e) {

result = "Error: Invalid input";

[Link]("<!DOCTYPE html>"); [Link]("<html>");


[Link]("<form method='get' action='FactorialServlet'>");

[Link]("Enter Number: <input type='text' name='number' value='"

+ (numParam != null ? numParam : "") + "'/>");

[Link]("<input type='submit' value='Calculate'/>");

[Link]("</form>");

[Link]("<br/>");

[Link]("Factorial Result: <input type='text' value='" + result + "' readonly/>");

[Link]("</body>");

[Link]("</html>");}

private long factorial(long n) {

if (n == 0 || n == 1) return 1;

return n * factorial(n - 1); }}


Lab-56. Write a servlet program that reads two numbers from web browser and finds sum of
these two numbers.

Code:

package [Link];

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

@WebServlet("/SumServlet")

public class SumServlet extends HttpServlet {

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

[Link]("text/html;charset=UTF-8");

PrintWriter out = [Link]();

String num1Param = [Link]("num1");

String num2Param = [Link]("num2");

String result = "";

if (num1Param != null && num2Param != null &&

![Link]() && ![Link]()) {

try {

double num1 = [Link]([Link]());

double num2 = [Link]([Link]());

result = [Link](num1 + num2);

} catch (NumberFormatException e) {

result = "Error: Invalid input";}}

[Link]("<!DOCTYPE html>"); [Link]("<html>");


[Link]("<head><title>Sum Calculator</title></head>");

[Link]("<body>");[Link]("<h2>Sum of Two Numbers</h2>");

[Link]("<form method='get' action='SumServlet'>");

[Link]("Number 1: <input type='text' name='num1' value='"

+ (num1Param != null ? num1Param : "") + "'/><br/><br/>");

[Link]("Number 2: <input type='text' name='num2' value='"

+ (num2Param != null ? num2Param : "") + "'/><br/><br/>");

[Link]("<input type='submit' value='Calculate Sum'/>");

[Link]("</form>");

[Link]("<br/>");

[Link]("Sum Result: <input type='text' value='" + result + "' readonly/>");

[Link]("</body>");

[Link]("</html>"); }}

Output:
Lab-56. Write a JSP program display text “Apache Tomcat” 10 times.

Code:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-


8"%>

<!DOCTYPE html>

<html>

<head>

<title>Apache Tomcat</title>

</head>

<body>

<h2>Displaying Apache Tomcat 10 times:</h2>

<% for(int i = 1; i <= 10; i++) { %>

<p><%= i %>. Apache Tomcat</p>

<% } %>

</body>

</html>

Output:
Lab-58. How exceptions can be handled in JSP scripts? Explain with suitable JSP script

Code:

<%@ page language="java" contentType="text/html; charset=UTF-8" errorPage="[Link]"


%>

<!DOCTYPE html>

<html>

<head><title>Division Example</title></head>

<body><h2>Division Calculator</h2>

<form method="get" action="[Link]">

Number 1: <input type="text" name="num1" /><br/><br/>

Number 2: <input type="text" name="num2" /><br/><br/>

<input type="submit" value="Divide" />

</form> <%

String n1 = [Link]("num1");

String n2 = [Link]("num2");

if(n1 != null && n2 != null && ![Link]() && ![Link]()) {

try {

int num1 = [Link](n1);

int num2 = [Link](n2);

if(num2 == 0) {

throw new ArithmeticException("Cannot divide by zero"); }

int result = num1 / num2;

[Link]("<h3>Result: " + result + "</h3>");

} catch(ArithmeticException e) {

[Link]("<h3 style='color:red'>Arithmetic Error: " + [Link]() + "</h3>");

} catch(NumberFormatException e) {

[Link]("<h3 style='color:red'>Error: Please enter valid numbers</h3>"); } }


%>
</body></html>

[Link]

<%@ page language="java" contentType="text/html; charset=UTF-8" isErrorPage="true" %>

<!DOCTYPE html><html>

<head><title>Error Page</title></head>

<body>

<h2 style="color:red">An Error Occurred!</h2>

<p>Error Message: <%= [Link]() %></p>

<p><a href="[Link]">Go Back</a></p></body></html>

Output:

You might also like