JAVA PROGRAMMING
PRACTICAL FILE
CSE504-22
Submitted by:- Submitted to:-
AkashdeepSingh Anchal
Btech cse
1
72212236
INDEX
S.NO LIST OF EXPERIMENT
1. Write a Java Program of create Classes and Objects
a) Write a Java Program to use data types, flow control statements .
2. b) Write the Java program to find the greatest number among three
numbers
a) Write a Java Program to use constructors, passing arguments to
constructors
b) Write a Java program to implement Switch statements to perform
3. the
following operations : 1) Addition 2) subtraction 3) multiplication
4) division
Write a Java program to initialize an array of integers, populate it
4
with values, and access elements by index.
Write a program to perform following operations on strings:
1) Compare two strings.
2) Count string length.
3) Convert upper case to lower case & vice versa.
5. 4) Concatenate two strings.
5) Print a substring.
c) Write a Java method to count all words in a string
Write a Java program to illustrate multi-level inheritance where a
6. subclass inherits from another subclass. Create a hierarchy of classes
to showcase the concept
Write a program to implement Multiple Inheritance using interface
7.
Write a program that demonstrates method overloading to perform
basic arithmetic operations such as addition, subtraction,
8.
multiplication, and division with different numbers of arguments
(e.g., two numbers, three numbers).
Write a base class and a derived class where a method in the derived
class overrides a method in the base class to provide a specific
9.
implementation (e.g., a Vehicle class with a move method, and a
Car class overriding the move method).
Construct a program to design a package in Java
10.
Write a Java program to handle following exceptions:
1) Divide by Zero Exception.
11
2) Array Index Out Of B bound Exception
Write a Java program to create a thread by extending the Thread
12.
class or implementing the Runnable interface
Write a Java program to design an applet to draw a square with
13.
different color lines
2
Write a Java program to design an applet that performs the basic
14. functionality of a calculator
Write a Java program to create a GUI with basic AWT components
15. including a label, text field, button, checkbox, and radio button.
Create a simple application that arranges components in a left-to-
right flow.Experiment with different alignment options
16 (FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT).
Create an application that uses BorderLayout to place components
17
in the five regions (North, South, East, West, Center).
Create a Java program to handle action events from GUI
18.
components like buttons using ActionListener interface.
Implement a Java program to copy contents from one file to another
using file input and output streams (FileInputStream,
19.
FileOutputStream).
Write a program to create a JDBC connection.
20
3
1) Write a Java Program of create Classes and Objects
class Car {
String model;
String color;
int year;
void displayInfo() {
System.out.println("Model: " + model);
System.out.println("Colour: " + color);
System.out.println("Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
car1.model = "Toyota Camry";
car1.color = "Red";
car1.year = 2020;
Car car2 = new Car();
car2.model = "Honda Accord";
car2.color = "Blue";
car2.year = 2021;
car1.displayInfo();
car2.displayInfo();
}
}
Output
2) A. Write a Java Program to use data types, flow control
statements .
4
B. Write the Java program to find the greatest number among
three numbers
A ) public class DataTypesAndFlowControl {
public static void main(String[] args) {
// Using different data types
int age = 25; // Integer
double height = 5.9; // Double
char initial = 'A'; // Character
String name = "Alice"; // String
boolean isStudent = true; // Boolean
// Displaying the values
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Initial: " + initial);
System.out.println("Is Student: " + isStudent);
// Flow control using if-else
if (age < 18) {
System.out.println(name + " is a minor.");
} else {
System.out.println(name + " is an adult.");
}
// Flow control using switch-case
int choice = 2; // Hard-coded choice for demonstration
switch (choice) {
case 1:
System.out.println("You chose option 1.");
break;
case 2:
System.out.println("You chose option 2.");
break;
case 3:
System.out.println("You chose option 3.");
break;
default:2
System.out.println("Invalid choice.");
}
}
}
5
OUTPUT
B) public class GreatestNumber {
public static void main(String[] args) {
// Hard-coded numbers for demonstration
int num1 = 10;
int num2 = 25;
int num3 = 15;
// Determine the greatest number
int greatest;
if (num1 >= num2 && num1 >= num3) {
greatest = num1;
} else if (num2 >= num1 && num2 >= num3) {
greatest = num2;
} else {
greatest = num3;
}
// Display the result
System.out.println("The greatest number is: " + greatest);
}
}
OUTPUT
B)
6
3) A. Write a Java Program to use constructors, passing
arguments to constructors
B. Write a Java program to implement Switch statements to
perform the
following operations :
1) Addition 2) subtraction 3) multiplication 4) division
A)class Rectangle {
private double length;
private double width;
// Constructor that takes arguments
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Method to calculate area
public double calculateArea() {
return length * width;
}
// Method to calculate perimeter
public double calculatePerimeter() {
return 2 * (length + width);
}
}
public class ConstructorExample {
public static void main(String[] args) {
// Creating an object of Rectangle using the constructor
Rectangle rect1 = new Rectangle(5.0, 3.0);
Rectangle rect2 = new Rectangle(7.5, 4.5);
// Displaying area and perimeter for rect1
7
System.out.println("Rectangle 1: ");
System.out.println("Area: " + rect1.calculateArea());
System.out.println("Perimeter: " + rect1.calculatePerimeter());
// Displaying area and perimeter for rect2
System.out.println("Rectangle 2: ");
System.out.println("Area: " + rect2.calculateArea());
System.out.println("Perimeter: " + rect2.calculatePerimeter());
}
}
B)public class ArithmeticOperations {
public static void main(String[] args) {
double num1 = 10.0;
double num2 = 5.0;
int choice = 1;
double result;
switch (choice) {
case 1:
result = num1 + num2;
System.out.println("Addition: " + result);
break;
case 2:
result = num1 - num2;
System.out.println("Subtraction: " + result);
break;
case 3:
result = num1 * num2;
System.out.println("Multiplication: " + result);
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
System.out.println("Division: " + result);
} else {
System.out.println("Error: Division by zero is not allowed.");
}
break;
default:
System.out.println("Invalid choice.");
}
}
8
Output
4) Write a Java program to initialize an array of integers,
populate it with values, and access elements by index.
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
System.out.println("Element at index 0: " + numbers[0]);
System.out.println("Element at index 1: " + numbers[1]);
System.out.println("Element at index 2: " + numbers[2]);
System.out.println("Element at index 3: " + numbers[3]);
System.out.println("Element at index 4: " + numbers[4]);
}
}
Output
9
10
5) Write a program to perform following operations on
strings:
1) Compare two strings.
2) Count string length.
3) Convert upper case to lower case & vice versa.
4) Concatenate two strings.
5) Print a substring.
6) Write a Java method to count all words in a string
public class StringOperations {
public static void main(String[] args) {
String str1 = "Hello World";
String str2 = "hello world";
System.out.println("1. Compare two strings: " + str1.equalsIgnoreCase(str2));
System.out.println("2. Count string length: " + str1.length());
System.out.println("3. Convert upper case to lower case: " + str1.toLowerCase());
System.out.println(" Convert lower case to upper case: " + str2.toUpperCase());
System.out.println("4. Concatenate two strings: " + str1 + " " + str2);
System.out.println("5. Print a substring: " + str1.substring(0, 5));
System.out.println("6. Count all words in a string: " + countWords(str1));
}
public static int countWords(String str) {
if (str == null || str.isEmpty()) {
return 0;
}
String[] words = str.trim().split("\\s+");
return words.length;
}
}
Output
11
6) Write a Java program to illustrate multi-level
inheritance where a subclass inherits from another
subclass. Create a hierarchy of classes to showcase the
concept
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Mammal extends Animal {
void walk() {
System.out.println("Mammal walks");
}
}
class Dog extends Mammal {
void bark() {
System.out.println("Dog barks");
}
}
public class MultiLevelInheritance {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.walk();
dog.bark();
}
}
Output
12
7) Write a program to implement Multiple Inheritance using
interface
interface Animal {
void eat();
}
interface Pet {
void play();
}
class Dog implements Animal, Pet {
public void eat() {
System.out.println("Dog eats");
}
public void play() {
System.out.println("Dog plays");
}
}
public class MultipleInheritance {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.play();
}
}
Output
8) Write a program that demonstrates method overloading
to perform basic arithmetic operations such as addition,
subtraction, multiplication, and division with different
numbers of arguments (e.g., two numbers, three numbers).
public class ArithmeticOperations {
public int add(int a, int b) {
return a + b;
13
}
public int add(int a, int b, int c) {
return a + b + c;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
public double divide(int a, int b) {
return (double) a / b;
}
public static void main(String[] args) {
ArithmeticOperations operations = new ArithmeticOperations();
System.out.println("Addition of 2 numbers: " + operations.add(5, 10));
System.out.println("Addition of 3 numbers: " + operations.add(5, 10, 15));
System.out.println("Subtraction: " + operations.subtract(10, 5));
System.out.println("Multiplication: " + operations.multiply(5, 4));
System.out.println("Division: " + operations.divide(20, 5));
}
}
Output
9) Write a base class and a derived class where a method in
the derived class overrides a method in the base class to
provide a specific implementation (e.g., a Vehicle class with a
move method, and a Car class overriding the move method).
class Vehicle {
public String move() {
14
return "The vehicle moves.";
}
}
class Car extends Vehicle {
@Override
public String move() {
return "The car drives on the road.";
}
}
public class Main {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
Car car = new Car();
System.out.println(vehicle.move());
System.out.println(car.move());
}
}
Output
10) Construct a program to design a package in Java
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double area() {
return Math.PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Circle circle = new Circle(5);
System.out.println("Area of the circle: " + circle.area());
}
15
}
Output
11) Write a Java program to handle following exceptions:
1) Divide by Zero Exception.
2) Array Index Out Of B bound Exception
import java.util.Scanner;
public class ExceptionHandling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Divide by Zero Exception
try {
System.out.print("Enter numerator: ");
int numerator = scanner.nextInt();
System.out.print("Enter denominator: ");
int denominator = scanner.nextInt();
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
// Array Index Out Of Bounds Exception
int[] array = {1, 2, 3};
try {
System.out.print("Enter array index: ");
int index = scanner.nextInt();
System.out.println("Array value: " + array[index]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index out of bounds.");
}
scanner.close();
}
}
16
12) Write a Java program to create a thread by extending
the Thread class or implementing the Runnable interface
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
13) Write a Java program to design an applet to draw a
square with different color lines
import java.applet.Applet;
import java.awt.*;
public class SquareApplet extends Applet {
public void paint(Graphics g) {
g.setColor(Color.RED);
g.drawLine(50, 50, 150, 50);
17
g.setColor(Color.GREEN);
g.drawLine(150, 50, 150, 150);
g.setColor(Color.BLUE);
g.drawLine(150, 150, 50, 150);
g.setColor(Color.);
g.drawLine(50, 150, 50, 50);
}
}
Output
14) Write a Java program to design an applet that performs
the basic functionality of a calculator
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class CalculatorApplet extends Applet implements ActionListener {
TextField t1, t2, t3;
Button add, sub;
public void init() {
t1 = new TextField(10);
t2 = new TextField(10);
t3 = new TextField(10);
add = new Button("+");
sub = new Button("-");
18
add(t1);
add(t2);
add(add);
add(sub);
add(t3);
add.addActionListener(this);
sub.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
if (e.getSource() == add) {
t3.setText(String.valueOf(num1 + num2));
} else {
t3.setText(String.valueOf(num1 - num2));
}
19
15) Write a Java program to create a GUI with basic AWT
components including a label, text field, button, checkbox,
and radio button.
import java.awt.*;
import java.awt.event.*;
public class BasicAWTComponents {
public static void main(String[] args) {
// Create a new Frame with the title "AWT Components"
Frame f = new Frame("AWT Components");
// Create a Label, TextField, Button, Checkbox, and CheckboxGroup for radio buttons
Label label = new Label("Enter Text:");
TextField textField = new TextField(20);
Button button = new Button("Submit");
Checkbox checkbox = new Checkbox("Accept Terms");
// Create a CheckboxGroup to group the radio buttons
CheckboxGroup group = new CheckboxGroup();
Checkbox radio1 = new Checkbox("Option 1", group, false); // First radio button
Checkbox radio2 = new Checkbox("Option 2", group, false); // Second radio button
// Set layout for the frame
f.setLayout(new FlowLayout());
// Add components to the frame
f.add(label);
f.add(textField);
f.add(button);
f.add(checkbox);
f.add(radio1);
f.add(radio2);
// Set the frame size and make it visible
f.setSize(300, 200);
f.setVisible(true);
// Add a window listener to handle the window closing event
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0); // Exit the application when the window is closed
}
});
}
}
20
16 ) Create a simple application that arranges components in
a left-to-right flow.Experiment with different alignment
options (FlowLayout.LEFT, FlowLayout.CENTER,
FlowLayout.RIGHT).
import java.awt.*;
import java.awt.event.*;
public class FlowLayoutExample {
public static void main(String[] args) {
Frame f = new Frame("FlowLayout Example");
f.setLayout(new FlowLayout(FlowLayout.LEFT));
f.add(new Button("Button 1"));
f.add(new Button("Button 2"));
f.add(new Button("Button 3"));
f.setSize(300, 200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
Output
21
17) Create an application that uses BorderLayout to place
components in the five regions (North, South, East, West,
Center)
import java.awt.*;
import java.awt.event.*;
public class BorderLayoutExample {
public static void main(String[] args) {
Frame f = new Frame("BorderLayout Example");
f.setLayout(new BorderLayout());
f.add(new Button("North"), BorderLayout.NORTH);
f.add(new Button("South"), BorderLayout.SOUTH);
f.add(new Button("East"), BorderLayout.EAST);
f.add(new Button("West"), BorderLayout.WEST);
f.add(new Button("Center"), BorderLayout.CENTER);
f .setSize(400, 300);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
Output
18) Create a Java program to handle action events from GUI
components like buttons using ActionListener interface.
import java.awt.*;
import java.awt.event.*;
public class ActionEventExample {
public static void main(String[] args) {
Frame f = new Frame("ActionEvent Example");
22
Button button = new Button("Click Me");
Label label = new Label("Button not clicked");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("Button clicked");
}
});
f.setLayout(new FlowLayout());
f.add(button);
f.add(label);
f.setSize(300, 200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
Output
Initially, the GUI window will display:
When you click the Click Me button, the label changes to:
19) implement a Java program to copy contents from one file
to another using file input and output streams
(FileInputStream, FileOutputStream).
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("source.txt");
FileOutputStream fos = new FileOutputStream("destination.txt")) {
byte[] buffer = new byte[1024];
int length;
23
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
System.out.println("File copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
20) Write a program to create a JDBC connection.
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "username";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
if (conn != null) {
System.out.println("Connected to the database.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output
If successful
24