0% found this document useful (0 votes)
79 views

JAVA LAB Prog

Uploaded by

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

JAVA LAB Prog

Uploaded by

Murali Vijay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

1. Write a simple java application, to print the message, “Hello, world!


2. Write a program to demonstrate a division by zero exception
3. Write a program to create a user defined exception
4. Write a java program to add two integers and two float numbers. Using function overloading.
5. Write a program to perform mathematical operations. Using Inheritance.
6. Write a java program to create a student class to demonstrate constructor. The pass mark for each subject is 50.
If a candidate fails in any one of the subjects his total mark must be declared as zero
7. Write a program to handle Null Pointer Exception and use the “finally” method to display a message to the user.
8. Write a program to Create a user defined Package in Java.
9. Write a program which create and displays a message on the window.
10. Write a program to draw several shapes in the window.
11. Calculating Area of a Square and Triangle Using Java Interface.
12. Square and Square Root Calculation Using Abstract Class in Java.
13. Using Generics in Java to Handle Different Data Types.
14. Create a frame which displays your personal details with respect to a button click.

1. Write a simple java application, to print the message, “Hello, world!”

class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Output

Hello, World!

2. Write a program to demonstrate a division by zero exception

public class DivisionByZero {


public static void main(String[] args) {
int numerator = 10;
int denominator = 0;

try {
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}.

Output
Exception caught: / by zero

3. Write a program to create a user defined exception

// Custom exception class


class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}

// Class that uses the custom exception


public class UserDefinedExceptionDemo {
// Method that throws the custom exception
static void checkAge(int age) throws CustomException {
if (age < 18) {
throw new CustomException("Age must be 18 or above.");
} else {
System.out.println("You are eligible to vote!");
}
}

// Main method to demonstrate the custom exception


public static void main(String[] args) {
try {
int age = 15;
checkAge(age);
} catch (CustomException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}

Output

Exception caught: Age must be 18 or above.

4. Write a java program to add two integers and two float numbers. Using function overloading.

public class FunctionOverloading {


// Method to add two integers
static int add(int a, int b) {
return a + b;
}

// Method to add two float numbers


static float add(float a, float b) {
return a + b;
}

public static void main(String[] args) {


int num1Int = 5, num2Int = 10;
float num1Float = 2.5f, num2Float = 3.7f;

// Adding two integers


int sumInt = add(num1Int, num2Int);
System.out.println("Sum of integers: " + sumInt);

// Adding two float numbers


float sumFloat = add(num1Float, num2Float);
System.out.println("Sum of float numbers: " + sumFloat);
}
}

Output

Sum of integers: 15
Sum of float numbers: 6.2

5. Write a program to perform mathematical operations. Using Inheritance.

// Class to perform addition and subtraction


class AddSub {
// Method to add two numbers
public int add(int a, int b) {
return a + b;
}

// Method to subtract two numbers


public int subtract(int a, int b) {
return a - b;
}
}

// Class to perform multiplication and division, inheriting from AddSub


class MulDiv extends AddSub {
// Method to multiply two numbers
public int multiply(int a, int b) {
return a * b;
}

// Method to divide two numbers


public int divide(int a, int b) {
if (b != 0) {
return a / b;
} else {
System.out.println("Error: Division by zero.");
return 0;
}
}
}

// Main class to perform mathematical operations


public class MathOperations {
public static void main(String[] args) {
// Creating an instance of MulDiv
MulDiv calculator = new MulDiv();

// Performing mathematical operations


int num1 = 10, num2 = 5;
System.out.println("Addition: " + calculator.add(num1, num2));
System.out.println("Subtraction: " + calculator.subtract(num1, num2));
System.out.println("Multiplication: " + calculator.multiply(num1, num2));
System.out.println("Division: " + calculator.divide(num1, num2));
}
}

Output

Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2

6. Write a java program to create a student class to demonstrate constructor.


1)The pass mark for each subject is 50.
2)If a candidate fails in any one of the subjects his total mark must be declared as zero.

import java.util.Scanner;

public class Student {


private int enrollmentId;
private String name;
private int sub1Mark;
private int sub2Mark;
private int sub3Mark;
private int totalMarks;

// Constructor
public Student(int enrollmentId, String name, int sub1Mark, int sub2Mark, int
sub3Mark) {
this.enrollmentId = enrollmentId;
this.name = name;
this.sub1Mark = sub1Mark;
this.sub2Mark = sub2Mark;
this.sub3Mark = sub3Mark;

// Calculate total marks only if the student passes in all subjects


if (sub1Mark >= 50 && sub2Mark >= 50 && sub3Mark >= 50) {
this.totalMarks = sub1Mark + sub2Mark + sub3Mark;
} else {
this.totalMarks = 0; // If the student fails in any subject, total marks
is set to zero
}
}

// Function to accept student details


public void acceptDetails() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Enrollment ID:");
enrollmentId = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.println("Enter Name:");
name = scanner.nextLine();
System.out.println("Enter Mark of Subject 1:");
sub1Mark = scanner.nextInt();
System.out.println("Enter Mark of Subject 2:");
sub2Mark = scanner.nextInt();
System.out.println("Enter Mark of Subject 3:");
sub3Mark = scanner.nextInt();

// Calculate total marks only if the student passes in all subjects


if (sub1Mark >= 50 && sub2Mark >= 50 && sub3Mark >= 50) {
totalMarks = sub1Mark + sub2Mark + sub3Mark;
} else {
totalMarks = 0; // If the student fails in any subject, total marks is set
to zero
}
}

// Function to display student details


public void displayDetails() {
System.out.println("Enrollment ID: " + enrollmentId);
System.out.println("Name: " + name);
System.out.println("Mark of Subject 1: " + sub1Mark);
System.out.println("Mark of Subject 2: " + sub2Mark);
System.out.println("Mark of Subject 3: " + sub3Mark);
System.out.println("Total Marks: " + totalMarks);
System.out.println();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student[] students = new Student[3];

// Accept details for each student


for (int i = 0; i < students.length; i++) {
System.out.println("Enter details for Student " + (i + 1) + ":");
System.out.println("===========================");
students[i] = new Student(0, "", 0, 0, 0); // Initialize with default
values
students[i].acceptDetails();
}

// Display details for each student


System.out.println("Student Details:");
System.out.println("================");
for (Student student : students) {
student.displayDetails();
}
}
}

Output

Enter details for Student 1:


===========================
Enter Enrollment ID:
101
Enter Name:
Vinay
Enter Mark of Subject 1:
76
Enter Mark of Subject 2:
45
Enter Mark of Subject 3:
82
Enter details for Student 2:
===========================
Enter Enrollment ID:
102
Enter Name:
kiran
Enter Mark of Subject 1:
60
Enter Mark of Subject 2:
73
Enter Mark of Subject 3:
57
Enter details for Student 3:
===========================
Enter Enrollment ID:
103
Enter Name:
sri Lakshmi
Enter Mark of Subject 1:
45
Enter Mark of Subject 2:
70
Enter Mark of Subject 3:
67
Student Details:
================
Enrollment ID: 101
Name: Vinay
Mark of Subject 1: 76
Mark of Subject 2: 45
Mark of Subject 3: 82
Total Marks: 0

Enrollment ID: 102


Name: kiran
Mark of Subject 1: 60
Mark of Subject 2: 73
Mark of Subject 3: 57
Total Marks: 190

Enrollment ID: 103


Name: sri Lakshmi
Mark of Subject 1: 45
Mark of Subject 2: 70
Mark of Subject 3: 67
Total Marks: 0

7. Write a program to handle Null Pointer Exception and use the “finally” method to display a message to the user.

public class HandleNullPointerException {


public static void main(String[] args) {
try {
String str = null;
System.out.println("Length of the string: " + str.length());
} catch (NullPointerException e) {
System.out.println("NullPointerException occurred: " + e.getMessage());
} finally {
System.out.println("Thank you for using our program!");
}
}
}

Output

NullPointerException occurred: Cannot invoke "String.length()" because "<local1>" is


null
Thank you for using our program!

=== Code Execution Successful ===

8. Write a program to Create a user defined Package in Java.

create a simple package called utilities which contains a class MathHelper that provides some basic mathematical functions.

Here's the directory structure for our package:

user-defined-package/

├── src/
│ └── utilities/
│ └── MathHelper.java

└── Main.java

Now, let's define the contents of the files:


MathHelper.java (inside the utilities package:

package utilities;

public class MathHelper {


public static int add(int a, int b) {
return a + b;
}

public static int subtract(int a, int b) {


return a - b;
}

public static int multiply(int a, int b) {


return a * b;
}

public static double divide(double a, double b) {


if (b == 0) {
throw new ArithmeticException("Division by zero!");
}
return a / b;
}
}

Main.java:

import utilities.MathHelper;

public class Main {


public static void main(String[] args) {
int a = 10;
int b = 5;

// Using methods from MathHelper class


int sum = MathHelper.add(a, b);
int difference = MathHelper.subtract(a, b);
int product = MathHelper.multiply(a, b);
double quotient = MathHelper.divide(a, b);

// Output the results


System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
}
}

9. Write a program which create and displays a message on the window.

import javax.swing.JFrame;
import javax.swing.JLabel;

public class MessageWindow {


public static void main(String[] args) {
// Create a JFrame instance
JFrame frame = new JFrame("Message Window");

// Create a JLabel instance with the message


JLabel label = new JLabel("Hello, this is a message!");

// Add the JLabel to the JFrame


frame.add(label);

// Set the size of the JFrame


frame.setSize(300, 200);

// Set the default close operation


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make the frame visible
frame.setVisible(true);
}
}

10.Write a program to draw several shapes in the window.

import javax.swing.*;
import java.awt.*;

public class ShapeDrawer extends JPanel {

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);

// Set the color for drawing


g.setColor(Color.RED);

// Draw a rectangle
g.drawRect(50, 50, 100, 50);

// Set the color for filling


g.setColor(Color.BLUE);

// Fill a rectangle
g.fillRect(200, 50, 100, 50);

// Draw an oval
g.setColor(Color.GREEN);
g.drawOval(50, 150, 100, 100);

// Fill an oval
g.setColor(Color.ORANGE);
g.fillOval(200, 150, 100, 100);

// Draw a line
g.setColor(Color.MAGENTA);
g.drawLine(50, 300, 300, 300);
}

public static void main(String[] args) {


JFrame frame = new JFrame("Shape Drawer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);

// Create an instance of ShapeDrawer and add it to the frame


ShapeDrawer shapeDrawer = new ShapeDrawer();
frame.add(shapeDrawer);

frame.setVisible(true);
}
}

11.Find Area of square Using Interface


import java.util.Scanner;

public class AreaOfSquare implements area{


public static void main (String[] args){
Scanner sc=new Scanner(System.in);
AreaOfSquare obj=new AreaOfSquare();

System.out.println("Enter base");
Double b=sc.nextDouble();
System.out.println("enter the height");
double h=sc.nextDouble();
double a=obj.areaTriangle(b,h);
System.out.println("area of triangle"+a);
System.out.println("/////////////////");
System.out.println("Ente the base to
calculate area of a square");
Double ba=sc.nextDouble();
Double s=obj.areaSquare(ba);
System.out.println("area of square"+s);
}
@Override
public double areaTriangle(double base,
double height) {
return 0.5*base*height;
}
@Override
public double areaSquare(double base){
return base * base;
}
}

//Area class

public interface area {


double areaTriangle(double base, double height);
double areaSquare(double base);
}

14.Square And SquareRoot using Interface

// SquareAndSquareRoot
package pack;

public abstract class SquareAndSquareRoot {


abstract int square(int a);
double squareroot(int a) {
return Math.sqrt(a);
}
}

// Calculation class
package pack;

import java.util.Scanner;

public class Calculation extends SquareAndSquareRoot {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Calculation obj = new Calculation();
System.out.println("Enter a number");
int n = sc.nextInt();
System.out.println("Square of " + n + ": " +
obj.square(n));
System.out.println("Square root of " + n + ": " +
obj.squareroot(n));
sc.close(); // Closing the scanner to avoid resource leak
}
@Override
int square(int a) {
return a * a;
}
}

You might also like