Java programs
Java programs
// 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);
// 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);
// Attributes (fields)
String title;
String author;
double price;
// Attributes (fields)
double length;
double width;
Constructor with one parameter called. Length and Width set to 5.0
Rectangle [Length: 5.0, Width: 5.0]
Area of rectangle2: 25.0
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;
}
} 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;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 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();
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();
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;
9)b)Writ a java program to design module to importing packages from other packages
Program:
package mypackage.util;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter methods
public String getName() {
return name;
}
// Display details
public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
import mypackage.util.Utility;
import mypackage.models.Person;
System.out.println();
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;
try {
// Prompt the user to enter their name
System.out.print("Enter your name: ");
String name = reader.readLine(); // Read a line of input
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);
}
// 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));
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.");
}
}
}
// 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;
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);
} 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;
try {
// Outer try block for general exception handling
System.out.println("Outer try block executed.");
} 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.");
}
}
thread1.start();
thread2.start();
thread3.start();
}
}
Output:
Creating single thread...
Single Thread is running.
Label label;
public MouseEventDemo() {
// Frame properties
setTitle("Mouse Event Demo");
setSize(400, 300);
setLayout(null);
setVisible(true);
// MouseListener methods
public void mouseClicked(MouseEvent e) {
label.setText("Mouse clicked at (" + e.getX() + ", " + e.getY() + ")");
}
// MouseMotionListener methods
public void mouseDragged(MouseEvent e) {
label.setText("Mouse dragged to (" + e.getX() + ", " + e.getY() + ")");
}
Label label;
public KeyboardEventDemo() {
// Frame properties
setTitle("Keyboard Event Demo");
setSize(400, 300);
setLayout(new FlowLayout());
setVisible(true);
// KeyListener methods
public void keyPressed(KeyEvent e) {
label.setText("Key Pressed: " + KeyEvent.getKeyText(e.getKeyCode()));
}
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);
// ActionListener method
public void actionPerformed(ActionEvent e) {
String inputText = textField.getText();
label.setText("You entered: " + inputText);
}
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);
// ActionListener method
public void actionPerformed(ActionEvent e) {
StringBuilder result = new StringBuilder("Selected: ");
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);
// 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 ");
// 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.");
}
}