[Go to site: main page, start]

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

Java Programming Lab Exercises

The document outlines a Java programming lab for II B.Sc Computer Science students, detailing various programming exercises including class definitions, method overloading, exception handling, and inheritance. It includes specific examples such as creating a Student class, calculating areas of geometric shapes, and implementing interfaces and threads. Each section provides aims, procedures, and code snippets for practical implementation of Java concepts.

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 views48 pages

Java Programming Lab Exercises

The document outlines a Java programming lab for II B.Sc Computer Science students, detailing various programming exercises including class definitions, method overloading, exception handling, and inheritance. It includes specific examples such as creating a Student class, calculating areas of geometric shapes, and implementing interfaces and threads. Each section provides aims, procedures, and code snippets for practical implementation of Java concepts.

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

PROGRAMMING IN JAVA LAB

SUBJECT CODE : 22UCS3CP3


CLASS : II [Link] COMPUTER SCIENCE
SEMESTER : FOURTH SEMESTER

PREPARED BY
[Link] [Link]., [Link]., [Link]
Assistant Professor / Department of Computer Science,
Thanthani Hans Roever College (A),
Elambalur, Perambalur-621220
[Link]. Title of the Program Page No.

1 STUDENT MARK LIST 1

(i) Overloading Constructor 4


2
(ii) Overloading Method 7

3 Complex Number 9

4 STUDENTS DETAILS 12
STUDENT DATA MEMBER’S
5 HEIGHT AND WEIGHT 15

6 INTERFACE 18

7 THREAD 21

8 INHERITANCE 24

9 CAR DETAILS 27

10 NEGATIVE ARRAY SIZE 31

11 FILE MENU 34

12 MOUSE EVENT HANDLING 38

13 DECIMAL TO BINARY NUMBER 41

14 EXCEPTION HANDLING 44
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.

Aim:
To be define a class Student that can store information about a student, including their
name, registration number, and marks in four subjects. It also provides methods to calculate
the total marks obtained and display the details of the student.

Procedure:
1. Define the Student class with attributes (name, regNumber, m1, m2, m3, m4).
2. Define a constructor to initialize the attributes.
3. Define a method (calculateTotalMarks) to calculate the total marks obtained by adding m1,
m2, m3, and m4.
4. Define a method (display Details) to print the student's information.
5. Create an instance of the Student class in the main method.
6. Call the display Details method on the instance to see the student's details.

1
STUDENT MARK LIST

Public class Student


{
private String name;
private int regnumber;
private int m1;
private int m2;
private int m3;
private int m4;
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;
}
public int calculateTotalMarks()
{
return m1+m2+m3+m4;
}
public void displayDetails()
{
[Link]("Name:"+name);
[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[])

2
{
Student student =new Student("John Doe",12345,80,85,90,95);
[Link]();
}
}

OUTPUT:

3
2. Write a Java program to find the area of a square, rectangle and triangle by
(i) Overloading Constructor (ii) Overloading Method.

Aim:
To be calculating the area of a square, rectangle, and triangle using both constructor
overloading and method overloading.
Procedure:
1. Define a class Shape with attributes side, length, breadth, base, and height.
2. Overload the constructor to handle the creation of objects for square, rectangle, and
triangle.
3. Define methods to calculate the area for each shape in the Shape class.
4. Define a class AreaCalculatorMethods with static methods for calculating the area of
square, rectangle, and triangle using method overloading.
5. In the main method, create instances of the Shape class using constructor overloading and
calculate the areas.
6. Also, use the static methods of AreaCalculatorMethods for method overloading to
calculate the areas.

4
(i) Overloading Constructor

public class AreaCalculator


{
public static void main(String args[])
{
Square square = new Square(5);
[Link]("Area of Square: " + [Link]());
Rectangle rectangle = new Rectangle(4, 6);
[Link]("Area of Rectangle: " + [Link]());
Triangle triangle = new Triangle(4, 5);
[Link]("Area of Triangle: " + [Link]());
}
}
class Square
{
private double side;

public Square(double side)


{
[Link] = side;
}
public double calculateArea()
{
return side * side;
}
}
class Rectangle
{
private double length;
private double width;
public Rectangle(double length, double width) {
[Link] = length;
[Link] = width;

5
}
public double calculateArea()
{
return length * width;
}
}
class Triangle
{
private double base;
private double height;
public Triangle(double base, double height)
{
[Link] = base;
[Link] = height;
}
public double calculateArea() {
return 0.5 * base * height;
}
}

OUTPUT:

6
(ii) Overloading Method.
public class AreaCalculator1
{
public static double calculateArea(double side)
{
return side * side;
}
public static double calculateArea(double length, double width)
{
return length * width;
}
public static double calculateArea1(double base, double height)
{
return 0.5 * base * height;
}
public static void main(String[] args)
{
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);
}
}

7
OUTPUT:

8
3. Write a java program to add two complex numbers. [Use passing object as argument
and return object].

Aim:

To be demonstrate how to add two complex numbers using a class, where objects are
used as arguments and an object is returned as the result.
Procedure:
1. ComplexNumber class is defined with attributes real and imaginary representing the real
and imaginary parts of a complex number.
2. The constructor public Complex Number(double real, double imaginary) initializes these
attributes when a new Complex Number object is created.
[Link] add method takes another Complex Number object (other) as an argument, adds their
real and imaginary parts separately, and returns a new Complex Number object
representing the sum.
4. In the main method, two complex numbers complex1 and complex2 are created.
[Link] (complex2) is called to add them, and the result is stored in the sum
variable.
. [Link], the sum is printed out in the format "Sum: <real part> + <imaginary part>i".

9
Complex Number

class Complex
{
private double real;
private double imaginary;
public Complex(double real, double imaginary)
{
[Link]=real;
[Link]=imaginary;
}
public static Complex addComplexNumbers(Complex num1, Complex num2)
{
double realSum = [Link] + [Link];
double imaginarySum = [Link] + [Link];
return new Complex(realSum, imaginarySum);
}
public void displayComplex()
{
[Link](real + " + " + imaginary + "i");
}
}
public class ComplexNumberAddition
{
public static void main(String[] args)
{
Complex num1 = new Complex(2.5, 3.7);
Complex num2 = new Complex(1.8, 2.9);
Complex sum = [Link](num1, num2);
[Link]("Sum of complex numbers: ");
[Link]();
}

10
}

OUTPUT:

11
4. Define 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.

Aim
This approach follows a procedural programming style where we have a class to
represent a student, and methods to perform operations on the student data
Procedure:
1. Student class is defined with data members name, roll Number, and age.
2. The constructor public Student (String name, int roll Number, int age) initializes these data
members when a new Student object is created.
3. Output method is a procedure that prints out the details of the student including name, roll
number, and age.
[Link] the main method, a Student object named student1 is created using the constructor, and
then its details are displayed using the output method

12
STUDENTS DETAILS
class Student
{
private String name;
private int rollNumber;
private int age;
public Student(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);
}
}
public class Main
{
public static void main(String[] args)
{
Student student = new Student("John Doe", 12345, 20);
[Link]();
}
}

13
OUTPUT:

14
5. Derive another class Student from Student super with data member’s height and
weight. Write a constructor and a method output () to display the details which
overrides the super classmethod output().[Apply method Overriding concept].

Aim
To be demonstrate method overriding in Java, where the subclass (StudentSubclass)
overrides a method from its super class (Student).
Procedure:
1. Student Super class is defined with data members name, roll Number, and age. It has a
constructor to initialize these attributes and an output() method to display details.
2. Student class extends Student Super. It adds attributes height and weight. The constructor
initializes all attributes, including those inherited from Student Super.
[Link] output () method in Student class overrides the output () method from Student Super. It
first calls the output () method from the super class using super. Output () and then displays
the additional details height and weight

15
STUDENT DATA MEMBER’S HEIGHT AND WEIGHT

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;
}
public void output()
{
[Link]();
[Link]("Height: " + height + " cm");
[Link]("Weight: " + weight + " kg");

16
}
}
public class main1
{
public static void main(String[] args)
{
Student student = new Student("John Doe", 12345, 20, 170.5, 65.7); [Link]();
}
}

OUTPUT:

17
[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 tofind the area of a circle.

Aim
To be demonstrate how to create and implement an interface in Java, and use it to find
the area of a circle.
Procedure:

1. Demo interface is created with a constant PI and a method area() which takes one double
type argument (radius in this case).
2. Circle class implements the Demo interface. It provides an implementation for the area()
method by using the formula for the area of a circle (PI * radius * radius).
3. In the Main class, an instance of Circle is created. The area() method is called with a
specified radius (in this case, 5.0) and the result is stored in circleArea.
4. The program then prints out the calculated area of the circle.

18
INTERFACE

interface Demo
{
double PI = 3.14159;
}
class Circle implements Demo
{
public double area(double radius)
{
return PI * radius * radius;
}
}
public class main2
{
public static void main(String[] args)
{
Circle circle = new Circle();
double radius = 5.0;
double circleArea = [Link](radius);
[Link]("Area of the circle: " + circleArea);
}
}

19
OUTPUT:

20
7. Write a java program to create a thread using Thread class.

Aim:
To be demonstrate multithreading in Java. We create a separate thread (MyThread) that
runs concurrently with the main thread.
Procedure:
1. We create a class MyThread that extends the Thread class. Inside this class, we override
the run () method, which is the entry point for the thread.
2. In the run () method, a loop is used to print "Thread: " along with a number from 1 to 5. It
then pauses for 1 second using [Link] ().
3. In the Main class, we create an instance of MyThread called thread.
4. We start the thread using [Link] (). This triggers the execution of the run () method in
a separate thread.
5. The main thread also executes a loop that prints "Main: " along with a number from 1 to 5,
pausing for 1 second between iterations.

21
THREAD

class MyThread extends Thread


{
public void run()
{
for (int i = 1; i <= 5; i++)
{
[Link]("Thread: " + i);
try
{
[Link](1000);
}
catch (InterruptedException e)
{
[Link]();
}
}
}
}
public class the
{
public static void main(String[] args)
{
MyThread thread = new MyThread();
[Link]();
for (int i = 1; i <= 5; i++)
{
[Link]("Main: " + i);
try
{
[Link](1000);
}
catch (InterruptedException e)
{
[Link]();
}
}
}
}

22
OUTPUT:

23
8. Demonstrate Java inheritance using extends keyword.
Aim:
To be illustrate Java inheritance using the extends keyword. Inheritance allows a subclass to
inherit the attributes and methods of a superclass.
Procedure:
1. Create a Superclass (Vehicle)
2. We’ll create a superclass Vehicle with attributes like brand and fuelType, and a method
startEngine().
3. Create a Subclass (Car) that Extends the Superclass
4. We’ll create a subclass Car that extends the Vehicle class. The Car class will have an
additional attribute numDoors and a method drive ().
5. Create an Instance and Use Inherited Methods In the Main class, we'll create an instance of
Car and use both the inherited method startEngine () and the subclass-specific method
drive().

24
INHERITANCE

class Vehicle
{
protected String brand;
public void drive()
{
[Link]("Driving the vehicle.");
}
}
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 inheri
{
public static void main(String[] args)
{
Car car = new Car("Toyota", 4);
[Link]();
[Link]();
}
}

25
OUTPUT:

26
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.
Aim:
To be create a Java Applet that allows the user to select a car model (MARUTI-
800, ZEN, ALTO, or ESTEEM) using checkboxes. When a checkbox is clicked, the program
should display the details of the selected car in a Text Area.
Procedure:
1. We create a class CarDetailsApplet that extends [Link] and implements the
Item Listener interface.
2. In the init() method, we create a Checkbox Group named carGroup to group the
checkboxes.
3. We create four checkboxes (maruti800, zen, alto, and esteem) and a TextArea named
displayArea. The checkboxes are associated with the carGroup.
4. We add an ItemListener to each checkbox using addItemListener(this).
5. In the itemStateChanged method, we use getState() to check which checkbox is selected.
Based on the selected checkbox, we update the displayArea with the details of the
corresponding car.

27
CAR DETAILS

import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="CarDetailsApplet1" width="400" height="300">
</applet>
*/
public class CarDetailsApplet1 extends Applet implements ItemListener
{
Checkbox maruti800, zen, alto, esteem;
TextArea detailsArea;
public void init()
{
maruti800 = new Checkbox("MARUTI-800");
zen = new Checkbox("ZEN");
alto = new Checkbox("ALTO");
esteem = new Checkbox("ESTEEM");
detailsArea = new TextArea(5, 30);
[Link](false);
add(maruti800);
add(zen);
add(alto);
add(esteem);
add(detailsArea);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void itemStateChanged(ItemEvent e)
{
Checkbox selectedCheckbox = (Checkbox) [Link]();

28
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" +"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");
}
}
}
}

29
OUTPUT

30
[Link] a Java program to throw the following exception,
1)Negative Array Size 2) Array Index out of Bounds
Aim:
To be demonstrate throwing two exceptions: NegativeArraySizeException and
ArrayIndexOutOfBoundsException.
Procedure:
1. In the main method, we have two try-catch blocks. Each block demonstrates one of the
exceptions.
2. NegativeArraySizeException:
In the first try-catch block, we attempt to create an array with a negative size (int[]
negativeArray = new int[-5];). This will throw a NegativeArraySizeException.
3. ArrayIndexOutOfBoundsException:
In the second try-catch block, we create an array arr with a size of 5 (int[] arr = new int[5];).
Then, we try to access an index beyond the array size (arr[10] = 5;). This will throw an
ArrayIndexOutOfBoundsException.

31
NEGATIVE ARRAY SIZE

public class ExceptionExample


{
public static void main(String[] args)
{
try
{
int[] negativeArray = new int[-1];
}
catch (NegativeArraySizeException e)
{
[Link]("NegativeArraySizeException: " + [Link]());
}
try
{
int[] array = new int[5];
int value = array[10];
}
catch (ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBoundsException: " + [Link]());
}
}
}

32
OUTPUT:

33
11. Write a java program to create a file menu with option New, Save and Close, Edit
menu with option cut, copy, and paste.
Aim:
To be create a GUI application with a File menu (New, Save, Close) and an Edit menu
(Cut, Copy, Paste) using [Link].
Procedure:
1. We create a JFrame named frame and a JMenuBar named menuBar.
2. We create a File menu with three menu items: New, Save, and Close.
3. We create an Edit menu with three menu items: Cut, Copy, and Paste.
4. We add ActionListeners to each menu item. When a menu item is clicked, the
corresponding message is printed to the console.
5. Finally, we add the menus to the menu bar and set the menu bar to the frame.

34
FILE MENU
import [Link].*;
import [Link].*;
import [Link].*;
public class CutAndPaste extends Frame {
MenuBar mb = new MenuBar();
Menu edit = new Menu("EDIT");
MenuItem cut = new MenuItem("Cut"),
copy = new MenuItem("Copy"),
paste = new MenuItem("Paste");
TextArea text = new TextArea(20, 20);
Clipboard clipbd = getToolkit().getSystemClipboard();
public CutAndPaste() {
[Link](new CutL());
[Link](new CopyL());
[Link](new PasteL());
[Link](cut);
[Link](copy);
[Link](paste);
[Link](edit);
setMenuBar(mb);
add(text, [Link]);
}
class CopyL implements ActionListener {
public void actionPerformed(ActionEvent e) {
String selection = [Link]();
StringSelection clipString = new StringSelection(selection);
[Link](clipString, clipString);
}
}
class CutL implements ActionListener {
public void actionPerformed(ActionEvent e) {
String selection = [Link]();
StringSelection clipString = new StringSelection(selection);
[Link](clipString, clipString);

35
[Link]("", [Link](), [Link]());
}
}
class PasteL implements ActionListener {
public void actionPerformed(ActionEvent e) {
Transferable clipData = [Link]([Link]);
try {
String ClipString = (String) [Link]([Link]);
[Link](ClipString, [Link](), [Link]());
} catch (Exception ex) {
[Link]("not String flavor");
}
}
}
public static void main(String args[]) {
CutAndPaste cp = new CutAndPaste();
[Link](300, 200);
[Link](true);
[Link](new WindowAdapter() {
public void windowClosing(WindowEvent w) {
[Link](0);
}
});
}
}

36
OUTPUT:

37
12. Write a java programming to illustrate Mouse Event Handling
Aim:
To be illustrate Mouse Event Handling in Java.
Procedure:
1. We create a class named MouseEventDemo that extends Frame and implements the
MouseListener interface.
[Link] the constructor, we create a Label named label and set its properties. We also set the
layout to null.
[Link] add this as a MouseListener to the frame to handle mouse events.
[Link] implement the MouseListener interface methods (mouseClicked, mouseEntered,
mouseExited, mousePressed, and mouseReleased) to perform actions when mouse events
occur.
[Link] each method, we update the text of the label to indicate which mouse event occurred.
[Link] the main method, we create an instance of MouseEventDemo to run the program.

38
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);
label = new JLabel("Click or hover over the window");
add(label);
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]() + ")");
}
public void mouseExited(MouseEvent e)
{
[Link]("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{
[Link]("Mouse Pressed at (" + [Link]() + ", " + [Link]() + ")");
}
public void mouseReleased(MouseEvent e)

39
{
[Link]("Mouse Released at (" + [Link]() + ", " + [Link]() + ")");
}
public static void main(String[] args)
{
[Link](new Runnable()
{
public void run()
{
new MouseEventExample();
}
});
}
}
OUTPUT:

40
[Link] convert a decimal to binary number
Aim:
To be convert a decimal number to its binary representation.
Procedure:
1. Take a decimal number as input.
2. The algorithm to convert a decimal number to binary is as follows:
3. Initialize an empty string (binary String) to store the binary representation.
4. Repeat the following steps until the decimal number is greater than 0:
5. Find the remainder when dividing the decimal number by 2.
6. Append the remainder to the beginning of the binary String.
7. Divide the decimal number by 2 (integer division).
8. The binary String now contains the binary representation of the decimal number.

41
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 decimalNumber = [Link]();

String binaryNumber = decimalToBinary(decimalNumber);


[Link]("Binary representation: " + binaryNumber);
}

public static String decimalToBinary(int decimalNumber)


{
if (decimalNumber == 0)
{
return "0";
}

StringBuilder binary = new StringBuilder();


while (decimalNumber > 0) {
int remainder = decimalNumber % 2;
[Link](0, remainder);
decimalNumber /= 2;
}
return [Link]();
}
}

42
OUTPUT:

43
[Link] a java program for Exception handling
Aim:
To be demonstrate exception handling in Java.
Procedure:
1. Input: The program asks the user to enter a number.
2. Try Block: It attempts to perform a division operation and print the result.
If an exception occurs during this process, it will jump to the appropriate catch block.
3. ArithmeticException Catch Block: This block handles the specific case of division by zero.
It prints an error message indicating that division by zero is not allowed.
4. General Exception Catch Block: This block handles any other exceptions that may occur.
It prints a generic error message along with the specific error message obtained from the
exception object.
5. Finally Block: This block is executed regardless of whether an exception occurs or not.
It prints a message indicating that the execution has completed.

44
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;
}
}

45
OUTPUT:

46

You might also like