Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Java Programs 2semester

The document contains a series of Java programming exercises for a second-semester practical record. It includes programs for various concepts such as conditional statements, loops, classes, inheritance, exception handling, and GUI components using AWT. Each program is accompanied by its code and expected output.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Java Programs 2semester

The document contains a series of Java programming exercises for a second-semester practical record. It includes programs for various concepts such as conditional statements, loops, classes, inheritance, exception handling, and GUI components using AWT. Each program is accompanied by its code and expected output.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Practical record java 2semester

Part A

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

Public class Main {

Public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println(“Enter a number: “);

Int num = scanner.nextInt();

If (num > 0) {

System.out.println(num + “ is positive.”);

} else if (num < 0) {

System.out.println(num + “ is negative.”);

} else {

System.out.println(num + “ is zero.”);

Output:

Enter a number: 10

10 is positive.

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

```
Public class Main {

Public static void main(String[] args) {

For (int I = 1; I <= 10; i++) {

Long factorial = calculateFactorial(i);

System.out.println(“Factorial of “ + I + “ = “ + factorial);

Public static long calculateFactorial(int num) {

Long factorial = 1;

For (int I = 1; I <= num; i++) {

Factorial *= I;

Return factorial;

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.*

```

Public class Student {

Private String name;

Private int age;

Public Student(String name, int age) {

This.name = name;

This.age = age;

Public void displayInfo() {

System.out.println(“Name: “ + name);

System.out.println(“Age: “ + age);

Public static void main(String[] args) {

Student student1 = new Student(“John Doe”, 20);

Student1.displayInfo();

Student student2 = new Student(“Jane Doe”, 22);

Student2.displayInfo();

}
}

Output:

Name: John Doe

Age: 20

Name: Jane Doe

Age: 22

*4. Program to demonstrate method overloading.*

```

Public class Calculator {

Public int add(int num1, int num2) {

Return num1 + num2;

Public double add(double num1, double num2) {

Return num1 + num2;

Public int add(int num1, int num2, int num3) {

Return num1 + num2 + num3;

Public static void main(String[] args) {

Calculator calculator = new Calculator();


System.out.println(calculator.add(10, 20));

System.out.println(calculator.add(10.5, 20.7));

System.out.println(calculator.add(10, 20, 30));

Output:

30

31.2

60

*5. Program to demonstrate single inheritance (simple calculator – base class, Advanced
Calculator-derived class).*

```

Public class SimpleCalculator {

Public int add(int num1, int num2) {

Return num1 + num2;

Public int subtract(int num1, int num2) {

Return num1 – num2;

Public class AdvancedCalculator extends SimpleCalculator {


Public int multiply(int num1, int num2) {

Return num1 * num2;

Public int divide(int num1, int num2) {

If (num2 != 0) {

Return num1 / num2;

} else {

Return 0;

Public static void main(String[] args) {

AdvancedCalculator calculator = new AdvancedCalculator();

System.out.println(calculator.add(10, 20));

System.out.println(calculator.subtract(30, 10));

System.out.println(calculator.multiply(10, 20));

System.out.println(calculator.divide(20, 10));

Output:

30

20

200

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

```

Import java.util.Arrays;

Public class Main {

Public static void main(String[] args) {

Int[] numbers = {10, 20, 30, 40, 50};

Arrays.sort(numbers);

System.out.println(“Minimum element: “ + numbers[0]);

System.out.println(“Maximum element: “ + numbers[numbers.length – 1]);

Output:

Minimum element: 10

Maximum element: 50

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

```

Public class Main {

Public static void main(String[] args) {

String str = “madam”;


String reversedStr = reverseString(str);

If (str.equals(reversedStr)) {

System.out.println(str + “ is a palindrome.”);

} else {

System.out.println(str + “ is not a palindrome.”);

Public static String reverseString(String str) {

StringBuilder reversedStr = new StringBuilder();

For (int I = str.length() – 1

Output:

Madam is a palindrome

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.

```

Public class Student {

Private int regNo;

Private String name;

Private int marks1;

Private int marks2;

Private int marks3;

Public Student(int regNo, String name, int marks1, int marks2, int marks3) {
This.regNo = regNo;

This.name = name;

This.marks1 = marks1;

This.marks2 = marks2;

This.marks3 = marks3;

Public int calculateTotalMarks() {

Return marks1 + marks2 + marks3;

Public void displayInfo() {

System.out.println(“Reg. No.: “ + regNo);

System.out.println(“Name: “ + name);

System.out.println(“Marks 1: “ + marks1);

System.out.println(“Marks 2: “ + marks2);

System.out.println(“Marks 3: “ + marks3);

System.out.println(“Total Marks: “ + calculateTotalMarks());

Public static void main(String[] args) {

Student[] students = new Student[3];

Students[0] = new Student(101, “John Doe”, 90, 80, 70);

Students[1] = new Student(102, “Jane Doe”, 95, 85, 75);

Students[2] = new Student(103, “Bob Smith”, 90, 80, 70);


For (Student student : students) {

Student.displayInfo();

System.out.println();

Output:

```

Student 1:

Reg. No.: 101

Name: John Doe

Marks: 90 80 70

Total Marks: 240

Student 2:

Reg. No.: 102

Name: Jane Doe

Marks: 95 85 75

Total Marks: 255

Student 3:

Reg. No.: 103

Name: Bob Smith

Marks: 90 80 70

Total Marks: 240


Part B problems

1. Program to generate negative array size exception

```

Public class Main {

Public static void main(String[] args) {

Int[] array = new int[-5];

```

Output:

```

Exception in thread “main” java.lang.NegativeArraySizeException

At Main.main(Main.java:3)

```

2. Program to generate NullPointer Exception.

```

Public class Main {

Public static void main(String[] args) {

String str = null;


System.out.println(str.length());

```

Output:

```

Exception in thread “main” java.lang.NullPointerException

At Main.main(Main.java:4)

```

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

```

Import java.util.InputMismatchException;

Import java.util.Scanner;

Public class Main {

Public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

Try {

System.out.println(“Enter first number: “);

Int a = scanner.nextInt();

System.out.println(“Enter second number: “);

Int b = scanner.nextInt();
System.out.println(“Sum: “ + (a + b));

} catch (InputMismatchException e) {

System.out.println(“Error: Invalid input. Please enter a valid number.”);

```

Output:

```

Enter first number:

Abc

Error: Invalid input. Please enter a valid number.

```

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 java.awt.*;

Import java.awt.event.*;

Public class Main extends Frame implements ActionListener {

Button morningButton, afternoonButton, eveningButton, closeButton;

Public Main() {
morningButton = new Button(“M”);

afternoonButton = new Button(“A”);

eveningButton = new Button(“E”);

closeButton = new Button(“Close”);

morningButton.addActionListener(this);

afternoonButton.addActionListener(this);

eveningButton.addActionListener(this);

closeButton.addActionListener(this);

add(morningButton, BorderLayout.NORTH);

add(afternoonButton, BorderLayout.CENTER);

add(eveningButton, BorderLayout.EAST);

add(closeButton, BorderLayout.SOUTH);

setSize(300, 200);

setVisible(true);

Public void actionPerformed(ActionEvent e) {

If (e.getSource() == morningButton) {

System.out.println(“Good Morning”);

} else if (e.getSource() == afternoonButton) {

System.out.println(“Good Afternoon”);

} else if (e.getSource() == eveningButton) {

System.out.println(“Good Evening”);
} else if (e.getSource() == closeButton) {

System.exit(0);

Public static void main(String[] args) {

New Main();

```

Output:

AWT window with 4 buttons M/A/E/Close

5. Program to demonstrate the various mouse handling events.

```

Import java.awt.*;

Import java.awt.event.*;

Public class Main extends Frame implements MouseListener, MouseMotionListener {

Label label;

Public Main() {

Label = new Label(“Mouse Events”);


addMouseListener(this);

addMouseMotionListener(this);

add(label, BorderLayout.CENTER);

setSize(300, 200);

setVisible(true);

Public void mouseClicked(MouseEvent e) {

Label.setText(“Mouse Clicked”);

Public void mousePressed(MouseEvent e) {

Label.setText(“Mouse Pressed”);

Public void mouseReleased(MouseEvent e) {

Label.setText(“Mouse Released”);

Public void mouseEntered(MouseEvent e) {

Label.setText(“Mouse Entered”);

}
Public void mouseExited(MouseEvent e) {

Label.setText(“Mouse Exited”);

Public void mouseDragged(MouseEvent e) {

Label.setText(“Mouse Dragged”);

Public void mouseMoved(MouseEvent e) {

Label.setText(“Mouse Moved”);

Public static void main(String[] args) {

New Main();

```

Output:

AWT window demonstrating various mouse handling events

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

```

Import java.io.*;
Public class Main {

Public static void main(String[] args) {

Try {

// Write to binary file

FileOutputStream fos = new FileOutputStream(“binary_file.dat”);

DataOutputStream dos = new DataOutputStream(fos);

Dos.writeInt(10);

Dos.writeDouble(20.5);

Dos.writeBoolean(true);

Dos.close();

Fos.close();

// Read from binary file

FileInputStream fis = new FileInputStream(“binary_file.dat”);

DataInputStream dis = new DataInputStream(fis);

Int num1 = dis.readInt();

Double num2 = dis.readDouble();

Boolean bool = dis.readBoolean();

System.out.println(“Int: “ + num1);

System.out.println(“Double: “ + num2);

System.out.println(“Boolean: “ + bool);
Dis.close();

Fis.close();

} catch (IOException e) {

System.out.println(“Error: “ + e.getMessage());

```

Output:

Int: 10

Double: 20.5

Boolean: true

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 java.awt.*;

Import java.awt.event.*;

Public class Main extends Frame implements ActionListener {

Button fatherButton, motherButton, closeButton;

Label fatherNameLabel, fatherAgeLabel, fatherDesignationLabel;

Label motherNameLabel, motherAgeLabel, motherDesignationLabel;


Public Main() {

fatherButton = new Button(“Father”);

motherButton = new Button(“Mother”);

closeButton = new Button(“Close”);

fatherNameLabel = new Label(“Father’s Name: “);

fatherAgeLabel = new Label(“Father’s Age: “);

fatherDesignationLabel = new Label(“Father’s Designation: “);

motherNameLabel = new Label(“Mother’s Name: “);

motherAgeLabel = new Label(“Mother’s Age: “);

motherDesignationLabel = new Label(“Mother’s Designation: “);

fatherButton.addActionListener(this);

motherButton.addActionListener(this);

closeButton.addActionListener(this);

add(fatherButton, BorderLayout.NORTH);

add(motherButton, BorderLayout.CENTER);

add(closeButton, BorderLayout.EAST);

add(fatherNameLabel, BorderLayout.WEST);

add(fatherAgeLabel, BorderLayout.SOUTH);

add(fatherDesignationLabel, BorderLayout.LINE_START);

add(motherNameLabel, BorderLayout.LINE_END);

add(motherAgeLabel, BorderLayout.PAGE_START);
add(motherDesignationLabel, BorderLayout.PAGE_END);

setSize(400, 300);

setVisible(true);

Public void actionPerformed(ActionEvent e) {

If (e.getSource() == fatherButton) {

fatherNameLabel.setText(“Father’s Name: John Doe”);

fatherAgeLabel.setText(“Father’s Age: 45”);

fatherDesignationLabel.setText(“Father’s Designation: Engineer”);

} else if (e.getSource() == motherButton) {

motherNameLabel.setText(“Mother’s Name: Jane Doe”);

motherAgeLabel.setText(“Mother’s Age: 40”);

motherDesignationLabel.setText(“Mother’s Designation: Doctor”);

} else if (e.getSource() == closeButton) {

System.exit(0);

Public static void main(String[] args) {

New Main();

```
Output:

AWT window with three buttons father, mother and close. Displays the respective details of
father and mother as name, age and designation when respective buttons are clicked.

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

```

Import java.awt.*;

Import java.awt.event.*;

Public class Main extends Frame implements ActionListener {

MenuBar menuBar;

Menu fileMenu, editMenu;

MenuItem newFileItem, openFileItem, exitItem;

MenuItem cutItem, copyItem, pasteItem;

Public Main() {

menuBar = new MenuBar();

fileMenu = new Menu(“File”);

editMenu = new Menu(“Edit”);

newFileItem = new MenuItem(“New”);

openFileItem = new MenuItem(“Open”);

exitItem = new MenuItem(“Exit”);


cutItem = new MenuItem(“Cut”);

copyItem = new MenuItem(“Copy”);

pasteItem = new MenuItem(“Paste”);

newFileItem.addActionListener(this);

openFileItem.addActionListener(this);

exitItem.addActionListener(this);

cutItem.addActionListener(this);

copyItem.addActionListener(this);

pasteItem.addActionListener(this);

fileMenu.add(newFileItem);

fileMenu.add(openFileItem);

fileMenu.add(exitItem);

editMenu.add(cutItem);

editMenu.add(copyItem);

editMenu.add(pasteItem);

menuBar.add(fileMenu);

menuBar.add(editMenu);

setMenuBar(menuBar);

setSize(400, 300);
setVisible(true);

Public void actionPerformed(ActionEvent e) {

If (e.getSource() == newFileItem) {

System.out.println(“New file created”);

} else if (e.getSource() == openFileItem) {

System.out.println(“File opened”);

} else if (e.getSource() == exitItem) {

System.exit(0);

} else if (e.getSource() == cutItem) {

System.out.println(“Text cut”);

} else if (e.getSource() == copyItem) {

System.out.println(“Text copied”);

} else if (e.getSource() == pasteItem) {

System.out.println(“Text pasted”);

Public static void main(String[] args) {

New Main();

```

Output:
AWT window with menu bar and pull-down menus. Displays messages when menu items
are clicked.

You might also like