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

java Lab Manual

The document provides a series of Java programming exercises covering various concepts such as data types, variable scope, string operations, control structures, object-oriented programming (including inheritance and interfaces), exception handling, and method overloading. Each exercise includes a code snippet and, in some cases, sample output demonstrating the functionality of the program. The exercises are designed to help learners practice and understand fundamental Java programming principles.

Uploaded by

jeevan63604
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)
38 views

java Lab Manual

The document provides a series of Java programming exercises covering various concepts such as data types, variable scope, string operations, control structures, object-oriented programming (including inheritance and interfaces), exception handling, and method overloading. Each exercise includes a code snippet and, in some cases, sample output demonstrating the functionality of the program. The exercises are designed to help learners practice and understand fundamental Java programming principles.

Uploaded by

jeevan63604
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
You are on page 1/ 21

Object Oriented programming LAB

1.Java Program to display “Hello World” and display the size of all the data types.

class SizeOfDataTypes

public static void main(String[] args)

System.out.println("Hello World");

System.out.println("S.No.\t\t Data Type\t\t Size");

System.out.println("1\t\t Byte\t\t\t" + Byte.SIZE);

System.out.println("2\t\t Short\t\t\t" + Short.SIZE);

System.out.println("3\t\t Integer\t\t" + Integer.SIZE);

System.out.println("4\t\t Float\t\t\t" + Float.SIZE);

System.out.println("5\t\t Long\t\t\t" + Long.SIZE);

System.out.println("6\t\t Double\t\t\t" + Double.SIZE);

System.out.println("7\t\t Character\t\t" + Character.SIZE);

2.Java Program to implement the usage of static,local and global variables.

public class InstanceCounter {

private static int numInstances = 0;

protected static int getCount() {

return numInstances;

private static void addInstance() {

numInstances++;

InstanceCounter() {

InstanceCounter.addInstance();

public static void main(String[] arguments) {

float pi=22/7f;

System.out.println("Value of Pi = "+pi);

System.out.println("Starting with " + InstanceCounter.getCount() + " instances");

for (int i=0; i < 5; ++i) {


new InstanceCounter();

System.out.println("Created "+ InstanceCounter.getCount() + " instances");

3.Java Program to implement string operations string length, string concatenate, substring

class StringOperations {

public static void main(String[] args) {

String firstname="Sachin";

String middlename=" Ramesh";

String lastname=" Tendulkar";

String name=firstname.concat(middlename).concat(lastname);

System.out.println("Name is: " + name);

System.out.println("Lenth of name is: " + name.length());

System.out.println("substing of name is: " + name.substring(7,13));

4.Java Program to find the maximum of three numbers

import java.util.Scanner;

class MaxOfThreeNumbers {

public static void main(String[] args) {

int a, b, c, largest, temp;

Scanner sc = new Scanner(System.in);

System.out.println("Enter the first number:");

a = sc.nextInt();

System.out.println("Enter the second number:");

b = sc.nextInt();

System.out.println("Enter the third number:");

c = sc.nextInt();

temp=a>b?a:b;

largest=c>temp?c:temp;

System.out.println("The largest number is: "+largest);

5.Java program to check whether the number is odd or even


import java.util.Scanner;

public class EvenOdd {

public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

System.out.print("Enter a number: ");

int num = reader.nextInt();

if(num%2==0)

System.out.println(num + " is even");

else

System.out.println(num + " is odd");

6.Java Program to implement default and parameterized constructors

import java.util.Scanner;

class Box {

double width;

double height;

double depth;

Box() {

width = 12.7d;

height = 15.0d;

depth = 5.6d;

Box(double w, double h, double d) {

width = w;

height = h;

depth = d;

double volume() {

return width * height * depth;

class Jain {

public static void main(String[] args) {

Box Box1 = new Box();


Box Box2 = new Box(4.7d, 8.5d, 6.3d);

double vol;

vol = Box1.volume();

System.out.println("Volume of Box1: " + vol);

// get volume of second box

vol = Box2.volume();

System.out.println("Volume of Box2: " + vol);

7.Java Program to implement an array of objects

import java.util.Scanner;

class Car {

public String name;

public int miles;

public Car(String name, int miles) {

this.name=name;

this.miles=miles;

public void printDetails() {

System.out.println(name+" - "+miles);

class Main {

public static void main(String[] args) {

Car cars[] = {

new Car("Tesla", 142000),

new Car("BMW", 485000),

new Car("Tata", 564000),

new Car("Ford", 580000)

};

for(Car car: cars)

car.printDetails();

8. Java program to implement Single Inheritance


import java.util.Scanner;

// Base class (Super class)

class Bicycle {

public int gear;

public int speed;

public Bicycle(int gear, int speed) {

this.gear = gear;

this.speed = speed;

public void applyBrake(int decrement) {

speed -= decrement;

public void speedUp(int increment) {

speed += increment;

public String toString() {

return "No of gears are " + gear + "\nSpeed of bicycle is " + speed;

// Derived class (Sub class)

class MountainBike extends Bicycle {

public int seatHeight;

public MountainBike(int gear, int speed, int startHeight) {

super(gear, speed);

seatHeight = startHeight;

public void setHeight(int newValue) {

seatHeight = newValue;

public String toString() {

return super.toString() + "\nSeat height is " + seatHeight;

// Main class

class Main1 {
public static void main(String[] args) {

MountainBike mb = new MountainBike(3, 100, 25);

System.out.println(mb.toString());

OUTPUT:

No of gears are 3

speed of bicycle is 100

seat height is 25

9. Java program to implement Multiple Inheritance using Interface

interface Character {

void attack();

interface Weapon {

void use();

class Warrior implements Character, Weapon {

public void attack() {

System.out.println("Warrior attacks with a sword.");

public void use() {

System.out.println("Warrior uses a sword.");

class Mage implements Character, Weapon {

public void attack() {

System.out.println("Mage attacks with a wand.");

public void use() {

System.out.println("Mage uses a wand.");

class Main3 {

public static void main(String[] args) {

Warrior warrior = new Warrior();


Mage mage = new Mage();

warrior.attack();

warrior.use();

mage.attack();

mage.use();

OUTPUT:

Warrior attacks with a sword.

Warrior uses a sword.

Mage attacks with a wand.

Mage uses a wand.

10. Java program to implement an applet

//SumNumsInteractive java

import java.applet.Applet;

import java.awt.*;

public class SumNumsInteractive extends Applet

TextField text1, text2;

public void init()

text1=new TextField(10);

text2=new TextField(10);

text1.setText("0");

text2.setText("0");

add(text1);

add(text2);

public void paint(Graphics g)

int num1=0;

int num2=0;

int sum;

String s1,s2,s3;
g.drawString("Input a number in each box", 10, 50);

try {

s1=text1.getText();

num1=Integer.parseInt(s1);

s2=text2.getText();

num2=Integer.parseInt(s2);

catch(Exception el)

sum=num1+num2;

String str = "THE SUM IS: "+String.valueOf(sum);

g.drawString (str,100,125);

public boolean action(Event ev, Object obj)

repaint();

return true;

11. Java program to demonstrate a division by zero exception

import java.util.Scanner;

public class Division_By_Zero_Exception {

public static void main(String[] args) {

try{

int number1, number2, output;

Scanner sc=new Scanner(System.in);

System.out.print("Enter first number: ");

number1=sc.nextInt();

System.out.print("Enter second number: ");

number2=sc.nextInt();

output=number1/number2;

System.out.println("Result:"+output);

catch(ArithmeticException e) {
System.out.println("Error:"+e.getMessage());

System.out.println("Error:"+e);

System.out.println("...End of Program...");

OUTPUT

Output 1

Enter first number: 20

Enter second number: 10

Result:2

...End of Program...

Output 2

Enter first number: 25

Enter second number 0

Error: by zero

Error java.lang.ArithmeticException: /by zero

...End of Program...

12. Java program to add two integers and two float numbers. When no arguments are supplied give a
default value to calculate the sum. Use method overloading.

import java.util.Scanner;

public class MethodOverload {

// Method to add two integers

public int add(int a, int b) {

return a + b;

// Method to add two float numbers

public float add(float a, float b) {

return a + b;

// Method to add two integers with default values

public int add() {

return add(5, 10); // default values

// Method to add a float number with a default value


public float add(float a) {

return add(a, 2.5f); // default value

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

MethodOverload calculator = new MethodOverload();

// Integer addition

System.out.println("Enter two integers (separated by space) (or press Enter for default):");

String intInput = scanner.nextLine();

if (intInput.isEmpty()) {

System.out.println("Sum of default integers: " + calculator.add());

} else {

String[] intValues = intInput.split(" ");

int a = Integer.parseInt(intValues[0]);

int b = Integer.parseInt(intValues[1]);

System.out.println("Sum of integers: " + calculator.add(a, b));

// Float addition

System.out.println("Enter two float numbers (separated by space) (or press Enter for default): ");

String floatInput = scanner.nextLine();

if (floatInput.isEmpty()) {

System.out.println("Sum of default floats: " + calculator.add(1.5f));

} else {

String[] floatValues = floatInput.split(" ");

float x = Float.parseFloat(floatValues[0]);

float y = Float.parseFloat(floatValues[1]);

System.out.println("Sum of floats: " + calculator.add(x, y));

scanner.close();

OUTPUT

Output: When user enters both values

Enter two integers (separated by space) (or press Enter for default):
15 25

Sum of integers: 40

Enter two float numbers (separated by space) (or press Enter for default):

63.2 56.1

Sum of floats: 119.3

Output: When user is not entering value and press enters

Enter two integers (or press Enter for default):

Sum of default integers: 15

Enter two float numbers (or press Enter for default):

Sum of default floats: 4.0

13. Java program that demonstrates run-time polymorphism.

class Employee {

// Method to be overridden

public void work() {

System.out.println("Employee is working");

class Developer extends Employee {

// Overriding the work method

@Override

public void work() {

System.out.println("Developer is writing code");

class Manager extends Employee {

// Overriding the work method

@Override

public void work() {

System.out.println("Manager is managing the team");

class Designer extends Employee

//Overriding the work method

@Override
public void work() {

System.out.println("Designer is creating designs");

public class RunTimePolymorphism {

public static void main(String[] args) {

System.out.println("Demo for Runtime Polymorphism");

System.out.println("---------------");

// Employee reference but Developer object

Employee emp = new Developer();

emp.work();

// Employee reference but Manager object

emp = new Manager();

emp.work();

// Employee reference but Designer object

emp = new Designer();

emp.work();

// Employee reference and Employee object

emp = new Employee();

emp.work();

OUTPUT

Demo for Runtime Polymorphism

----------------------------

Developer is writing code

Manager is managing the team

Designer is creating designs

Employee is working

14. Java program to catch negative array size Exception. This exception is caused when the array is
initialized to negative values.

import java.util.*;

public class NegativeArrayException {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


System.out.print("Enter the size of the array: ");

int size = scanner.nextInt();

try {

// Attempt to create an array with the specified size

int[] array = new int[size];

System.out.println("Array of size " + size + " created successfully.");

} catch (NegativeArraySizeException e) {

System.out.println("Error: Array size cannot be negative.");

} catch (InputMismatchException e) {

System.out.println("Error: Invalid input. Please enter a valid integer.");

scanner.next();

finally {

scanner.close();

System.out.println("End of the program.");

OUTPUT:

Output for positive integer

Enter the size of the array: 10

Array of size 10 created successfully.

END OF THE PROGRAM-

Output for negative integer

Enter the size of the array: -6

Error: Array size cannot be negative.

END OF THE PROGRAM-

Output for other than integer

Enter the size of the array: C

Exception in thread "main" java.util.InputMismatchException

at java.base/java.util. Scanner.throwFor(Scanner.java:939)
at java base java.util.Scanner.next(Scanner.java:1594)

at java.base/java.util.Scanner.nextInt(Scanner.java:2258)

at java.base/java.util.Scanner.nextInt(Scanner.java:2212)

at Book_Java_Lab/LabPrograms. Negative_array Exception.main(Negative_array_Exception.java:11)

15. Java program to handle null pointer exception and use the “finally” method to display a message to
the user.

import java.util.*;

public class NullPointerExceptionDemo {

public static void main(String args[]) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");

String input = scanner.nextLine(); // Fixed syntax error

try {

if (input.isEmpty()) {

input = null;

System.out.println("Length of the string: " + input.length()); // Might throw NullPointerException

} catch (NullPointerException e) {

System.out.println("A null pointer exception occurred.");

} finally {

System.out.println("END OF PROGRAM.");

scanner.close();

}OUTPUT

Output 1: Input is entered by user

Enter a string: Java World

Length of the string: 10

-END OF PROGRAM

Output 1: No Input

Enter a string:

A null pointer exception occurred.

-END OF PROGRAM-
16. Java program to import user-defined packages.

Step 1: Create a package "shape" inside ‘src’ folder in the working project.

Step 2: Inside "shape" create three classes 'Circle java', 'Square java", "Triangle java"

Step 3: Outside the "shape" package create main class file 'CustomPack.java'

Step 4: Run the "CustomPack.java"

Circle.java

package shape;

public class Circle (

private double radius;

public Circle(double r) |

radius=r;

public double area() |

return (3.14*radius*radius);

Square.java

package shape;

public class Square {

private int side;

public Square(int s) {

side=s;

public int area() {

return (side*side);

Triangle.java

package shape;

public class Triangle{

private int sidel,side2.side3;

public Triangle(int s1, int s2,int s3) {

sidel=s1;

side2=s2;

side3=s3;

public double area() {


double s=(sidel+side2+side3)/2;

double a=Math.sqrt((s-side1)+(s-side2)+(s-side3));

return a;

CustomPack.java

package LabPrograms;

import shape.*;

import java.util.*;

public class CustomPack {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

System.out.println("Enter The side of the Square: ");

int s=sc.nextInt();

Square sq=new Square(s);

System.out.println("Area of Square is " + sq.area());

System.out.println("Enter The radius of the Circle: ");

double r=sc.nextDouble();

Circle ci=new Circle(s);

System.out.println("Area of Circle is " + ci.area());

System.out.println("Enter The Sides of the Triangle: ");

int sl=sc.nextInt();

int s2=sc.nextInt();

int s3=sc.nextInt();

shape.Triangle t=new shape. Triangle(s1,s2,s3);

System.out.println("Area of Triangle is " + t.area());

OUTPUT

Enter the side of the Square: 7

Area of Square is 49

Enter the radius of the Circle: 6

Area of Circle is 153.86

Enter The Sides of the Triangle:

6
5

Area of Triangle is 2.8284271247461903

17. Java program to check whether a number is palindrome or not

import java.util.Scanner;

public class PalindromeChecker {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

int originalNumber = number;

int reversedNumber = 0;

while (number != 0) {

int digit = number % 10;

reversedNumber = reversedNumber * 10 + digit;

number /= 10;

if (originalNumber == reversedNumber) {

System.out.println(originalNumber + " is a palindrome.");

} else {

System.out.println(originalNumber + " is not a palindrome.");

scanner.close();

}OUTPUT

Output 1

Enter a number: 78524

78524 is not a palindrome

Output 2

Enter a number: 9669

9669 is a palindrome
18. Java program to find the factorial of a list of numbers reading input as command line argument.

import java.math.BigInteger;

public class FactorialDemo {

public static void main(String[] args) {

for (String arg : args) {

try {

int number = Integer.parseInt(arg);

System.out.println("Factorial of " + number + " = " + factorial(number));

} catch (NumberFormatException e) {

System.out.println(arg + " is not a valid number.");

private static BigInteger factorial(int number) {

BigInteger result = BigInteger.ONE;

for (int i = 2; i <= number; i++) {

result = result.multiply(BigInteger.valueOf(i));

return result;

}In Eclipse IDE open Run Run Configurations

Click on "Arguments tab

Inside Program Arguments' enter list of numbers one by one

Finally click on 'Run' to see the output

OUTPUT

Factorial of 5=120

Factorial of 4=24

Factorial of 7=5040

19. Java program to display all prime numbers between two limits.

import java.util.Scanner;

public class PrimeNumbers {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the lower limit: ");

int lowerLimit = scanner.nextInt();

System.out.print("Enter the upper limit: ");

int upperLimit = scanner.nextInt();

System.out.println("Prime numbers between " + lowerLimit + " and " + upperLimit + " are:");

for (int num = lowerLimit; num <= upperLimit; num++) {

if (isPrime(num)) {

System.out.print(num + " ");

scanner.close(); // Close scanner to prevent resource leaks

public static boolean isPrime(int number) {

if (number <= 1) {

return false;

for (int i = 2; i <= Math.sqrt(number); i++) {

if (number % i == 0) {

return false;

return true;

OUTPUT

Enter the lower limit: 12

Enter the upper limit: 40

Prime numbers between 12 and 40 are: 13 17 19 23 29 31 37


20. Java program to create a thread using Runnable Interface.

class MyThread implements Runnable {

private String threadName;

public MyThread(String threadName) {

this.threadName = threadName;

@Override

public void run() {

System.out.println(threadName + " started.");

for (int i = 0; i < 5; i++) {

System.out.println(threadName + ": " + i);

try {

Thread.sleep(1000); // Sleep for 1 second

} catch (InterruptedException e) {

System.out.println(threadName + " interrupted.");

System.out.println(threadName + " finished.");

public class ThreadRunnable {

public static void main(String[] args) {

// Create two threads

MyThread thread1 = new MyThread("Thread-1");

MyThread thread2 = new MyThread("Thread-2");

// Create Thread objects and pass the Runnable instances

Thread t1 = new Thread(thread1);

Thread t2 = new Thread(thread2);

// Start the threads

t1.start();
t2.start();

OUTPUT

Thread-2 started.

Thread-2: 0

Thread-1 started.

Thread-1:0

Thread-2: 1

Thread-1: 1

Thread-2: 2

Thread-1: 2

Thread-2: 3

Thread-1: 3

Thread-2:4

Thread-1:4

Thread-2 finished.

Thread-1 finished.

You might also like