0% found this document useful (0 votes)
3 views39 pages

OOPs With Java Lab

The document outlines the vision and mission of an educational institute focused on empowering individuals through holistic education and service to society. It includes a lab manual for a Programming with Java course, detailing course objectives, outcomes, and a list of practical experiments. The document also provides sample programs demonstrating Java programming concepts such as control flow, exception handling, and GUI development.

Uploaded by

monkeymon11057
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)
3 views39 pages

OOPs With Java Lab

The document outlines the vision and mission of an educational institute focused on empowering individuals through holistic education and service to society. It includes a lab manual for a Programming with Java course, detailing course objectives, outcomes, and a list of practical experiments. The document also provides sample programs demonstrating Java programming concepts such as control flow, exception handling, and GUI development.

Uploaded by

monkeymon11057
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

VISION OF THE INSTITUTE

Empower the individuals and society at large through educational excellence; sensitize them for a
life dedicated to the service of fellow human beings and mother land.

MISSION OF THE INSTITUTE

To impact holistic education that enables the students to become socially responsive and useful,
with roots firm on traditional and cultural values; and to hone their skills to accept challenges and
respond to opportunities in a global scenario.

Lab manual on: Programming with Java


Course Code: CAM22P
Course Credits: 02 (0-0-2)
Contact Hours: 4 Hours per week
Total Contact Hours: 60 Hours
Formative Assessment Marks: 10
Summative Assessment Marks: 40
Examination Duration: 03 hours
Prepared by: BHOOMIKA M M

Overview:
The Programming with Java covers fundamental concepts of programming, object-oriented principles,
and exception handling. Programs provide a comprehensive understanding of Java's core features, error
handling, and graphical user interface development. The practical implementation helps to build a solid
foundation for Java development.

Learning Objectives:

The Programming with Java, enhance the understanding of fundamental programming concepts and
their practical applications. Students will gain hands-on experience with decision-making processes
and loops, which are crucial for controlling program flow. The programs aim to improve problem-
solving skills, which are essential for creating reliable and interactive software.
Course Outcome:

Develop Java programs using basic control flow (if-else, loops), arrays, and data
CO1 types, and apply object-oriented programming concepts such as classes, objects,
inheritance, and method overloading.

Understand and handle Java exceptions such as NullPointerException,


CO2 NumberFormatException, and ArrayIndexOutOfBoundsException, and implement
effective exception handling mechanisms in Java programs.

Design and implement GUI-based applications using AWT (Abstract Window


Toolkit), including creating windows, handling mouse events, adding buttons, and
CO3
constructing menu bars with pull-down menus, while also working with file I/O
operations.

List of Experiments
Part A

1. Program to find whether the given number is Positive, Negative or Zero.

2. Program to list the factorial of the numbers 1 to 10.

3. Program to demonstrate classes & objects.

4. Program to demonstrate method overloading.

5. Program to demonstrate single inheritance (simple calculator – base class, Advanced

Calculator – derived class).

6. Program to find Maximum & Minimum element in one dimensional array of numbers.

7. Program to check whether the given string is palindrome or not.

8. Program to create a ‘Student’ class with [Link]., name and marks of 3 subjects.

Calculate the total marks of 3 subjects and create an array of 3 student objects &

display the results.


Part B
1. Program to generate negative array size exception

2. Program to generate NullPointer Exception.

3. Program that reads two integer numbers for the variables a and b. The program

should catch NumberFormatException & display the error message.

4. Program to create AWT window with 4 buttons M/A/E/Close. Display M for Good

Morning, A for Afternoon, E for evening and Close button to exit the window.

5. Program to demonstrate the various mouse handling events.

6. Program to read and write Binary I/O file.

7. Program to create window with three buttons father, mother and close. Display the respective
details of father and mother as name, age and designation using AWT

controls.

8. Program to create menu bar and pull-down menus.

Evaluation Scheme for Lab Examination

Assessment Criteria Marks Marks


Program – 1 from Part A Writing 15
Program – 1 from Part A Writing 15
Execution of any one program 5
Viva voice based 5
Total 40
PART A

1. Program to find whether the given number is Positive, Negative or Zero.

import [Link];

public class CheckNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

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

int number = [Link]();

if (number > 0) {

[Link](number + " is positive.");

} else if (number < 0) {

[Link](number + " is negative.");

} else {

[Link](number + " is zero.");

OUTPUT
Enter a number: 5
5 is positive.
Enter a number: 0
0 is zero.
Enter a number: -8
-8 is negative.
2. Program to list the factorial of the numbers 1 to 10.

public class FactorialList {

public static void main(String[] args) {

for (int i = 1; i <= 10; i++) {

[Link]("Factorial of " + i + " = " + factorial(i));

public static long factorial(int n) {

long fact = 1;

for (int i = 1; i <= n; i++) {

fact *= i;

return fact;

OUTPUT
Factorial of 1 = 1
Factorial of 2 = 2
Factorial of 3 = 6
Factorial of 4 = 24
Factorial of 5 = 120
Factorial of 6 = 720
Factorial of 7 = 5040
Factorial of 8 = 40320
Factorial of 9 = 362880
Factorial of 10 = 3628800
3. Program to demonstrate classes & objects.
// Define a class Car

class Car {

// Attributes (Instance Variables)

String brand;

String model;

int year;

// Constructor to initialize object

Car(String brand, String model, int year) {

[Link] = brand;

[Link] = model;

[Link] = year;

// Method to display car details

void displayInfo() {

[Link]("Car Brand: " + brand);

[Link]("Car Model: " + model);

[Link]("Car Year: " + year);

// Main class

public class Main {

public static void main(String[] args) {

// Creating an object of Car class

Car myCar = new Car("Toyota", "Corolla", 2022);


// Calling method using the object

[Link]();

OUTPUT

Car Brand: Toyota

Car Model: Corolla

Car Year: 2022


4. Program to demonstrate method overloading

// Main class

public class Method {

public static void main(String[] args) {

// Creating an object of ShapeCalculator class

ShapeCalculator calculator = new ShapeCalculator();

// Method Overloading Demonstration

[Link]("Area of Square: " + [Link](5));

[Link]("Area of Rectangle: " + [Link](5, 10));

[Link]("Area of Circle: " + [Link](7.5));

// Class with method overloading

class ShapeCalculator {

// Method to calculate area of a square (side × side)

int calculateArea(int side) {

return side * side;

// Method to calculate area of a rectangle (length × width)

int calculateArea(int length, int width) {

return length * width;

// Method to calculate area of a circle (π × radius²)

double calculateArea(double radius) {

return [Link] * radius * radius;


}

OUTPUT

Area of Square: 25

Area of Rectangle: 50

Area of Circle: 176.71458676442586


5. Program to demonstrate single inheritance (simple calculator – base class,
Advanced

Calculator – derived class).

// Main class to run the program

public class inheritance {

public static void main(String[] args) {

// Creating an object of AdvancedCalculator

AdvancedCalculator calc = new AdvancedCalculator();

// Using methods from SimpleCalculator (Base Class)

[Link]("Addition: " + [Link](10, 5));

[Link]("Subtraction: " + [Link](10, 5));

// Using methods from AdvancedCalculator (Derived Class)

[Link]("Multiplication: " + [Link](10, 5));

[Link]("Division: " + [Link](10, 5));

// Base Class: Simple Calculator

class SimpleCalculator {

// Method for Addition

int add(int a, int b) {

return a + b;

// Method for Subtraction

int subtract(int a, int b) {

return a - b;
}

// Derived Class: Advanced Calculator (Inherits SimpleCalculator)

class AdvancedCalculator extends SimpleCalculator {

// Method for Multiplication

int multiply(int a, int b) {

return a * b;

// Method for Division

double divide(int a, int b) {

if (b == 0) {

[Link]("Error: Division by zero is not allowed.");

return 0;

return (double) a / b;

OUTPUT

Addition: 15

Subtraction: 5

Multiplication: 50

Division: 2.0
6. Program to find Maximum & Minimum element in one dimensional array of
numbers.

// Main class

public class Array {

public static void main(String[] args) {

// Example array

int[] numbers = {23, 5, 78, 12, 67, 90, 34, 1};

// Calling method to find min and max

findMinMax(numbers);

// Method to find the minimum and maximum in an array

public static void findMinMax(int[] arr) {

// Initializing min and max with the first element

int min = arr[0];

int max = arr[0];

// Loop through the array to find min and max

for (int i = 1; i < [Link]; i++) {

if (arr[i] < min) {

min = arr[i];

if (arr[i] > max) {

max = arr[i];

// Displaying the results


[Link]("Minimum Element: " + min);

[Link]("Maximum Element: " + max);

OUTPUT

Minimum Element: 1

Maximum Element: 90
7. Program to check whether the given string is palindrome or not.

import [Link];

public class Palindrome {

public static void main(String[] args) {

// Taking user input

Scanner scanner = new Scanner([Link]);

[Link]("Enter a string: ");

String input = [Link]();

[Link](); // Close scanner to avoid resource leak

// Check if the string is a palindrome

if (isPalindrome(input)) {

[Link]("The string \"" + input + "\" is a palindrome.");

} else {

[Link]("The string \"" + input + "\" is NOT a palindrome.");

// Method to check if a string is a palindrome

public static boolean isPalindrome(String str) {

int left = 0, right = [Link]() - 1;

while (left < right) {

if ([Link](left) != [Link](right)) {

return false; // Not a palindrome

left++;
right--;

return true; // Palindrome

OUTPUT

Enter a string: madam

The string "madam" is a palindrome.

Enter a string: hello

The string "hello" is NOT a palindrome.


8. Program to create a ‘Student’ class with [Link]., name and marks of 3
subjects.
Calculate the total marks of 3 subjects and create an array of 3 student objects &
display the results.

public class Student {


private int regNo;
private String name;
private int marks1, marks2, marks3;
public Student(int regNo, String name, int marks1, int marks2, int marks3) {
[Link] = regNo;
[Link] = name;
this.marks1 = marks1;
this.marks2 = marks2;
this.marks3 = marks3;
}
public int getTotalMarks() {
return marks1 + marks2 + marks3;
}

public void displayDetails() {


[Link]("Reg. No: " + regNo);
[Link]("Name: " + name);
[Link]("Marks: " + marks1 + ", " + marks2 + ", " + marks3);
[Link]("Total Marks: " + getTotalMarks());
[Link]("---------------------------");
}

public static void main(String[] args) {


Student[] students = new Student[3];
students[0] = new Student(101, "Alice", 85, 90, 78);
students[1] = new Student(102, "Bob", 76, 88, 95);
students[2] = new Student(103, "Charlie", 89, 92, 80);

[Link]("Student Details:");
[Link]("---------------------------");
for (Student student : students) {
[Link]();
}
}
}
OUTPUT
Student Details:
---------------------------
Reg. No: 101
Name: Alice
Marks: 85, 90, 78
Total Marks: 253
---------------------------
Reg. No: 102
Name: Bob
Marks: 76, 88, 95
Total Marks: 259
---------------------------
Reg. No: 103
Name: Charlie
Marks: 89, 92, 80
Total Marks: 261
---------------------------
PART B

1. Program to generate negative array size exception

public class NegativeSize {

public static void main(String[] args) {

try {

// Attempting to create an array with negative size

int size = -5;

int[] arr = new int[size]; // This will throw ArraySizeException

[Link]("Array created with size: " + size);

} catch (NegativeArraySizeException e) {

// Catching the NegativeArraySizeException

[Link]("Exception caught: " + e);

OUTPUT

Exception caught: [Link]: -5


2. Program to generate NullPointer Exception.

public class NullPointer {

public static void main(String[] args) {

try {

// Declaring a String object without initialization

String str = null;

// Attempting to call a method on the null object, which will cause

// NullPointerException

int length = [Link](); // This will throw NullPointerException

[Link]("Length of the string: " + length);

} catch (NullPointerException e) {

// Catching the NullPointerException

[Link]("Exception caught: " + e);

OUTPUT

Exception caught: [Link]:

Cannot invoke "[Link]()" because "<local1>" is null


3. Program that reads two integer numbers for the variables a and b. The program
should catch NumberFormatException & display the error message.

import [Link];

public class NumberFormat {

public static void main(String[] args) {

// Create a scanner object to read user input

Scanner scanner = new Scanner([Link]);

try {

// Reading the first integer input

[Link]("Enter the first number (a): ");

String inputA = [Link]();

int a = [Link](inputA); // This will throw NumberFormatException if invalid input

// Reading the second integer input

[Link]("Enter the second number (b): ");

String inputB = [Link]();

int b = [Link](inputB); // This will throw NumberFormatException if invalid input

// Display the sum of a and b

[Link]("The sum of " + a + " and " + b + " is: " + (a + b));

} catch (NumberFormatException e) {

// Catching and handling NumberFormatException

[Link]("Error: Please enter valid integer numbers. Exception: " + e);

} finally {

// Close the scanner to prevent resource leaks

[Link]();

}
}

OUTPUT

Enter the first number (a): 10

Enter the second number (b): 20

The sum of 10 and 20 is: 30

Enter the first number (a): abc

Error: Please enter valid integer numbers. Exception: [Link]: For input
string: "abc"
4. Program to create AWT window with 4 buttons M/A/E/Close. Display M for
Good
Morning, A for Afternoon, E for evening and Close button to exit the window.

import [Link].*;

import [Link].*;

public class Good {

public static void main(String[] args) {

// Create a Frame (Window)

Frame frame = new Frame("AWT Button Example");

// Create 4 buttons

Button buttonM = new Button("M");

Button buttonA = new Button("A");

Button buttonE = new Button("E");

Button buttonClose = new Button("Close");

// Set the layout of the frame to FlowLayout

[Link](new FlowLayout());

// Add buttons to the frame

[Link](buttonM);

[Link](buttonA);

[Link](buttonE);

[Link](buttonClose);

// Label to display messages

Label messageLabel = new Label("");

[Link](messageLabel);

// Action for Good Morning (M)


[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

[Link]("Good Morning");

});

// Action for Good Afternoon (A)

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

[Link]("Good Afternoon");

});

// Action for Good Evening (E)

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

[Link]("Good Evening");

});

// Action to close the window (Close button)

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

[Link](0); // Exit the program

});

// Set frame size and visibility

[Link](300, 200);
[Link](true);

// Close the window when clicking the close button (x) at the top right

[Link](new WindowAdapter() {

public void windowClosing(WindowEvent we) {

[Link](0);

});

OUTPUT
5. Program to demonstrate the various mouse handling events.

// Java AWT Program to demonstrate

// MouseListener

import [Link].*;

import [Link].*;

public class MouseMain {

public static void main(String[] args){

// Create an instance of frame

Frame f = new Frame("MouseListener Demo");

// Create a label

Label l = new Label("Welcome to GeeksforGeeks!");

// Set the properties of label

[Link](80, 100, 220, 30);

[Link](new Font("Serif", [Link], 18));

[Link]([Link]);

// Add MouseListener to the label with different methods

[Link](new MouseListener() {

public void mouseClicked(MouseEvent e){

[Link]("Mouse Clicked");

public void mouseEntered(MouseEvent e){

[Link]("Mouse Entered");

public void mouseExited(MouseEvent e){


[Link]("Mouse Exited");

public void mousePressed(MouseEvent e){

[Link]("Mouse Pressed");

public void mouseReleased(MouseEvent e){

[Link]("Mouse Released");

});

// Add label to the frame

[Link](l);

// Set the properties of frame

[Link](null);

[Link](400, 300);

[Link](true);

}
OUTPUT
6. Program to read and write Binary I/O file.

import [Link].*;

public class BinaryFileIO {

public static void main(String[] args) {

String filename = "[Link]";

// Writing binary data to a file

writeBinaryFile(filename);

// Reading binary data from the file

readBinaryFile(filename);

private static void writeBinaryFile(String filename) {

try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(filename))) {

[Link](100); // Writing an integer

[Link](99.99); // Writing a double

[Link]("Hello, Binary I/O!"); // Writing a string

[Link]("Binary data written to file successfully.");

} catch (IOException e) {

[Link]("Error writing to file: " + [Link]());

private static void readBinaryFile(String filename) {

try (DataInputStream dis = new DataInputStream(new FileInputStream(filename))) {

int intValue = [Link](); // Reading an integer

double doubleValue = [Link](); // Reading a double


String strValue = [Link](); // Reading a string

[Link]("Binary data read from file:");

[Link]("Integer: " + intValue);

[Link]("Double: " + doubleValue);

[Link]("String: " + strValue);

} catch (IOException e) {

[Link]("Error reading from file: " + [Link]());

OUTPUT

Binary data written to file successfully.

Binary data read from file:

Integer: 100

Double: 99.99

String: Hello, Binary I/O!


7. Program to create window with three buttons father, mother and close. Display
the respective details of father and mother as name, age and designation using AWT
controls.

import [Link].*;

import [Link].*;

public class FamilyDetailsAWT extends Frame implements ActionListener {

private Label nameLabel, ageLabel, designationLabel;

private Button fatherButton, motherButton, closeButton;

public FamilyDetailsAWT() {

setTitle("Family Details");

setSize(400, 300);

setLayout(new FlowLayout());

setResizable(false);

setLocationRelativeTo(null); // Center the window

// Creating buttons

fatherButton = new Button("Father");

motherButton = new Button("Mother");

closeButton = new Button("Close");

// Creating labels

nameLabel = new Label("Name: ");

ageLabel = new Label("Age: ");

designationLabel = new Label("Designation: ");

// Adding action listeners

[Link](this);

[Link](this);
[Link](this);

// Adding components to Frame

add(fatherButton);

add(motherButton);

add(closeButton);

add(nameLabel);

add(ageLabel);

add(designationLabel);

// Window closing event

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

dispose();

});

setVisible(true);

@Override

public void actionPerformed(ActionEvent e) {

if ([Link]() == fatherButton) {

[Link]("Name: John Doe");

[Link]("Age: 45");

[Link]("Designation: Engineer");

} else if ([Link]() == motherButton) {

[Link]("Name: Jane Doe");

[Link]("Age: 42");
[Link]("Designation: Doctor");

} else if ([Link]() == closeButton) {

dispose(); // Close the window

public static void main(String[] args) {

new FamilyDetailsAWT();

OUTPUT
8. Program to create menu bar and pull-down menus.

import [Link].*;

import [Link].*;

import [Link].*;

public class MenuBarExample extends JFrame implements ActionListener {

private JMenuItem newItem, openItem, saveItem, exitItem;

private JMenuItem cutItem, copyItem, pasteItem;

private JMenuItem aboutItem;

public MenuBarExample() {

setTitle("Menu Bar Example");

setSize(400, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new FlowLayout());

// Creating Menu Bar

JMenuBar menuBar = new JMenuBar();

// Creating Menus

JMenu fileMenu = new JMenu("File");

JMenu editMenu = new JMenu("Edit");

JMenu helpMenu = new JMenu("Help");

// Creating Menu Items for File Menu

newItem = new JMenuItem("New");

openItem = new JMenuItem("Open");


saveItem = new JMenuItem("Save");

exitItem = new JMenuItem("Exit");

// Adding menu items to File Menu

[Link](newItem);

[Link](openItem);

[Link](saveItem);

[Link](); // Adds a separator line

[Link](exitItem);

// Creating Menu Items for Edit Menu

cutItem = new JMenuItem("Cut");

copyItem = new JMenuItem("Copy");

pasteItem = new JMenuItem("Paste");

// Adding menu items to Edit Menu

[Link](cutItem);

[Link](copyItem);

[Link](pasteItem);

// Creating Menu Item for Help Menu

aboutItem = new JMenuItem("About");

[Link](aboutItem);

// Adding Menus to Menu Bar

[Link](fileMenu);

[Link](editMenu);

[Link](helpMenu);

// Setting Menu Bar to the Frame

setJMenuBar(menuBar);
// Adding Action Listeners

[Link](this);

[Link](this);

[Link](this);

[Link](this);

[Link](this);

[Link](this);

[Link](this);

[Link](this);

setVisible(true);

@Override

public void actionPerformed(ActionEvent e) {

if ([Link]() == newItem) {

[Link](this, "New File Created");

} else if ([Link]() == openItem) {

[Link](this, "Open File Dialog");

} else if ([Link]() == saveItem) {

[Link](this, "File Saved Successfully");

} else if ([Link]() == exitItem) {

[Link](0); // Exit the application

} else if ([Link]() == cutItem) {

[Link](this, "Cut Action Performed");

} else if ([Link]() == copyItem) {

[Link](this, "Copy Action Performed");


} else if ([Link]() == pasteItem) {

[Link](this, "Paste Action Performed");

} else if ([Link]() == aboutItem) {

[Link](this, "This is a simple Menu Bar Example.");

public static void main(String[] args) {

new MenuBarExample();

OUTPUT

You might also like