0% found this document useful (0 votes)
20 views20 pages

Java Lab Codes

The document provides a comprehensive list of Java lab codes organized by modules, covering basic to advanced concepts in Java programming, including OOP principles, control statements, loops, and inheritance. Each lab includes sample code snippets demonstrating various programming tasks such as basic arithmetic operations, constructors, and inheritance. The document also offers examples of using classes, methods, and encapsulation in Java.

Uploaded by

hiteshnahak07
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)
20 views20 pages

Java Lab Codes

The document provides a comprehensive list of Java lab codes organized by modules, covering basic to advanced concepts in Java programming, including OOP principles, control statements, loops, and inheritance. Each lab includes sample code snippets demonstrating various programming tasks such as basic arithmetic operations, constructors, and inheritance. The document also offers examples of using classes, methods, and encapsulation in Java.

Uploaded by

hiteshnahak07
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/ 20

Java Lab Codes

LESSON PLAN OF OOPJ.pdf


PDF

give me the code of all the labs

Here is the complete list of Java lab codes based on the lesson plan from the PDF you uploaded. I've
organized them module-wise and session-wise for clarity.

🔹 MODULE I: Introduction to Java & OOPs Concepts


Lab 4: Basic Java Setup

java

// 1. Installation & Path Setting: (Manual Step)


// 2. Print a welcome message
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java programming.");
}
}

Lab 6: Basic Programs

java

// 1. Add two numbers


public class Add {
public static void main(String[] args) {
int a = 10, b = 20;
int sum = a + b;
System.out.println("Sum = " + sum);
}
}

// 2. Swap using third variable


public class Swap {
public static void main(String[] args) {
int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
System.out.println("a = " + a + ", b = " + b);
}
}

// 3. Swap without third variable


public class SwapWithoutTemp {
public static void main(String[] args) {
int a = 5, b = 10;
a = a + b;
b = a - b;

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/20
a = a - b;
System.out.println("a = " + a + ", b = " + b);
}
}

// 4. Area of a circle
public class CircleArea {
public static void main(String[] args) {
double radius = 5.0;
double area = Math.PI * radius * radius;
System.out.println("Area = " + area);
}
}

Lab 8: Calculator

java

// Simple calculator
import java.util.Scanner;

public class Calculator {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers: ");
double a = sc.nextDouble(), b = sc.nextDouble();
System.out.print("Enter operation (+, -, *, /): ");
char op = sc.next().charAt(0);

switch(op) {
case '+': System.out.println("Result = " + (a + b)); break;
case '-': System.out.println("Result = " + (a - b)); break;
case '*': System.out.println("Result = " + (a * b)); break;
case '/':
if (b != 0) System.out.println("Result = " + (a / b));
else System.out.println("Divide by zero error.");
break;
default: System.out.println("Invalid operator.");
}
}
}

Lab 10: Control Statements

java

// 1. Largest of 3 numbers
public class Largest {
public static void main(String[] args) {
int a = 10, b = 25, c = 20;
if(a >= b && a >= c) System.out.println("Largest: " + a);
else if(b >= c) System.out.println("Largest: " + b);
else System.out.println("Largest: " + c);
}
}

// 2. Day of week using switch


public class DayOfWeek {
public static void main(String[] args) {
int day = 3;
switch(day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday"); break;
case 7: System.out.println("Sunday"); break;

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/20
default: System.out.println("Invalid Day");
}
}
}

// 3. Leap year using switch (not ideal, but possible)


public class LeapYear {
public static void main(String[] args) {
int year = 2024;
boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
switch (isLeap ? 1 : 0) {
case 1: System.out.println(year + " is a Leap Year."); break;
case 0: System.out.println(year + " is not a Leap Year.");
}
}
}

Lab 12: Loops

java

// 1. Print 1 to 10
public class OneToTen {
public static void main(String[] args) {
for(int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}

// 2. Factorial
public class Factorial {
public static void main(String[] args) {
int n = 5;
int fact = 1;
for(int i = 1; i <= n; i++) {
fact *= i;
}
System.out.println("Factorial = " + fact);
}
}

// 3. Fibonacci series
public class Fibonacci {
public static void main(String[] args) {
int n = 10, a = 0, b = 1;
System.out.print("Fibonacci Series: ");
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int temp = a + b;
a = b;
b = temp;
}
}
}

This is just Module I. There are Modules II, III, and IV remaining with more advanced topics like
inheritance, exceptions, threads, GUI, etc.
Would you like me to continue and provide all remaining lab codes from Modules II to IV?

Create a class Calculator with methods to


perform basic arithmetic operation like
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/20
addition, subtraction, multiplication and
division. WAP to call these methods and
display the results.

Here is the complete Java program that defines a class Calculator with methods for addition,
subtraction, multiplication, and division, and a main method to call these methods and display the
results:

java

// Calculator.java
public class Calculator {

// Method for addition


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

// Method for subtraction


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

// Method for multiplication


public double multiply(double a, double b) {
return a * b;
}

// Method for division


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

public static void main(String[] args) {


Calculator calc = new Calculator();

double num1 = 20.5;


double num2 = 4.5;

System.out.println("Addition: " + calc.add(num1, num2));


System.out.println("Subtraction: " + calc.subtract(num1, num2));
System.out.println("Multiplication: " + calc.multiply(num1, num2));
System.out.println("Division: " + calc.divide(num1, num2));
}
}

✅ Output (Sample):
makefile

Addition: 25.0
Subtraction: 16.0
Multiplication: 92.25
Division: 4.555555555555555

Let me know if you'd like a version that takes user input using Scanner, or if you want to add error
handling or other features.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/20
.WAP to know the use of default
constructor.

Here is a Java program that demonstrates the use of a default constructor:

✅ Program: Use of Default Constructor


java

// DefaultConstructorExample.java
public class DefaultConstructorExample {

// Default constructor
DefaultConstructorExample() {
System.out.println("Default constructor called.");
}

// Method to display message


void display() {
System.out.println("This is a method in the class.");
}

public static void main(String[] args) {


// Creating object which calls the default constructor
DefaultConstructorExample obj = new DefaultConstructorExample();

// Calling the method


obj.display();
}
}

📌 Explanation:
A default constructor is a constructor without any parameters.

It is either provided by the compiler or defined by the programmer (as shown above).
It is automatically called when an object is created.

🖥️ Sample Output:
pgsql

Default constructor called.


This is a method in the class.

Let me know if you'd like to see examples for parameterized constructors, constructor overloading,
or any real-life use case.

WAP to create a class Person with a


parameterized constructor to initialize

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/20
attributes like name & age. Display the details
using a method

Here is a Java program that demonstrates a parameterized constructor in a class Person to initialize
attributes like name and age, and then display them using a method.

✅ Program: Person Class with Parameterized Constructor


java

// Person.java
public class Person {

// Attributes
String name;
int age;

// Parameterized constructor
Person(String personName, int personAge) {
name = personName;
age = personAge;
}

// Method to display the details


void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}

// Main method to create and test the object


public static void main(String[] args) {
// Create object with parameterized constructor
Person p1 = new Person("Hitesh", 20);

// Call method to display details


p1.displayDetails();
}
}

🖥️ Sample Output
makefile

Name: Hitesh
Age: 20

Let me know if you'd like this extended with multiple objects, user input, or stored in arrays/lists!

WAP to create a class Student with


attributes name & rollNumber. Use the „this‟
keyword in the constructor to initialize the
attributes & display the details.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/20
Here is a Java program that demonstrates how to use the this keyword inside a constructor to initialize
class attributes for a Student class with name and rollNumber.

✅ Program: Student Class with this Keyword

java

// Student.java
public class Student {

// Attributes
String name;
int rollNumber;

// Constructor using 'this' keyword


Student(String name, int rollNumber) {
this.name = name; // 'this' refers to the current object's variable
this.rollNumber = rollNumber;
}

// Method to display student details


void displayDetails() {
System.out.println("Student Name: " + name);
System.out.println("Roll Number: " + rollNumber);
}

// Main method
public static void main(String[] args) {
// Create a Student object
Student s1 = new Student("Ankit", 101);

// Display the details


s1.displayDetails();
}
}

🖥️ Sample Output
yaml

Student Name: Ankit


Roll Number: 101

📌 Explanation:
this.name refers to the class-level variable, while name on the right is the constructor parameter.

Using this avoids confusion when parameter names match instance variable names.

Let me know if you'd like an example using user input, arrays of students, or storing them in a
collection.

WAP to create a class Person with private


attributes name & age. Use getter & setter

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/20
method to access & update these attributes.

Here's a Java program that creates a Person class with private attributes name and age, and uses getter
and setter methods to access and update them:

✅ Program: Person Class with Getters and Setters


java

// Person.java
public class Person {

// Private attributes
private String name;
private int age;

// Setter method for name


public void setName(String name) {
this.name = name;
}

// Getter method for name


public String getName() {
return name;
}

// Setter method for age


public void setAge(int age) {
this.age = age;
}

// Getter method for age


public int getAge() {
return age;
}

// Method to display details


public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}

// Main method
public static void main(String[] args) {
// Creating object of Person
Person p1 = new Person();

// Using setters to set data


p1.setName("Rohit");
p1.setAge(22);

// Displaying using display method


p1.displayDetails();

// Using getters directly


System.out.println("Access using getter -> Name: " + p1.getName() + ", Age: " +
p1.getAge());
}
}

🖥️ Sample Output

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/20
yaml

Name: Rohit
Age: 22
Access using getter -> Name: Rohit, Age: 22

🔐 Why Use Getters and Setters?


Encapsulation: Keeps fields private and controlled.

Allows validation or logic inside setters (e.g., if age < 0).


Makes code maintainable and secure.

Let me know if you'd like a version with input from the user using Scanner, or handling multiple
persons.

.WAP to demonstrate the concept of single


inheritance.

Here's a Java program that demonstrates the concept of single inheritance, where a subclass inherits
properties and behaviors from a single superclass.

✅ Program: Single Inheritance Example


java

// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

// Subclass inheriting from Animal


class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}

// Main class
public class SingleInheritanceDemo {
public static void main(String[] args) {
// Create an object of the subclass
Dog myDog = new Dog();

// Call method from superclass


myDog.eat();

// Call method from subclass


myDog.bark();
}
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/20
🖥️ Sample Output
nginx

This animal eats food.


The dog barks.

📌 Explanation:
Dog extends Animal, which means it inherits the eat() method.
This is single inheritance since there is only one parent class.

Let me know if you want an example of multilevel or hierarchical inheritance next!

WAP to demonstrate the concept of


multilevel inheritance i.e. A child class
inherits from a parent and this child class
becomes the parent for another class.(
Example: Vechicle, Car & ElectricCar
classes)

Here's a Java program that demonstrates the concept of multilevel inheritance using the example of
Vehicle, Car, and ElectricCar classes.

✅ Program: Multilevel Inheritance Example


java

// Base class
class Vehicle {
void start() {
System.out.println("Vehicle is starting...");
}
}

// Intermediate class that extends Vehicle


class Car extends Vehicle {
void drive() {
System.out.println("Car is being driven...");
}
}

// Derived class that extends Car


class ElectricCar extends Car {
void charge() {
System.out.println("Electric car is charging...");
}
}

// Main class to test multilevel inheritance


public class MultilevelInheritanceDemo {
public static void main(String[] args) {
// Create object of the most derived class
ElectricCar myEV = new ElectricCar();

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/20
// Call methods from all levels of inheritance
myEV.start(); // From Vehicle
myEV.drive(); // From Car
myEV.charge(); // From ElectricCar
}
}

🖥️ Sample Output
csharp

Vehicle is starting...
Car is being driven...
Electric car is charging...

📌 Explanation:
ElectricCar inherits from Car, and Car inherits from Vehicle.

Thus, ElectricCar has access to methods from both its parent and grandparent classes, showing
multilevel inheritance.

Let me know if you want to try hierarchical or multiple inheritance using interfaces!

.WAP to design a class called “Calculator”


having multiple “add” methods with different
parameters, such as add (int a, int b), add
(double a, double b), and add (int a, int b, int
c) etc. to demonstrate method overloading

Here is a Java program that demonstrates method overloading by creating a Calculator class with
multiple add() methods, each having different parameter lists:

✅ Program: Method Overloading in Calculator


java

// Calculator.java
public class Calculator {

// add method with two integers


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

// add method with three integers


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

// add method with two double values


double add(double a, double b) {
return a + b;

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/20
}

public static void main(String[] args) {


Calculator calc = new Calculator();

// Calling different overloaded methods


System.out.println("Addition of 2 integers: " + calc.add(10, 20));
System.out.println("Addition of 3 integers: " + calc.add(5, 15, 25));
System.out.println("Addition of 2 doubles : " + calc.add(12.5, 7.3));
}
}

🖥️ Sample Output
yaml

Addition of 2 integers: 30
Addition of 3 integers: 45
Addition of 2 doubles : 19.8

📌 Explanation:
All methods have the same name (add), but their parameters differ in type or number.

This is a classic example of compile-time polymorphism (method overloading).

Let me know if you want to see constructor overloading, or overloading in combination with
inheritance or interfaces.

WAP to design a superclass called "Shape"


with a method called "draw” and a subclass
called "Circle" that also has a "draw" method.
Override the "draw" method in the "Circle"
subclass by giving specific implementation
details for drawing a circle which differs from
the "draw" method in the superclass to
demonstrate method overriding

Here is a Java program that demonstrates method overriding using a superclass Shape and a subclass
Circle. The draw() method is overridden in the Circle class to provide specific implementation for
drawing a circle.

✅ Program: Method Overriding Example


java

// Superclass
class Shape {
void draw() {
System.out.println("Drawing a generic shape...");
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/20
}

// Subclass
class Circle extends Shape {
// Overriding the draw method
@Override
void draw() {
System.out.println("Drawing a circle with radius and center.");
}
}

// Main class
public class MethodOverridingDemo {
public static void main(String[] args) {
// Create object of Shape
Shape shape = new Shape();
shape.draw(); // Calls superclass method

// Create object of Circle


Circle circle = new Circle();
circle.draw(); // Calls overridden method in subclass

// Polymorphic behavior
Shape s = new Circle();
s.draw(); // Calls Circle's overridden method due to dynamic dispatch
}
}

🖥️ Sample Output
scss

Drawing a generic shape...


Drawing a circle with radius and center.
Drawing a circle with radius and center.

📌 Key Points:
The Circle class overrides the draw() method from Shape.
The third call (Shape s = new Circle();) shows runtime polymorphism, also called dynamic
method dispatch.

Let me know if you want to try abstract classes, interfaces, or polymorphic arrays of shapes next!

Demonstrate how to achieve dynamic


method Dispatch

Here's a Java program that demonstrates how to achieve Dynamic Method Dispatch (also known as
Runtime Polymorphism) using a superclass reference to call an overridden method in the subclass.

✅ Program: Dynamic Method Dispatch Example


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/20
java

// Superclass
class Animal {
void sound() {
System.out.println("The animal makes a sound.");
}
}

// Subclass 1
class Dog extends Animal {
@Override
void sound() {
System.out.println("The dog barks.");
}
}

// Subclass 2
class Cat extends Animal {
@Override
void sound() {
System.out.println("The cat meows.");
}
}

// Main class
public class DynamicDispatchDemo {
public static void main(String[] args) {
// Superclass reference
Animal ref;

// Refer to Dog object


ref = new Dog();
ref.sound(); // Calls Dog's version of sound()

// Refer to Cat object


ref = new Cat();
ref.sound(); // Calls Cat's version of sound()
}
}

🖥️ Sample Output
bash

The dog barks.


The cat meows.

📌 Explanation:
Animal is the superclass.
Dog and Cat are subclasses that override the sound() method.

A reference of superclass (Animal ref) is used to refer to subclass objects.


At runtime, Java determines which sound() method to call based on the actual object, not the
reference type. This is dynamic method dispatch.

Let me know if you'd like a version using an abstract class or interface for more real-world
polymorphism!

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/20
Write a Java program where two interfaces,
Printable and Showable, are implemented by
a single class Demo. The Printable interface
contains a method print() and the Showable
interface contains a method show().
Demonstrate the implementation.

Here’s a Java program that demonstrates how a class can implement multiple interfaces. The class Demo
implements both Printable and Showable interfaces, each with a separate method:

✅ Program: Multiple Interfaces Implementation


java

// Define Printable interface


interface Printable {
void print();
}

// Define Showable interface


interface Showable {
void show();
}

// Class that implements both interfaces


public class Demo implements Printable, Showable {

// Implement print() from Printable


public void print() {
System.out.println("Printing from Printable interface.");
}

// Implement show() from Showable


public void show() {
System.out.println("Showing from Showable interface.");
}

// Main method
public static void main(String[] args) {
Demo obj = new Demo();

// Call both methods


obj.print();
obj.show();
}
}

🖥️ Sample Output
csharp

Printing from Printable interface.


Showing from Showable interface.

📌 Explanation:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/20
Interfaces Printable and Showable define separate methods.
The Demo class uses the implements keyword to implement both interfaces.
This demonstrates multiple inheritance using interfaces, which is allowed in Java.

Let me know if you’d like to extend this with default methods in interfaces, or with inheritance plus
interfaces!

.Design a user-defined package named “my pack” having a “Balance” class with a
method to print the current balance

Here's how you can create a user-defined package named mypack with a Balance class that contains a
method to print the current balance.

✅ Step-by-Step Guide
📁 Folder structure:
css

ProjectFolder/

├── mypack/
│ └── Balance.java

└── Main.java

📝 1. Balance.java (inside mypack folder)

java

package mypack; // Declare the package

public class Balance {


private double amount;

// Constructor
public Balance(double amount) {
this.amount = amount;
}

// Method to print current balance


public void showBalance() {
System.out.println("Current balance is: ₹" + amount);
}
}

📝 2. Main.java (outside the mypack folder)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/20
java

import mypack.Balance; // Import the Balance class from user-defined package

public class Main {


public static void main(String[] args) {
// Create object and call method
Balance myAcc = new Balance(5000.75);
myAcc.showBalance();
}
}

⚙️ How to Compile and Run


Open terminal or command prompt inside ProjectFolder:

✅ Compile:
bash

javac mypack/Balance.java
javac Main.java

▶️ Run:
bash

java Main

🖥️ Sample Output
pgsql

Current balance is: ₹5000.75

Let me know if you'd like to add setters/getters, or file storage for balances!

WAP that reverse a given string without


using any built-in reverse method.

Here's a Java program that reverses a given string manually, without using any built-in reverse
methods like StringBuilder.reverse():

✅ Program: Reverse a String Without Built-in Method


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/20
java

import java.util.Scanner;

public class ReverseString {


public static void main(String[] args) {
// Taking input from the user
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String original = sc.nextLine();

String reversed = "";

// Loop through the string from end to start


for (int i = original.length() - 1; i >= 0; i--) {
reversed += original.charAt(i);
}

System.out.println("Reversed string: " + reversed);


}
}

🖥️ Sample Output
csharp

Enter a string: hello


Reversed string: olleh

📌 Explanation:
A loop starts from the last character and appends each character to a new string.

No built-in reverse() method is used.

Let me know if you want this using char arrays, recursion, or if you'd like the reversed string stored in a
file!

.WAP to reverse a string using


StringBuffer‟s reverse() method.

Here is a simple Java program that demonstrates how to reverse a string using StringBuffer's reverse()
method:

✅ Program: Reverse a String Using StringBuffer.reverse()

java

import java.util.Scanner;

public class ReverseUsingStringBuffer {


public static void main(String[] args) {
// Take input from user

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/20
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = sc.nextLine();

// Use StringBuffer and reverse() method


StringBuffer sb = new StringBuffer(input);
StringBuffer reversed = sb.reverse();

// Display reversed string


System.out.println("Reversed string: " + reversed);
}
}

🖥️ Sample Output
csharp

Enter a string: JavaProgramming


Reversed string: gnimmargorPavaJ

📌 Notes:
StringBuffer is mutable and has a built-in reverse() method.
You can also use StringBuilder similarly if thread safety is not required.

Let me know if you want to compare this with manual reversal or using recursion!

WAP to append text to a given string using


StringBuilder‟s append() method

Here is a Java program that demonstrates how to append text to a given string using StringBuilder's
append() method:

✅ Program: Append Text Using StringBuilder.append()

java

import java.util.Scanner;

public class AppendUsingStringBuilder {


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

// Take the original string


System.out.print("Enter the original string: ");
String original = sc.nextLine();

// Take the string to append


System.out.print("Enter the text to append: ");
String toAppend = sc.nextLine();

// Create StringBuilder object and append


StringBuilder sb = new StringBuilder(original);
sb.append(toAppend);

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/20
// Display result
System.out.println("Resulting string: " + sb.toString());
}
}

🖥️ Sample Output
vbnet

Enter the original string: Hello


Enter the text to append: World
Resulting string: HelloWorld

📌 Notes:
StringBuilder is used for efficient string manipulation.
The append() method adds the new text to the end of the existing string.

Let me know if you want to append multiple values like numbers or use loops to build strings
dynamically!

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/20

You might also like