0% found this document useful (0 votes)
10 views22 pages

Java Lab Manual

The document contains multiple Java programming examples demonstrating various concepts such as class creation, method overloading, inheritance, interface implementation, exception handling, GUI components, and event handling. Each section includes code snippets for specific tasks like calculating areas, managing student data, adding complex numbers, and creating applets with checkboxes. The examples illustrate practical applications of Java programming principles and object-oriented design.

Uploaded by

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

Java Lab Manual

The document contains multiple Java programming examples demonstrating various concepts such as class creation, method overloading, inheritance, interface implementation, exception handling, GUI components, and event handling. Each section includes code snippets for specific tasks like calculating areas, managing student data, adding complex numbers, and creating applets with checkboxes. The examples illustrate practical applications of Java programming principles and object-oriented design.

Uploaded by

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

1.

Define a class called Student with the attributes name - reg_number and marks
obtained in four subjects(m1,m2,m3,m4).Write a suitable constructor and methods to
find the total mark obtained by the student and display the details of the student.

public class Student


{
private String name;
private int regNumber;
private int m1;
private int m2;
private int m3;
private int m4;
// Constructor
public Student(String name, int regNumber, int m1, int m2, int m3, int m4)
{
[Link] = name;
[Link] = regNumber;
this.m1 = m1;
this.m2 = m2;
this.m3 = m3;
this.m4 = m4;
}
// Method to calculate total marks
public int calculateTotalMarks()
{
return m1 + m2 + m3 + m4;
}
// Method to display student details
public void displayDetails() {
[Link]("Name: " + name);

1
[Link]("Registration Number: " + regNumber);
[Link]("Marks obtained in m1: " + m1);
[Link]("Marks obtained in m2: " + m2);
[Link]("Marks obtained in m3: " + m3);
[Link]("Marks obtained in m4: " + m4);
[Link]("Total Marks: " + calculateTotalMarks());
}
public static void main(String[] args) {
// Create a new student object
Student student = new Student("John Doe", 12345, 80, 85, 90, 95);
// Display student details
[Link]();
}
}

2
[Link] a Java program to find the area of a square, rectangle and triangle by
(i) Overloading Constructor
public class AreaCalculator
{
private double area;
// Constructor for square
public AreaCalculator(double side)
{
area = side * side;
}
// Constructor for rectangle
public AreaCalculator(double length, double width) {
area = length * width;
}
// Constructor for triangle
public AreaCalculator(double base, double height, String shape) {
area = 0.5 * base * height;
}
// Method to display the area
public void displayArea() {
[Link]("Area: " + area);
}
public static void main(String[] args) {
// Create objects using overloaded constructors
AreaCalculator square = new AreaCalculator(5);
AreaCalculator rectangle = new AreaCalculator(4, 6);
AreaCalculator triangle = new AreaCalculator(3, 4, "triangle");
// Display the areas
[Link]();

3
[Link]();
[Link]();
}
}

(ii) Overloading Method.


public class AreaCalculator {
// Method to calculate the area of a square
public static double calculateArea(double side) {
return side * side;
}
// Method to calculate the area of a rectangle
public static double calculateArea(double length, double width) {
return length * width;
}

// Method to calculate the area of a triangle


public static double calculateArea(double base, double height) {
return 0.5 * base * height;
}
public static void main(String[] args) {
// Calculate and display the areas using overloaded methods
double squareArea = calculateArea(5);
double rectangleArea = calculateArea(4, 6);
double triangleArea = calculateArea(3, 4);
[Link]("Area of square: " + squareArea);
[Link]("Area of rectangle: " + rectangleArea);
[Link]("Area of triangle: " + triangleArea);
}
}

4
[Link] a java program to add two complex numbers. [Use passing object as argument
and return object].
class Complex {
private double real;
private double imaginary;

public Complex(double real, double imaginary) {


[Link] = real;
[Link] = imaginary;
}
// Method to add two complex numbers
public static Complex addComplexNumbers(Complex num1, Complex num2) {
double realSum = [Link] + [Link];
double imaginarySum = [Link] + [Link];
return new Complex(realSum, imaginarySum);
}
// Method to display the complex number
public void displayComplex() {
[Link](real + " + " + imaginary + "i");
}
}
public class ComplexNumberAddition {
public static void main(String[] args) {
// Create two complex numbers
Complex num1 = new Complex(2.5, 3.7);
Complex num2 = new Complex(1.8, 2.9);
// Add two complex numbers
Complex sum = [Link](num1, num2);
// Display the result
[Link]("Sum of complex numbers: ");

5
[Link]();
}
}

6
[Link] a class called Student super with data members name, roll number and age.
Write a suitable constructor and a method output () to display the details.
class Student {
private String name;
private int rollNumber;
private int age;
// Constructor
public Student(String name, int rollNumber, int age) {
[Link] = name;
[Link] = rollNumber;
[Link] = age;
}
// Method to display student details
public void output() {
[Link]("Name: " + name);
[Link]("Roll Number: " + rollNumber);
[Link]("Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
// Create a student object
Student student = new Student("John Doe", 12345, 20);

// Display student details


[Link]();
}
}

7
[Link] another class Student from Student super with data members height and
weight. Write a constructor and a method output () to display the details which
overrides the super class method output().[Apply method Overriding concept].
class StudentSuper {
private String name;
private int rollNumber;
private int age;

public StudentSuper(String name, int rollNumber, int age) {


[Link] = name;
[Link] = rollNumber;
[Link] = age;
}
public void output() {
[Link]("Name: " + name);
[Link]("Roll Number: " + rollNumber);
[Link]("Age: " + age);
}
}
class Student extends StudentSuper {
private double height;
private double weight;
public Student(String name, int rollNumber, int age, double height, double weight) {
super(name, rollNumber, age);
[Link] = height;
[Link] = weight;
}
@Override
public void output() {
[Link]();

8
[Link]("Height: " + height + " cm");
[Link]("Weight: " + weight + " kg");
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student("John Doe", 12345, 20, 170.5, 65.7);
[Link]();
}
}

9
[Link] a java program to create an interface called Demo, which contains a double
type constant, and a method called area () with one double type argument. Implement
the interface to find the area of a circle.
interface Demo {
double PI = 3.14159; // Constant
double area(double radius); // Method
}
class Circle implements Demo {
public double area(double radius) {
return PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Circle circle = new Circle();
double radius = 5.0;
double circleArea = [Link](radius);
[Link]("Area of the circle: " + circleArea);
}
}

[Link] a java program to create a thread using Thread class.


class MyThread extends Thread {
@Override
public void run() {
// Code to be executed in the thread
for (int i = 1; i <= 5; i++) {
[Link]("Thread: " + i);
try {
[Link](1000); // Sleep for 1 second

10
} catch (InterruptedException e) {
[Link]();
}
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
[Link](); // Start the thread
// Code in the main thread
for (int i = 1; i <= 5; i++) {
[Link]("Main: " + i);
try {
[Link](1000); // Sleep for 1 second
} catch (InterruptedException e) {
[Link]();
}
}
}
}

11
[Link] Java inheritance using extends keyword.
// Superclass
class Vehicle {
protected String brand;
public void drive() {
[Link]("Driving the vehicle.");
}
}
// Subclass
class Car extends Vehicle {
private int numberOfSeats;
public Car(String brand, int numberOfSeats) {
[Link] = brand;
[Link] = numberOfSeats;
}
public void displayDetails() {
[Link]("Brand: " + brand);
[Link]("Number of seats: " + numberOfSeats);
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car("Toyota", 4);
[Link](); // Inherited method from the superclass
[Link](); // Method specific to the subclass
}
}

12
9. Create an applet with four Checkboxes with labels MARUTI-800, ZEN, ALTO and
ESTEEM and a Text area object. The program must display the details of the car while
clicking a particular Checkbox.
import [Link].*;
import [Link].*;
import [Link].*;

public class CarDetailsApplet extends Applet implements ItemListener {


Checkbox maruti800, zen, alto, esteem;
TextArea detailsArea;

public void init() {


// Create checkboxes
maruti800 = new Checkbox("MARUTI-800");
zen = new Checkbox("ZEN");
alto = new Checkbox("ALTO");
esteem = new Checkbox("ESTEEM");

// Create text area


detailsArea = new TextArea(5, 30);
[Link](false);

// Add checkboxes and text area to the applet


add(maruti800);
add(zen);
add(alto);
add(esteem);
add(detailsArea);

13
// Add item listener to checkboxes
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}

public void itemStateChanged(ItemEvent e) {


Checkbox selectedCheckbox = (Checkbox) [Link]();

if (selectedCheckbox == maruti800) {
if ([Link]()) {
[Link]("Details of MARUTI-800\n\n" +
"Model: MARUTI-800\n" +
"Engine: 0.8L Petrol\n" +
"Transmission: Manual\n" +
"Fuel Economy: 22 km/l");
}
} else if (selectedCheckbox == zen) {
if ([Link]()) {
[Link]("Details of ZEN\n\n" +
"Model: ZEN\n" +
"Engine: 1.0L Petrol\n" +
"Transmission: Manual\n" +
"Fuel Economy: 18 km/l");
}
} else if (selectedCheckbox == alto) {
if ([Link]()) {
[Link]("Details of ALTO\n\n" +

14
"Model: ALTO\n" +
"Engine: 1.0L Petrol\n" +
"Transmission: Manual\n" +
"Fuel Economy: 20 km/l");
}
} else if (selectedCheckbox == esteem) {
if ([Link]()) {
[Link]("Details of ESTEEM\n\n" +
"Model: ESTEEM\n" +
"Engine: 1.3L Petrol\n" +
"Transmission: Manual/Automatic\n" +
"Fuel Economy: 16 km/l");
}
}
}
}
<html>
<head>
<title>Car Details Applet</title>
</head>
<body>
<applet code="[Link]" width="400" height="300"></applet>
</body>
</html>

15
10. Write a Java program to throw the following exception,
1) Negative Array Size 2) Array Index out of Bounds
public class ExceptionExample {
public static void main(String[] args) {
// Example of NegativeArraySizeException
try {
int[] negativeArray = new int[-1];
} catch (NegativeArraySizeException e) {
[Link]("NegativeArraySizeException: " + [Link]());
}

// Example of ArrayIndexOutOfBoundsException
try {
int[] array = new int[5];
int value = array[10];
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBoundsException: " + [Link]());
}
}
}

16
11. Write a java program to create a file menu with option New, Save and Close, Edit
menu with option cut, copy, and paste.
import [Link].*;
import [Link].*;
import [Link].*;

public class MenuExample extends JFrame {


public MenuExample() {
setTitle("Menu Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create menu bar


JMenuBar menuBar = new JMenuBar();

// Create File menu


JMenu fileMenu = new JMenu("File");

// Create New menu item


JMenuItem newItem = new JMenuItem("New");
[Link](newItem);

// Create Save menu item


JMenuItem saveItem = new JMenuItem("Save");
[Link](saveItem);

// Create Close menu item


JMenuItem closeItem = new JMenuItem("Close");
[Link](closeItem);

17
// Create Edit menu
JMenu editMenu = new JMenu("Edit");
// Create Cut menu item
JMenuItem cutItem = new JMenuItem("Cut");
[Link](cutItem);
// Create Copy menu item
JMenuItem copyItem = new JMenuItem("Copy");
[Link](copyItem);
// Create Paste menu item
JMenuItem pasteItem = new JMenuItem("Paste");
[Link](pasteItem);
// Add File and Edit menus to the menu bar
[Link](fileMenu);
[Link](editMenu);
// Set the menu bar for the frame
setJMenuBar(menuBar);
setVisible(true);
}
public static void main(String[] args) {
[Link](new Runnable() {
public void run() {
new MenuExample();
}
});
}
}

18
12. Write a java programming to illustrate Mouse Event Handling
import [Link].*;
import [Link].*;
import [Link].*;

public class MouseEventExample extends JFrame implements MouseListener {


private JLabel label;

public MouseEventExample() {
setTitle("Mouse Event Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a label
label = new JLabel("Click or hover over the window");
add(label);

// Add mouse listener to the frame


addMouseListener(this);

setVisible(true);
}

public void mouseClicked(MouseEvent e) {


[Link]("Mouse Clicked at (" + [Link]() + ", " + [Link]() + ")");
}

public void mouseEntered(MouseEvent e) {


[Link]("Mouse Entered at (" + [Link]() + ", " + [Link]() + ")");

19
}

public void mouseExited(MouseEvent e) {


[Link]("Mouse Exited");
}

public void mousePressed(MouseEvent e) {


[Link]("Mouse Pressed at (" + [Link]() + ", " + [Link]() + ")");
}

public void mouseReleased(MouseEvent e) {


[Link]("Mouse Released at (" + [Link]() + ", " + [Link]() + ")");
}

public static void main(String[] args) {


[Link](new Runnable() {
public void run() {
new MouseEventExample();
}
});
}
}

20
13. Write a java program To convert a decimal to binary number
import [Link];

public class DecimalToBinary {


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

[Link]("Enter a decimal number: ");


int decimal = [Link]();

String binary = convertToBinary(decimal);

[Link]("Binary representation: " + binary);


}

public static String convertToBinary(int decimal) {


if (decimal == 0) {
return "0";
}
StringBuilder binary = new StringBuilder();

while (decimal > 0) {


int remainder = decimal % 2;
[Link](0, remainder);
decimal = decimal / 2;
}
return [Link]();
}
}

21
14. Write a java program for Exception handling
import [Link];

public class ExceptionHandlingExample {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter two numbers: ");
try {
int num1 = [Link]();
int num2 = [Link]();
int result = divideNumbers(num1, num2);
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
} catch (Exception e) {
[Link]("Error: Something went wrong");
}
[Link]();
}
public static int divideNumbers(int dividend, int divisor) {
return dividend / divisor;
}
}

22

You might also like