Lab java
Lab java
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];
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];
Output:
Lab-4. Write a Java program reads a character and check if it is alphabet or not.
Code:
package rabina_lab;
import [Link];
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};
}
}
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];
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];
[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]);
Output:
Lab-9. Write Java program to print prime numbers from 300 to 500 using method.
Code:
Code:
import [Link];
Code:
public class lab11 {
public static void main(String[] args) {
int[] arr = new int[]{0,1,2,3};
}
public static int isAllPossibilities(int[] arr){
boolean[] found = new boolean[[Link]];
for(int x : arr){
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;
}
Code:
package rabina_lab;
class ShapeAreaCalculator {
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");
}}
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());
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 {
[Link] = name;
[Link] = birthDate;
return name;
[Link] = name;
return birthDate;
[Link] = birthDate;
[Link] = gpa;
[Link] = graduationYear;
return gpa;
[Link] = gpa;
return graduationYear;
[Link] = graduationYear;
@Override
[Link]();
[Link]();
[Link]();
[Link](3.95);
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;
[Link]("Box Dimensions -> Width: " + [Link] + ", Height: " + [Link] + ", Depth:
" + [Link]);
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;
[Link] = length;
[Link] = breadth;
}}
double height;
super(length, breadth);
[Link] = height;}
[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;
[Link] = length;
[Link] = breadth;
[Link] = height;
double weight;
[Link] = weight;
double costPerKg;
public Shipment(double length, double breadth, double height, double weight, double
costPerKg) {
[Link] = costPerKg;
[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;
this.dim1 = dim1;
this.dim2 = dim2;}
super(length, width);
@Override
}}
super(base, height); }
@Override
Figure dynamicShape;
dynamicShape = rect;
dynamicShape = tri;
Output:
Lab-25. Write a Java program to demonstrate divide by zero exception.
Code:
package rabina_lab;
int denominator = 0;
try {
} catch (ArithmeticException e) {
Output:
Lab-26. Write a Java program to demonstrate array index bounds exception
Code:
package rabina_lab;
try {
} catch (ArrayIndexOutOfBoundsException e) {
Output:
Lab-27. Write a Java Program to demonstrate null exception
Code:
package rabina_lab;
try {
} catch (NullPointerException e) {
Output:
Lab-28. Write a Java program to demonstrate custom exception
Code:
package rabina_lab;
super(message);}
throw new InvalidAgeException("Age " + age + " is too young to vote! Must be 18 or
older.");
} else {
try {
checkVotingEligibility(16);
} catch (InvalidAgeException e) {
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];
try {
int data;
[Link](character); }
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally { try {
if (reader != null) {
[Link]();
} catch (IOException e) {
package rabina_lab;
import [Link];
import [Link];
try{
}catch(IOException e){
[Link]();}finally{
[Link]();
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];
try {
int data;
[Link]("--------------------------------------------")
[Link](character);
[Link]("\n--------------------------------------------");
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
try {
if (reader != null) {
[Link]();
} catch (IOException e) {
Output:
Lab-32. Write a Java program that writes line of text to file using byte stream.
Code:
import [Link];
import [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.";
[Link](converted);
try{
[Link]();
}catch(IOException e){
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];
FileInputStream is = null;
try{
int byteData;
is = new FileInputStream(filePath);
[Link](character);
}catch(FileNotFoundException error){
}catch(IOException e){
}finally{
try{
if (is != null){
[Link]()
}catch(IOException e){
Output:
Lab-34. Write a Java program to read-write objects to file.
package rabina_lab;
import [Link];
import [Link];
String name;
int rollNumber;
double gpa;
[Link] = name;
[Link] = rollNumber;
[Link] = gpa;
[Link]("Student Name: " + name + " | Roll: " + rollNumber + " | GPA: " +
gpa);
[Link](studentToWrite); object!
} catch (IOException e) {
} catch (IOException e) {
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 {
[Link] = size;
[Link]("Stack Overflow! Cannot push " + value + ". The stack is full.");
} else {
top++;
stackArray[top] = value;
if (top < 0) {
} else {
top--;
return poppedValue;}
if (top < 0) {
[Link]("Stack is empty.");
return -1; }
return stackArray[top];}}
[Link](10);[Link](20); [Link](30);
[Link](40);
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](); } }}
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
Code:
import [Link];
import [Link];
@Override
try {
num1 = [Link](param1);
num2 = [Link](param2);
} else {
} catch (NumberFormatException e) {
@Override
} else {
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</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].*
[Link](300, 350);
[Link](new FlowLayout());
[Link](new ActionListener() {
@Override
} else {
});
[Link](new WindowAdapter() {
@Override
[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];
[Link](400, 150);
[Link](JFrame.EXIT_ON_CLOSE);
[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];
[Link](350, 250);
[Link](JFrame.EXIT_ON_CLOSE);
[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");
package rabina_lab;
import [Link].*;
String sql = "INSERT INTO student (ID, name, district, age) VALUES (?, ?, ?, ?)";
try {
[Link]("[Link]");
[Link]("Connecting to database...");
pstmt = [Link](sql);
[Link](1, 3);
[Link](2, "Rohan");
[Link](3, "Lalitpur");
[Link](4, 22);
if (rowsInserted > 0) {
} } catch (ClassNotFoundException e) {
[Link]("Driver Error: Ensure the MySQL Connector dependency is
configured properly.");
[Link]();
} catch (SQLException e) {
[Link]();
} finally {
try {
} 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]
try {
[Link]("[Link]");
[Link]("Connecting to database...");
pstmt = [Link](sql);
int targetIdToDelete = 2;
[Link](1, targetIdToDelete);
if (rowsDeleted > 0) {
} else {
}
} catch (ClassNotFoundException e) {
[Link]();
} catch (SQLException e) {
[Link]();
} finally {
try {
} 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")
@Override
[Link]("text/html;charset=UTF-8");
try {
if (num < 0) {
} else {
result = [Link](factorial(num));
} catch (NumberFormatException e) {
[Link]("</form>");
[Link]("<br/>");
[Link]("</body>");
[Link]("</html>");}
if (n == 0 || n == 1) return 1;
Code:
package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@WebServlet("/SumServlet")
@Override
[Link]("text/html;charset=UTF-8");
try {
} catch (NumberFormatException e) {
[Link]("</form>");
[Link]("<br/>");
[Link]("</body>");
[Link]("</html>"); }}
Output:
Lab-56. Write a JSP program display text “Apache Tomcat” 10 times.
Code:
<!DOCTYPE html>
<html>
<head>
<title>Apache Tomcat</title>
</head>
<body>
<% } %>
</body>
</html>
Output:
Lab-58. How exceptions can be handled in JSP scripts? Explain with suitable JSP script
Code:
<!DOCTYPE html>
<html>
<head><title>Division Example</title></head>
<body><h2>Division Calculator</h2>
</form> <%
String n1 = [Link]("num1");
String n2 = [Link]("num2");
try {
if(num2 == 0) {
} catch(ArithmeticException e) {
} catch(NumberFormatException e) {
[Link]
<!DOCTYPE html><html>
<head><title>Error Page</title></head>
<body>
Output: