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

Java programs

The document contains several Java programs demonstrating various concepts such as string operations, class and object creation, constructors, method overloading, inheritance, method overriding, and package creation. Each program includes code snippets along with their outputs, illustrating how to perform operations like string manipulation, arithmetic calculations, and data storage. The programs serve as practical examples for learning Java programming techniques and object-oriented principles.

Uploaded by

narendernath67
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views41 pages

Java programs

The document contains several Java programs demonstrating various concepts such as string operations, class and object creation, constructors, method overloading, inheritance, method overriding, and package creation. Each program includes code snippets along with their outputs, illustrating how to perform operations like string manipulation, arithmetic calculations, and data storage. The programs serve as practical examples for learning Java programming techniques and object-oriented principles.

Uploaded by

narendernath67
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 41

JAVA LAB PROGRAMS

2)Write a java program on strings


Program:
public class StringOperations {

public static void main(String[] args) {

// Initializing some strings


String str1 = "Hello";
String str2 = "World";
String str3 = " Java Programming ";

// 1. Concatenate strings
String concatenated = str1 + " " + str2;
System.out.println("Concatenated String: " + concatenated);

// 2. String length
int length = str1.length();
System.out.println("Length of str1: " + length);

// 3. String comparison (case-sensitive)


boolean areEqual = str1.equals(str2);
System.out.println("Are str1 and str2 equal? " + areEqual);

// 4. String comparison (case-insensitive)


boolean areEqualIgnoreCase = str1.equalsIgnoreCase("HELLO");
System.out.println("Are str1 and 'HELLO' equal (ignore case)? " + areEqualIgnoreCase);

// 5. Convert string to uppercase and lowercase


String upperCaseStr = str1.toUpperCase();
String lowerCaseStr = str2.toLowerCase();
System.out.println("Uppercase str1: " + upperCaseStr);
System.out.println("Lowercase str2: " + lowerCaseStr);

// 6. Extract substring
String substring = str3.trim().substring(5, 16); // Removing extra spaces and getting substring
System.out.println("Extracted Substring: " + substring);

// 7. Replace characters
String replacedStr = str3.replace("Java", "Python");
System.out.println("Replaced String: " + replacedStr);

// 8. Check if string contains a specific substring


boolean containsWord = str3.contains("Programming");
System.out.println("Does str3 contain 'Programming'? " + containsWord);

// 9. Check if string starts with a specific prefix


boolean startsWith = str1.startsWith("He");
System.out.println("Does str1 start with 'He'? " + startsWith);

// 10. Check if string ends with a specific suffix


boolean endsWith = str2.endsWith("ld");
System.out.println("Does str2 end with 'ld'? " + endsWith);

// 11. Convert string to char array


char[] charArray = str1.toCharArray();
System.out.print("Characters in str1: ");
for (char c : charArray) {
System.out.print(c + " ");
}
System.out.println();

// 12. String splitting


String sentence = "Java is fun, Java is awesome!";
String[] words = sentence.split(" "); // Split by space
System.out.println("Words in the sentence:");
for (String word : words) {
System.out.println(word);
}

// 13. Trim whitespaces


String trimmedStr = str3.trim();
System.out.println("Trimmed str3: '" + trimmedStr + "'");
}
}
Output:
Concatenated String: Hello World
Length of str1: 5
Are str1 and str2 equal? false
Are str1 and 'HELLO' equal (ignore case)? true
Uppercase str1: HELLO
Lowercase str2: world
Extracted Substring: Programming
Replaced String: Python Programming
Does str3 contain 'Programming'? true
Does str1 start with 'He'? true
Does str2 end with 'ld'? true
Characters in str1: H e l l o
Words in the sentence:
Java
is
fun,
Java
is
awesome!
Trimmed str3: 'Java Programming'
3)write a java program to create class and objects and adding methods.
Program:
// Define the Book class
class Book {

// Attributes (fields)
String title;
String author;
double price;

// Constructor to initialize the Book object


public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}

// Method to display details of the book


public void displayDetails() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Price: $" + price);
}

// Method to apply a discount to the price


public void applyDiscount(double discountPercentage) {
price = price - (price * discountPercentage / 100);
}
// Method to update the price directly
public void setPrice(double newPrice) {
price = newPrice;
}

// Method to get the price of the book


public double getPrice() {
return price;
}
}

public class Main {


public static void main(String[] args) {

// Creating objects (instances) of the Book class


Book book1 = new Book("Java Programming", "John Doe", 29.99);
Book book2 = new Book("Learning Python", "Jane Smith", 34.99);

// Displaying book details before applying discount


System.out.println("Book 1 Details (Before Discount):");
book1.displayDetails();
System.out.println();

System.out.println("Book 2 Details (Before Discount):");


book2.displayDetails();
System.out.println();

// Applying a 10% discount on both books


book1.applyDiscount(10); // Apply 10% discount on book1
book2.applyDiscount(10); // Apply 10% discount on book2

// Displaying book details after applying discount


System.out.println("Book 1 Details (After Discount):");
book1.displayDetails();
System.out.println();

System.out.println("Book 2 Details (After Discount):");


book2.displayDetails();
System.out.println();

// Changing the price of the second book directly


book2.setPrice(24.99);
System.out.println("Book 2 Details (After Direct Price Update):");
book2.displayDetails();
}
}
Output:
Book 1 Details (Before Discount):
Title: Java Programming
Author: John Doe
Price: $29.99

Book 2 Details (Before Discount):


Title: Learning Python
Author: Jane Smith
Price: $34.99

Book 1 Details (After Discount):


Title: Java Programming
Author: John Doe
Price: $26.991

Book 2 Details (After Discount):


Title: Learning Python
Author: Jane Smith
Price: $31.491

Book 2 Details (After Direct Price Update):


Title: Learning Python
Author: Jane Smith
Price: $24.99
4)write a java program using constructors and constructor overloading
Program:
// Define the Rectangle class
class Rectangle {

// Attributes (fields)
double length;
double width;

// Default constructor (no parameters)


public Rectangle() {
length = 1.0; // default length
width = 1.0; // default width
System.out.println("Default constructor called. Length and Width set to 1.0");
}

// Constructor with one parameter (for square)


public Rectangle(double side) {
length = side;
width = side;
System.out.println("Constructor with one parameter called. Length and Width set to " + side);
}

// Constructor with two parameters (for rectangle)


public Rectangle(double length, double width) {
this.length = length;
this.width = width;
System.out.println("Constructor with two parameters called. Length: " + length + ", Width: " +
width);
}

// Method to calculate area of the rectangle


public double calculateArea() {
return length * width;
}

// Method to display rectangle details


public void displayDetails() {
System.out.println("Rectangle [Length: " + length + ", Width: " + width + "]");
}
}

public class Main {


public static void main(String[] args) {

// Creating objects using different constructors (constructor overloading)

// Using default constructor


Rectangle rectangle1 = new Rectangle();
rectangle1.displayDetails();
System.out.println("Area of rectangle1: " + rectangle1.calculateArea());
System.out.println();

// Using constructor with one parameter (for square)


Rectangle rectangle2 = new Rectangle(5.0);
rectangle2.displayDetails();
System.out.println("Area of rectangle2: " + rectangle2.calculateArea());
System.out.println();

// Using constructor with two parameters (for rectangle)


Rectangle rectangle3 = new Rectangle(10.0, 4.0);
rectangle3.displayDetails();
System.out.println("Area of rectangle3: " + rectangle3.calculateArea());
System.out.println();
}
}
Output:
Default constructor called. Length and Width set to 1.0
Rectangle [Length: 1.0, Width: 1.0]
Area of rectangle1: 1.0

Constructor with one parameter called. Length and Width set to 5.0
Rectangle [Length: 5.0, Width: 5.0]
Area of rectangle2: 25.0

Constructor with two parameters called. Length: 10.0, Width: 4.0


Rectangle [Length: 10.0, Width: 4.0]
Area of rectangle3: 40.0
5)Write a java program input as command line arguments and perform operation on that data
Program:
public class CommandLineOperations {
public static void main(String[] args) {
// Check if there are any command-line arguments
if (args.length == 0) {
System.out.println("Please provide numbers as command-line arguments.");
return;
}

try {
double sum = 0;
double product = 1;
for (String arg : args) {
// Parse the command-line arguments as doubles
double number = Double.parseDouble(arg);
sum += number;
product *= number;
}

double average = sum / args.length;

// Display the results


System.out.println("Results:");
System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
System.out.println("Average: " + average);

} catch (NumberFormatException e) {
System.out.println("Error: Please enter valid numbers as arguments.");
}
}
}
Output:
Results:
Sum: 10.0
Product: 35.0
Average: 3.3333333333333335
6) write a java program input as command line arguments and update manipulated data in files
Program:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class CommandLineToFile {


public static void main(String[] args) {
// Check if there are any command-line arguments
if (args.length == 0) {
System.out.println("Please provide input data as command-line arguments.");
return;
}

// File to store manipulated data


String outputFileName = "output.txt";

try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName))) {


for (String arg : args) {
// Manipulate the data (e.g., convert to uppercase)
String manipulatedData = arg.toUpperCase();
// Write the manipulated data to the file
writer.write(manipulatedData);
writer.newLine(); // Add a new line for each argument
}

System.out.println("Data successfully written to " + outputFileName);


} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}
}
Output:
HELLO
WORLD
JAVA
PROGRAMMING
6)write a java program using concept of overloading methods
Program:
public class MethodOverloadingExample {

// Method to add two integers


public int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


public int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two doubles


public double add(double a, double b) {
return a + b;
}

// Overloaded method to concatenate two strings


public String add(String a, String b) {
return a + b;
}

public static void main(String[] args) {


MethodOverloadingExample example = new MethodOverloadingExample();
// Calling different overloaded methods
int sumOfTwo = example.add(10, 20);
int sumOfThree = example.add(10, 20, 30);
double sumOfDoubles = example.add(10.5, 20.5);
String concatenatedString = example.add("Hello, ", "World!");

// Display the results


System.out.println("Sum of two integers: " + sumOfTwo);
System.out.println("Sum of three integers: " + sumOfThree);
System.out.println("Sum of two doubles: " + sumOfDoubles);
System.out.println("Concatenated string: " + concatenatedString);
}
}
Output:
Sum of two integers: 30
Sum of three integers: 60
Sum of two doubles: 31.0
Concatenated string: Hello, World!
7)write a java program on inheritance
Program:
// Base class (Superclass)
class Person {
protected String name;
protected int age;

// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}

// Method to display details


public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

// Derived class (Subclass)


class Student extends Person {
private String studentId;
private String course;

// Constructor
public Student(String name, int age, String studentId, String course) {
super(name, age); // Call the constructor of the superclass
this.studentId = studentId;
this.course = course;
}

// Method to display student details (overrides and extends base class method)
public void displayDetails() {
super.displayDetails(); // Call the base class method
System.out.println("Student ID: " + studentId);
System.out.println("Course: " + course);
}
}

// Main class
public class InheritanceExample {
public static void main(String[] args) {
// Create a Person object
Person person = new Person("Alice", 45);
System.out.println("Person Details:");
person.displayDetails();

System.out.println();

// Create a Student object


Student student = new Student("Bob", 20, "S12345", "Computer Science");
System.out.println("Student Details:");
student.displayDetails();
}
}
Output:
Person Details:
Name: Alice
Age: 45

Student Details:
Name: Bob
Age: 20
Student ID: S12345
Course: Computer Science
8)write a java program using the concept of method overriding.
Program:
// Superclass
class Animal {
// Method to be overridden
public void sound() {
System.out.println("Animals make sounds");
}
}

// Subclass 1
class Dog extends Animal {
// Overriding the sound method
public void sound() {
System.out.println("Dog barks");
}
}

// Subclass 2
class Cat extends Animal {
// Overriding the sound method
public void sound() {
System.out.println("Cat meows");
}
}

// Main class
public class MethodOverridingExample {
public static void main(String[] args) {
// Creating objects of each class
Animal genericAnimal = new Animal();
Animal dog = new Dog();
Animal cat = new Cat();

// Calling the sound method for each object


System.out.println("Generic Animal Sound:");
genericAnimal.sound();

System.out.println("\nDog Sound:");
dog.sound();
System.out.println("\nCat Sound:");
cat.sound();
}
}
Output:
Generic Animal Sound:
Animals make sounds

Dog Sound:
Dog barks

Cat Sound:
Cat meows
9)a) Writ a java program to creation of packages
Program:
// File: mypackage/Greetings.java
package mypackage;

public class Greetings {


public void sayHello() {
System.out.println("Hello from the mypackage!");
}

public void sayGoodbye() {


System.out.println("Goodbye from the mypackage!");
}
}
// File: PackageDemo.java
import mypackage.Greetings; // Import the Greetings class from mypackage

public class PackageDemo {


public static void main(String[] args) {
// Create an object of the Greetings class
Greetings greetings = new Greetings();

// Call methods from the Greetings class


greetings.sayHello();
greetings.sayGoodbye();
}
}
Output:
Hello from the mypackage!
Goodbye from the mypackage!

9)b)Writ a java program to design module to importing packages from other packages
Program:
package mypackage.util;

public class Utility {


public static void printMessage(String message) {
System.out.println("Utility Message: " + message);
}
}
package mypackage.models;

public class Person {


private String name;
private int age;

// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}

// Getter methods
public String getName() {
return name;
}

public int getAge() {


return age;
}

// Display details
public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
import mypackage.util.Utility;
import mypackage.models.Person;

public class MainApp {


public static void main(String[] args) {
// Using the Utility class
Utility.printMessage("Welcome to the Java Module Example");

// Using the Person class


Person person = new Person("Alice", 25);
person.displayDetails();
}
}
Output:
Utility Message: Welcome to the Java Module Example
Name: Alice
Age: 25
10)Write a java program on interfaces
Program:
// Define an interface
interface Animal {
void makeSound(); // Abstract method
void eat(); // Abstract method
}

// Implement the interface in the Dog class


class Dog implements Animal {
public void makeSound() {
System.out.println("Dog barks");
}

public void eat() {


System.out.println("Dog eats bones");
}
}

// Implement the interface in the Cat class


class Cat implements Animal {
public void makeSound() {
System.out.println("Cat meows");
}

public void eat() {


System.out.println("Cat eats fish");
}
}
// Main class
public class InterfaceExample {
public static void main(String[] args) {
// Create objects of Dog and Cat
Animal dog = new Dog();
Animal cat = new Cat();

// Call methods on Dog object


System.out.println("Dog:");
dog.makeSound();
dog.eat();

System.out.println();

// Call methods on Cat object


System.out.println("Cat:");
cat.makeSound();
cat.eat();
}
}
Output:
Dog:
Dog barks
Dog eats bones

Cat:
Cat meows
Cat eats fish
11)a)write a java program on I/O streams reading data through keyboard.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class KeyboardInputExample {


public static void main(String[] args) {
// Create a BufferedReader to read data from the keyboard
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

try {
// Prompt the user to enter their name
System.out.print("Enter your name: ");
String name = reader.readLine(); // Read a line of input

// Prompt the user to enter their age


System.out.print("Enter your age: ");
int age = Integer.parseInt(reader.readLine()); // Read and convert input to integer

// Display the input back to the user


System.out.println("Hello, " + name + "! You are " + age + " years old.");
} catch (IOException e) {
System.out.println("An error occurred while reading input: " + e.getMessage());
} catch (NumberFormatException e) {
System.out.println("Invalid input! Please enter a valid number for age.");
}
}
}
Output:
Enter your name: Alice
Enter your age: 25
Hello, Alice! You are 25 years old.

Enter your name: Bob


Enter your age: twenty
Invalid input! Please enter a valid number for age.
11)b)write a java program perform reading and writing operations on files using file streams
Program:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileStreamExample {


public static void main(String[] args) {
// Source and destination file paths
String inputFile = "input.txt";
String outputFile = "output.txt";

FileInputStream fileInputStream = null;


FileOutputStream fileOutputStream = null;

try {
// Open the source file for reading
fileInputStream = new FileInputStream(inputFile);
// Open the destination file for writing
fileOutputStream = new FileOutputStream(outputFile);

System.out.println("Reading data from " + inputFile + " and writing to " + outputFile);

int byteData;
// Read data byte by byte and write it to the destination file
while ((byteData = fileInputStream.read()) != -1) {
fileOutputStream.write(byteData);
}

System.out.println("File copy operation completed successfully!");


} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
} finally {
// Close file streams in the finally block to ensure they are closed even if an exception occurs
try {
if (fileInputStream != null) {
fileInputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
System.out.println("Error closing streams: " + e.getMessage());
}
}
}
}
Output:
Hello, this is a test file.
Reading data from input.txt and writing to output.txt
File copy operation completed successfully!
Hello, this is a test file.
12)a) write a java program to search a student mark percentage based on pin number using ArrayList
Program:
import java.util.ArrayList;
import java.util.Scanner;

// Student class to store student information


class Student {
private String name;
private int pin;
private double percentage;

// Constructor to initialize student information


public Student(String name, int pin, double percentage) {
this.name = name;
this.pin = pin;
this.percentage = percentage;
}

// Getter methods for name, pin, and percentage


public String getName() {
return name;
}

public int getPin() {


return pin;
}

public double getPercentage() {


return percentage;
}

public String toString() {


return "Name: " + name + ", PIN: " + pin + ", Percentage: " + percentage;
}
}

public class StudentSearch {


public static void main(String[] args) {
// Create an ArrayList to store student objects
ArrayList<Student> students = new ArrayList<>();

// Add some sample student data to the list


students.add(new Student("Alice", 101, 85.5));
students.add(new Student("Bob", 102, 90.0));
students.add(new Student("Charlie", 103, 78.5));
students.add(new Student("David", 104, 92.5));

// Create a scanner object to get user input


Scanner scanner = new Scanner(System.in);
// Ask user to enter a PIN number
System.out.print("Enter the PIN number to search for the student's percentage: ");
int pinNumber = scanner.nextInt();

// Search for the student with the given PIN number


boolean found = false;
for (Student student : students) {
if (student.getPin() == pinNumber) {
// Print student's name and percentage
System.out.println("Student Found: " + student);
found = true;
break;
}
}

// If student not found


if (!found) {
System.out.println("No student found with PIN: " + pinNumber);
}

// Close the scanner


scanner.close();
}
}
Output:
Enter the PIN number to search for the student's percentage: 102
Student Found: Name: Bob, PIN: 102, Percentage: 90.0
Enter the PIN number to search for the student's percentage: 105
No student found with PIN: 105
12)b)Write a java program to create linked list to perform delete,insert and update data in linkedlist
with any application.
Program:
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Scanner;

// Student class to represent a student object


class Student {
private String name;
private int id;
private double marks;
// Constructor to initialize student object
public Student(String name, int id, double marks) {
this.name = name;
this.id = id;
this.marks = marks;
}

// Getter and Setter methods


public String getName() {
return name;
}

public int getId() {


return id;
}

public double getMarks() {


return marks;
}

public void setName(String name) {


this.name = name;
}

public void setMarks(double marks) {


this.marks = marks;
}

public String toString() {


return "ID: " + id + ", Name: " + name + ", Marks: " + marks;
}
}

public class LinkedListStudentManagement {


public static void main(String[] args) {
// Create a LinkedList to store students
LinkedList<Student> studentsList = new LinkedList<>();

// Sample data
studentsList.add(new Student("Alice", 101, 85.5));
studentsList.add(new Student("Bob", 102, 90.0));
studentsList.add(new Student("Charlie", 103, 78.0));
studentsList.add(new Student("David", 104, 92.5));

Scanner scanner = new Scanner(System.in);

while (true) {
// Display menu
System.out.println("\nStudent Management System");
System.out.println("1. Display All Students");
System.out.println("2. Insert a Student");
System.out.println("3. Delete a Student");
System.out.println("4. Update Student Marks");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume the newline character after the number input

switch (choice) {
case 1:
// Display all students
displayAllStudents(studentsList);
break;
case 2:
// Insert a new student
System.out.print("Enter Student Name: ");
String name = scanner.nextLine();
System.out.print("Enter Student ID: ");
int id = scanner.nextInt();
System.out.print("Enter Student Marks: ");
double marks = scanner.nextDouble();
studentsList.add(new Student(name, id, marks));
System.out.println("Student added successfully!");
break;
case 3:
// Delete a student by ID
System.out.print("Enter Student ID to delete: ");
int deleteId = scanner.nextInt();
boolean deleted = false;
for (ListIterator<Student> iterator = studentsList.listIterator(); iterator.hasNext(); ) {
Student student = iterator.next();
if (student.getId() == deleteId) {
iterator.remove();
System.out.println("Student with ID " + deleteId + " deleted.");
deleted = true;
break;
}
}
if (!deleted) {
System.out.println("No student found with ID " + deleteId);
}
break;
case 4:
// Update student marks by ID
System.out.print("Enter Student ID to update marks: ");
int updateId = scanner.nextInt();
boolean updated = false;
for (Student student : studentsList) {
if (student.getId() == updateId) {
System.out.print("Enter new marks for Student ID " + updateId + ": ");
double newMarks = scanner.nextDouble();
student.setMarks(newMarks);
System.out.println("Marks updated successfully for Student ID " + updateId);
updated = true;
break;
}
}
if (!updated) {
System.out.println("No student found with ID " + updateId);
}
break;
case 5:
// Exit
System.out.println("Exiting the system...");
scanner.close();
return;
default:
System.out.println("Invalid choice! Please try again.");
}
}
}

// Method to display all students in the LinkedList


public static void displayAllStudents(LinkedList<Student> studentsList) {
if (studentsList.isEmpty()) {
System.out.println("No students to display.");
} else {
System.out.println("\nAll Students:");
for (Student student : studentsList) {
System.out.println(student);
}
}
}
}
Output:
Student Management System
1. Display All Students
2. Insert a Student
3. Delete a Student
4. Update Student Marks
5. Exit
Enter your choice: 1
All Students:
ID: 101, Name: Alice, Marks: 85.5
ID: 102, Name: Bob, Marks: 90.0
ID: 103, Name: Charlie, Marks: 78.0
ID: 104, Name: David, Marks: 92.5
Enter Student Name: John
Enter Student ID: 105
Enter Student Marks: 88.5
Student added successfully!
Enter Student Name: John
Enter Student ID: 105
Enter Student Marks: 88.5
Student added successfully!
Enter Student ID to update marks: 105
Enter new marks for Student ID 105: 91.0
Marks updated successfully for Student ID 105
Enter Student ID to delete: 105
Student with ID 105 deleted.
13)a)Write a java program on try,catch and finally.
Program:
import java.util.Scanner;

public class TryCatchFinallyExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
// Prompt the user to input two numbers
System.out.print("Enter the numerator: ");
int numerator = scanner.nextInt();

System.out.print("Enter the denominator: ");


int denominator = scanner.nextInt();

// Attempt division
int result = numerator / denominator;
System.out.println("The result of division is: " + result);
} catch (ArithmeticException e) {
// This block handles the case when division by zero occurs
System.out.println("Error: Cannot divide by zero!");
} catch (Exception e) {
// This block handles any other exceptions
System.out.println("Error: Something went wrong!");
} finally {
// This block always executes, regardless of whether an exception occurred or not
System.out.println("Execution of the program is complete.");
scanner.close(); // Close the scanner resource
}
}
}
Output:
Enter the numerator: 10
Enter the denominator: 2
The result of division is: 5
Execution of the program is complete.
13)b)Write a java program on multiple catch statements
Program:
import java.util.Scanner;

public class MultipleCatchExample {


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

try {
// Prompt the user to enter two numbers
System.out.print("Enter the numerator: ");
int numerator = scanner.nextInt();
System.out.print("Enter the denominator: ");
int denominator = scanner.nextInt();

// Attempt division
int result = numerator / denominator;
System.out.println("The result of division is: " + result);

// Prompt the user to enter a string


System.out.print("Enter a number as a string: ");
String str = scanner.next();
// Attempt to convert the string to an integer
int num = Integer.parseInt(str);
System.out.println("The string converted to integer is: " + num);

} catch (ArithmeticException e) {
// This block handles division by zero error
System.out.println("Error: Cannot divide by zero!");
} catch (NumberFormatException e) {
// This block handles invalid string-to-integer conversion
System.out.println("Error: Invalid number format. Please enter a valid integer.");
} catch (Exception e) {
// This block handles any other unforeseen errors
System.out.println("Error: An unexpected error occurred.");
} finally {
// This block always executes
System.out.println("Execution of the program is complete.");
scanner.close(); // Close the scanner resource
}
}
}
Output:
Enter the numerator: 10
Enter the denominator: 2
The result of division is: 5
Enter a number as a string: 15
The string converted to integer is: 15
Execution of the program is complete.
13)c)Write a java program on nested try statements
Program:
import java.util.Scanner;

public class NestedTryExample {


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

try {
// Outer try block for general exception handling
System.out.println("Outer try block executed.");

// Prompt for numerator and denominator


System.out.print("Enter the numerator: ");
int numerator = scanner.nextInt();

System.out.print("Enter the denominator: ");


int denominator = scanner.nextInt();

// Inner try block for division operation


try {
// Attempt division
int result = numerator / denominator;
System.out.println("The result of division is: " + result);
} catch (ArithmeticException e) {
// Catch division by zero error in the inner block
System.out.println("Error: Cannot divide by zero in the inner try block.");
}

// Prompt for a string to convert to an integer


System.out.print("Enter a number as a string: ");
String str = scanner.next();

// Inner try block for string-to-integer conversion


try {
// Attempt to convert the string to an integer
int num = Integer.parseInt(str);
System.out.println("The string converted to integer is: " + num);
} catch (NumberFormatException e) {
// Catch invalid number format error in the inner block
System.out.println("Error: Invalid number format. Please enter a valid integer in the inner try
block.");
}

} catch (Exception e) {
// Outer catch block for general exception handling
System.out.println("Error: An unexpected error occurred in the outer try block.");
} finally {
// Finally block always executes
System.out.println("Execution of the program is complete.");
scanner.close(); // Close the scanner resource
}
}
}
Output:
Outer try block executed.
Enter the numerator: 10
Enter the denominator: 2
The result of division is: 5
Enter a number as a string: 15
The string converted to integer is: 15
Execution of the program is complete.
14)a) write a java program on creation of single and multiple threads
Program:
// Single Thread creation by extending Thread class
class SingleThread extends Thread {
public void run() {
System.out.println("Single Thread is running.");
}
}

// Multiple Threads creation by implementing Runnable interface


class MultipleThreads implements Runnable {
private String threadName;

public MultipleThreads(String threadName) {


this.threadName = threadName;
}

public void run() {


System.out.println(threadName + " is running.");
}
}

public class ThreadExample {


public static void main(String[] args) {
// Creating and starting a single thread
System.out.println("Creating single thread...");
SingleThread singleThread = new SingleThread();
singleThread.start();

// Creating and starting multiple threads


System.out.println("\nCreating multiple threads...");
Thread thread1 = new Thread(new MultipleThreads("Thread 1"));
Thread thread2 = new Thread(new MultipleThreads("Thread 2"));
Thread thread3 = new Thread(new MultipleThreads("Thread 3"));

thread1.start();
thread2.start();
thread3.start();
}
}
Output:
Creating single thread...
Single Thread is running.

Creating multiple threads...


Thread 1 is running.
Thread 2 is running.
Thread 3 is running.
14)b)write a java program on adding priorities to multiple threads
Program:
class PriorityThread extends Thread {
private String threadName;

public PriorityThread(String threadName) {


this.threadName = threadName;
}
public void run() {
System.out.println(threadName + " with priority " + getPriority() + " is running.");
}
}

public class ThreadPriorityExample {


public static void main(String[] args) {
// Creating multiple threads with different priorities

// Thread with HIGH priority


Thread thread1 = new PriorityThread("Thread 1");
thread1.setPriority(Thread.MAX_PRIORITY); // Highest priority
// Thread with NORMAL priority
Thread thread2 = new PriorityThread("Thread 2");
thread2.setPriority(Thread.NORM_PRIORITY); // Default priority

// Thread with LOW priority


Thread thread3 = new PriorityThread("Thread 3");
thread3.setPriority(Thread.MIN_PRIORITY); // Lowest priority

// Starting all threads


thread1.start();
thread2.start();
thread3.start();
}
}
Output:
Thread 1 with priority 10 is running.
Thread 2 with priority 5 is running.
Thread 3 with priority 1 is running.
15)a)write a java program on graphics and colors
Program:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class GraphicsAndColorsApplet extends Applet {

// Initialize the applet


public void init() {
setSize(600, 400); // Set the size of the applet
setBackground(Color.WHITE); // Set the background color to white
}

// Paint method to draw on the applet


public void paint(Graphics g) {
super.paint(g);

// Draw a red rectangle


g.setColor(Color.RED);
g.fillRect(50, 50, 200, 100); // x, y, width, height

// Draw a blue oval


g.setColor(Color.BLUE);
g.fillOval(300, 50, 200, 100); // x, y, width, height

// Draw a green line


g.setColor(Color.GREEN);
g.drawLine(50, 200, 550, 200); // start x, start y, end x, end y

// Draw a yellow arc


g.setColor(Color.YELLOW);
g.drawArc(50, 250, 200, 100, 0, 180); // x, y, width, height, start angle, arc angle

// Draw a string of text


g.setColor(Color.BLACK);
g.drawString("Graphics and Colors Example", 200, 350);
}
}
<html>
<body>
<applet code="GraphicsAndColorsApplet.class" width="600" height="400">
</applet>
</body>
</html>
Output:
 A red rectangle is drawn at the top-left corner.
 A blue oval is drawn at the top-right corner.
 A green line is drawn horizontally in the middle.
 A yellow arc is drawn beneath the rectangle.
 The text "Graphics and Colors Example" is displayed at the bottom of the applet.
15)b)write a java applet program simple animations using threads and graphics
Program:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class SimpleAnimationApplet extends Applet implements Runnable {


private int xPos = 0; // X position of the circle
private int yPos = 100; // Y position of the circle
private Thread animator; // The thread for animation

// Initialize the applet


public void init() {
setSize(600, 400); // Set the size of the applet
setBackground(Color.WHITE); // Set the background color
}

// Start the animation


public void start() {
animator = new Thread(this); // Create a new thread
animator.start(); // Start the thread
}

// Run the animation in a loop


public void run() {
while (true) {
xPos += 5; // Move the circle to the right
if (xPos > getWidth()) {
xPos = 0; // Reset position to the left when it goes off-screen
}

repaint(); // Request a redraw of the applet


try {
Thread.sleep(50); // Pause for a while to control animation speed
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

// Draw the graphics (called by repaint())


public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.RED); // Set the color for the circle
g.fillOval(xPos, yPos, 50, 50); // Draw the circle at the current position
}

// Stop the animation


public void stop() {
animator = null; // Stop the thread when the applet is stopped
}
}
<html>
<body>
<applet code="SimpleAnimationApplet.class" width="600" height="400">
</applet>
</body>
</html>
Output:
When the applet is run, a red circle will move from the left side of the window to the right. When the
circle reaches the right edge, it will loop back to the left side and continue moving across the screen.
16)a)write a java awt program to handle mouse events.
import java.awt.*;
import java.awt.event.*;

public class MouseEventDemo extends Frame implements MouseListener, MouseMotionListener {

Label label;

public MouseEventDemo() {
// Frame properties
setTitle("Mouse Event Demo");
setSize(400, 300);
setLayout(null);
setVisible(true);

// Label to display messages


label = new Label("Interact with the mouse!");
label.setBounds(100, 100, 200, 30);
add(label);

// Adding mouse listeners


addMouseListener(this);
addMouseMotionListener(this);

// Window closing event


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

// MouseListener methods
public void mouseClicked(MouseEvent e) {
label.setText("Mouse clicked at (" + e.getX() + ", " + e.getY() + ")");
}

public void mousePressed(MouseEvent e) {


label.setText("Mouse pressed at (" + e.getX() + ", " + e.getY() + ")");
}

public void mouseReleased(MouseEvent e) {


label.setText("Mouse released at (" + e.getX() + ", " + e.getY() + ")");
}

public void mouseEntered(MouseEvent e) {


label.setText("Mouse entered the frame");
}

public void mouseExited(MouseEvent e) {


label.setText("Mouse exited the frame");
}

// MouseMotionListener methods
public void mouseDragged(MouseEvent e) {
label.setText("Mouse dragged to (" + e.getX() + ", " + e.getY() + ")");
}

public void mouseMoved(MouseEvent e) {


label.setText("Mouse moved to (" + e.getX() + ", " + e.getY() + ")");
}

public static void main(String[] args) {


new MouseEventDemo();
}
}
Output:
You can interact with the window to see the different messages displayed based on your mouse actions.
16)b)Write a java awt program to handle keyboard events
Program:
import java.awt.*;
import java.awt.event.*;

public class KeyboardEventDemo extends Frame implements KeyListener {

Label label;

public KeyboardEventDemo() {
// Frame properties
setTitle("Keyboard Event Demo");
setSize(400, 300);
setLayout(new FlowLayout());
setVisible(true);

// Label to display messages


label = new Label("Type something on the keyboard...");
label.setPreferredSize(new Dimension(350, 50));
add(label);

// Adding key listener


addKeyListener(this);

// Window closing event


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

// KeyListener methods
public void keyPressed(KeyEvent e) {
label.setText("Key Pressed: " + KeyEvent.getKeyText(e.getKeyCode()));
}

public void keyReleased(KeyEvent e) {


label.setText("Key Released: " + KeyEvent.getKeyText(e.getKeyCode()));
}

public void keyTyped(KeyEvent e) {


label.setText("Key Typed: " + e.getKeyChar());
}

public static void main(String[] args) {


new KeyboardEventDemo();
}
}
Output:
This program will show you details about the key you pressed, released, or typed, and you can extend it
further for specific actions based on keys.
16)c)write a java awt program to illustrate textfields and button controls
Program:
import java.awt.*;
import java.awt.event.*;

public class TextFieldButtonDemo extends Frame implements ActionListener {

TextField textField;
Button button;
Label label;

public TextFieldButtonDemo() {
// Frame properties
setTitle("TextField and Button Demo");
setSize(400, 200);
setLayout(new FlowLayout());
setVisible(true);

// TextField
textField = new TextField(20);
add(textField);

// Button
button = new Button("Submit");
add(button);

// Label
label = new Label("Enter text and click Submit.");
add(label);

// Add action listener to the button


button.addActionListener(this);

// Window closing event


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

// ActionListener method
public void actionPerformed(ActionEvent e) {
String inputText = textField.getText();
label.setText("You entered: " + inputText);
}

public static void main(String[] args) {


new TextFieldButtonDemo();
}
}
Output:
This program demonstrates the basic usage of TextField and Button controls, along with event
handling in AWT.
16)d)write a java awt program to illustrate checkbox and list control.
Program:
import java.awt.*;
import java.awt.event.*;

public class CheckboxListDemo extends Frame implements ActionListener {

Checkbox checkbox1, checkbox2, checkbox3;


List list;
Button button;
Label label;

public CheckboxListDemo() {
// Frame properties
setTitle("Checkbox and List Demo");
setSize(400, 300);
setLayout(new FlowLayout());
setVisible(true);

// Checkboxes
checkbox1 = new Checkbox("Option 1");
checkbox2 = new Checkbox("Option 2");
checkbox3 = new Checkbox("Option 3");
add(checkbox1);
add(checkbox2);
add(checkbox3);

// List
list = new List(4, false); // Single-selection list
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
add(list);

// Button
button = new Button("Show Selections");
add(button);

// Label
label = new Label("Selections will appear here.");
label.setPreferredSize(new Dimension(350, 30));
add(label);

// Add action listener to the button


button.addActionListener(this);

// Window closing event


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

// ActionListener method
public void actionPerformed(ActionEvent e) {
StringBuilder result = new StringBuilder("Selected: ");

// Add selected checkboxes


if (checkbox1.getState()) result.append("Option 1 ");
if (checkbox2.getState()) result.append("Option 2 ");
if (checkbox3.getState()) result.append("Option 3 ");

// Add selected list item


String selectedItem = list.getSelectedItem();
if (selectedItem != null) {
result.append("| List: ").append(selectedItem);
}

// Update label with selections


label.setText(result.toString());
}

public static void main(String[] args) {


new CheckboxListDemo();
}
}
Output:
This program demonstrates the basic usage of Checkbox and List controls, as well as event handling
for user interaction in AWT.
16)e)write a java application program to illustrate multiple controls
Program:
import java.awt.*;
import java.awt.event.*;

public class MultipleControlsDemo extends Frame implements ActionListener {

TextField textField;
Checkbox checkbox1, checkbox2, checkbox3;
List list;
Button submitButton, clearButton;
Label resultLabel;

public MultipleControlsDemo() {
// Frame properties
setTitle("Multiple Controls Demo");
setSize(500, 400);
setLayout(new FlowLayout());
setVisible(true);

// TextField
Label textFieldLabel = new Label("Enter Name:");
add(textFieldLabel);
textField = new TextField(20);
add(textField);

// Checkboxes
Label checkboxLabel = new Label("Select Options:");
add(checkboxLabel);
checkbox1 = new Checkbox("Option 1");
checkbox2 = new Checkbox("Option 2");
checkbox3 = new Checkbox("Option 3");
add(checkbox1);
add(checkbox2);
add(checkbox3);

// List
Label listLabel = new Label("Select an Item:");
add(listLabel);
list = new List(4, false); // Single-selection list
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
add(list);

// Buttons
submitButton = new Button("Submit");
clearButton = new Button("Clear");
add(submitButton);
add(clearButton);

// Label to display results


resultLabel = new Label("Results will appear here.");
resultLabel.setPreferredSize(new Dimension(450, 30));
add(resultLabel);

// Add action listeners


submitButton.addActionListener(this);
clearButton.addActionListener(this);

// Window closing event


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

// ActionListener method
public void actionPerformed(ActionEvent e) {
if (e.getSource() == submitButton) {
// Collect inputs
StringBuilder result = new StringBuilder("Name: ");
result.append(textField.getText());
result.append(" | Selected Options: ");
if (checkbox1.getState()) result.append("Option 1 ");
if (checkbox2.getState()) result.append("Option 2 ");
if (checkbox3.getState()) result.append("Option 3 ");

String selectedItem = list.getSelectedItem();


result.append(" | Selected Item: ").append(selectedItem != null ? selectedItem : "None");

// Display result
resultLabel.setText(result.toString());
} else if (e.getSource() == clearButton) {
// Clear inputs and label
textField.setText("");
checkbox1.setState(false);
checkbox2.setState(false);
checkbox3.setState(false);
list.deselect(list.getSelectedIndex());
resultLabel.setText("Results will appear here.");
}
}

public static void main(String[] args) {


new MultipleControlsDemo();
}
}
Output:
Interact with the controls by entering text, selecting checkboxes, choosing a list item, and clicking
buttons to see the results.

You might also like