0% found this document useful (0 votes)
42 views14 pages

Java Lab Manual: Programs & Examples

The SEP Java Lab Manual outlines a series of programming exercises divided into two parts. Part A includes tasks such as checking number positivity, calculating factorials, demonstrating classes and inheritance, and creating a student class. Part B focuses on exception handling, AWT GUI creation, and file I/O operations.

Uploaded by

divyashreer58
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)
42 views14 pages

Java Lab Manual: Programs & Examples

The SEP Java Lab Manual outlines a series of programming exercises divided into two parts. Part A includes tasks such as checking number positivity, calculating factorials, demonstrating classes and inheritance, and creating a student class. Part B focuses on exception handling, AWT GUI creation, and file I/O operations.

Uploaded by

divyashreer58
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

SEP JAVA LAB MANUAL

Laboratory Program List


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

part A

[Link] to check whether the given number is Positive, Negative, or Zero.

import [Link];
public class NumberCheck
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
if (number > 0)
{
[Link]("Positive");
}
else if (number < 0)
{
[Link]("Negative");
}
else
{
[Link]("Zero");
}
SEP JAVA LAB MANUAL

}
}
Output:

2. Program to list the factorial of the number from 1 to 10


public class FactorialList
{
public static void main(String[] args)
{
for (int number = 1; number <= 10; number++)
{
int factorial = 1;
for (int i = 1; i <= number; i++)
{
factorial *= i;
}
[Link]("Factorial of " + number + " is " + factorial);
}
}
}

Output:

3. Program to demonstrate classes & objects.


class Car
{
String brand;
int year;
void displayDetails()
{
[Link]("Brand: " + brand);
[Link]("Year: " + year);
}
SEP JAVA LAB MANUAL

}
public class Sample
{
public static void main(String[] args)
{
Car myCar = new Car();
[Link] = "Toyota";
[Link] = 2020;
[Link]();
}
}

Output

4. program to demonstrate method overloading

class Calculator
{
int add(int a, int b)
{
return a + b;
}
int add(int a, int b, int c)
{
return a + b + c;
}
}
public class Pgm4
{
public static void main(String[] args)
{
Calculator calc = new Calculator();
[Link]("Sum of 10 and 20: " + [Link](10, 20));
[Link]("Sum of 10, 20, and 30: " + [Link](10, 20, 30));
}}

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


Advanced Calculator – derived class).
SEP JAVA LAB MANUAL

class BaseCalculator
{
int add(int a, int b)
{
return a + b;
}
}

class AdvancedCalculator extends BaseCalculator


{
int multiply(int a, int b)
{
return a * b;
}
}
public class Pgm5
{
public static void main(String[] args)
{
AdvancedCalculator calc = new AdvancedCalculator();
[Link]("Addition: " + [Link](10, 20));
[Link]("Multiplication: " + [Link](10, 20));
}
}

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


numbers.

public class MaxMinArray


{
public static void main(String[] args)
{
int[] numbers = {10, 20, 4, 45, 99, 2,67};
int max = numbers[0];
int min = numbers[0];
for (int i = 1; i < [Link]; i++)
{
if (numbers[i] > max)
{
max = numbers[i];
}
if (numbers[i] < min)
{
min = numbers[i];
}
}
SEP JAVA LAB MANUAL

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


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

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

import [Link];
public class PalindromeCheck
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
String reversed = new StringBuilder(str).reverse().toString();
if ([Link](reversed))
{
[Link]("The string is a palindrome.");
}
else
{
[Link]("The string is not a palindrome.");
}
[Link]();
}
}

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

import [Link];

class Student
{
int regNo;
SEP JAVA LAB MANUAL

String name;
int marks1, marks2, marks3;
int getTotalMarks()
{
return marks1 + marks2 + marks3;
}
}
public class Pgm8
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
Student[] students = new Student[3];
for (int i = 0; i < 3; i++)
{
students[i] = new Student();
[Link]("Enter details for Student " + (i + 1));
[Link]("Enter Registration Number: ");
students[i].regNo = [Link]();
[Link]();
[Link]("Enter Name: ");
students[i].name = [Link]();
[Link]("Enter Marks for Subject 1: ");
students[i].marks1 = [Link]();
[Link]("Enter Marks for Subject 2: ");
students[i].marks2 = [Link]();
[Link]("Enter Marks for Subject 3: ");
students[i].marks3 = [Link]();
[Link]();
}
[Link]("Student Results:");
for (int i = 0; i < 3; i++) {
[Link]("Student " + (i + 1) + ": " + students[i].name);
[Link]("Registration No: " + students[i].regNo);
[Link]("Total Marks: " + students[i].getTotalMarks());
[Link]();
}
[Link]();
}
}
SEP JAVA LAB MANUAL

PART B

1 Program to generate negative array size exception

public class NegativeArraySizeExceptionExample


{
public static void main(String[] args)
{
try
{
int[] arr = new int[-5];
}
catch (NegativeArraySizeException e)
{
[Link]("Exception: " + e);
}
}
}

[Link] to generate NullPointer Exception.

public class NullPointerExample


{
public static void main(String[] args)
SEP JAVA LAB MANUAL

{
String str = null;
[Link]([Link]());
}
}

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

import [Link];

public class NumberFormatExceptionExample


{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
try
{
[Link]("Enter the first number (a): ");
int a = [Link]([Link]());
[Link]("Enter the second number (b): ");
int b = [Link]([Link]());
[Link]("You entered: a = " + a + ", b = " + b);
}
catch (NumberFormatException e)
{
[Link]("Error: Please enter valid integers.");
}
[Link]();
}
}

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 SimpleAWTExample
{
public static void main(String[] args)
{
SEP JAVA LAB MANUAL

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


Button btnMorning = new Button("M");
Button btnAfternoon = new Button("A");
Button btnEvening = new Button("E");
Button btnClose = new Button("Close");
[Link](new FlowLayout());
[Link](btnMorning);
[Link](btnAfternoon);
[Link](btnEvening);
[Link](btnClose);
[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
[Link]("Good Morning");
}
});

[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
[Link]("Good Afternoon");
}
});

[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
[Link]("Good Evening");
}
});

[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
[Link](0);
}
});
[Link](300, 200);
[Link](true);
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
SEP JAVA LAB MANUAL

5. Program to demonstrate various mouse handling events.

import [Link].*;
import [Link].*;
public class MouseEventExample extends Frame
{
public MouseEventExample()
{
setTitle("Mouse Event Demo");
setSize(300, 200);
setLayout(new FlowLayout());
addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked at: " + [Link]() + ", " + [Link]());
}
public void mousePressed(MouseEvent e)
{
[Link]("Mouse Pressed at: " + [Link]() + ", " + [Link]());
}
public void mouseReleased(MouseEvent e)
{
[Link]("Mouse Released at: " + [Link]() + ", " + [Link]());
}
});

addMouseMotionListener(new MouseAdapter()
{
public void mouseMoved(MouseEvent e)
{
[Link]("Mouse Moved at: " + [Link]() + ", " + [Link]());
}
});
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
SEP JAVA LAB MANUAL

[Link](0);
}
});

setVisible(true);
}

public static void main(String[] args)


{
new MouseEventExample();
}
}

[Link] to read and write Binary I/O file.

import [Link].*;
public class BinaryFileExample
{
public static void main(String[] args)
{
byte[] data = {10, 20, 30, 40, 50};
try(FileOutputStream fos = new FileOutputStream("[Link]"))
{
[Link](data);
[Link]("Data written to the file.");
}
catch (IOException e)
{
[Link]("Error writing to the file: " + [Link]());
}
try(FileInputStream fis = new FileInputStream("[Link]"))
{
int byteRead;
[Link]("Data read from the file: ");
while ((byteRead = [Link]()) != -1)
{
[Link](byteRead + " ");
}
[Link]();
SEP JAVA LAB MANUAL

} catch (IOException e)
{
[Link]("Error reading from the file: " + [Link]());
}
}
}

7. Program to create a window with three buttons (Father, Mother, Close). Display
the respective details of father and mother (name, age, and designation) using
AWT controls.

import [Link].*;
import [Link].*;
public class FamilyDetails extends Frame
{
public FamilyDetails()
{
setTitle("Family Details") ;
setSize(400, 200);
setLayout(new FlowLayout());
Button btnFather = new Button("Father");
Button btnMother = new Button("Mother");
Button btnClose = new Button("Close");

Label lblDetails = new Label("");


[Link]([Link]);
[Link](new Dimension(350, 40));
add(btnFather);
add(btnMother);
add(btnClose);
add(lblDetails);
[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
[Link]("Father: John, Age: 45, Designation: Engineer");
}
});
[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
[Link]("Mother: Mary, Age: 40, Designation: Teacher");
}
});
[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
[Link](0);
}
SEP JAVA LAB MANUAL

});

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
setVisible(true);
}

public static void main(String[] args)


{
new FamilyDetails();
}
}

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

import [Link].*;
class MenuExample
{
MenuExample()
{
Frame f=new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
[Link](i1);
[Link](i2);
[Link](i3);
[Link](i4);
[Link](i5);
[Link](submenu);
[Link](menu);
[Link](mb);
[Link](400,400);
[Link](null);
[Link](true);
}
SEP JAVA LAB MANUAL

public static void main(String args[])


{
new MenuExample();
}
}

output

Common questions

Powered by AI

The Java program uses Abstract Window Toolkit (AWT) to create a window containing buttons by setting up a 'Frame' and adding 'Button' objects arranged using 'FlowLayout'. Event handling is managed by adding event listeners to these buttons, such as 'ActionListener'. For instance, clicking buttons triggers actions defined in 'actionPerformed' methods that print messages or change the window's state, like exiting the application when the close button is clicked .

Binary I/O operations in Java are demonstrated by reading from and writing to binary files using 'FileInputStream' and 'FileOutputStream'. The operations are encapsulated within try-with-resources statements that ensure resources are closed automatically, preventing leaks. The program writes an array of bytes to a file and reads them back, showcasing fundamental file operations with error handling for 'IOException'. This highlights Java's robust exception handling features and the practical application of binary file I/O in handling non-character data efficiently .

The Java programs handle exceptions using try-catch blocks. For a negative array size exception, the program attempts to create an array with a negative size within a try block and catches the exception using 'catch (NegativeArraySizeException e)'. Similarly, a null pointer exception is demonstrated by trying to access methods on a null object reference within a try block and would be caught using 'catch (NullPointerException e)' if defined .

The Java program demonstrates single inheritance by defining a base class 'BaseCalculator' and a derived class 'AdvancedCalculator'. The 'BaseCalculator' contains a method 'add' for addition, and the derived class 'AdvancedCalculator' extends 'BaseCalculator' by adding a new method 'multiply' for multiplication. This structure follows the inheritance hierarchy where 'AdvancedCalculator' inherits the properties and methods of 'BaseCalculator' while introducing additional functionalities .

Method overloading in the 'Calculator' class allows multiple 'add' methods with different parameter lists. This provides flexibility, enabling the class to handle the addition of two or three numbers through the same method name 'add', improving usability and code readability by providing different ways to sum numbers depending on the number of inputs provided .

The 'Student' class stores student information such as registration number, name, and marks for three subjects. It includes a method to calculate total marks across these subjects, 'getTotalMarks'. An array of 'Student' objects is created, each storing individual student data. The program, through loops, populates the student data and outputs each student's total marks, demonstrating encapsulation and object-oriented design in managing collections of related data .

The program constructs user interfaces by utilizing AWT components to create a frame with a 'MenuBar', adding 'Menu' and 'MenuItem' objects to form hierarchical structures with pull-down menus. This setup enhances interaction by logically grouping commands, allowing users to navigate and select operations from the menu items easily, thereby simulating real application interfaces and improving user experience through organized and accessible design .

The programs demonstrate generating and handling multiple exceptions through deliberate errors, such as creating an array with negative size or null reference access. Each scenario is enclosed in try-catch blocks tailored to specific exceptions like 'NegativeArraySizeException', 'NullPointerException', and 'NumberFormatException'. These strategies allow the program to manage errors gracefully by providing informative messages and maintaining application flow, preventing abrupt termination, thus illustrating robust error handling practices .

The Java application uses AWT to handle mouse events by implementing 'MouseListener' and 'MouseMotionListener' interfaces. It captures different types of mouse interactions: 'mouseClicked', 'mousePressed', 'mouseReleased', 'mouseMoved', and 'mouseDragged', each triggering respective print statements. By adding listeners to the components, the program responds in real-time to user interactions on the window, enhancing interactivity and user feedback mechanisms .

The program reads a string input, reverses it using 'StringBuilder' and 'reverse()', and compares the reversed string to the original using 'equals()'. If both are identical, the string is declared a palindrome; otherwise, it is not. This logic relies on the fact that palindromes read the same forward and backward .

You might also like