GL BAJAJ Institute of Technology and
Management
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P. India]
Department of Computer Science and Engineering - Artificial Intelligence
Object Oriented Programing with Java Lab (BCS-452)
Lab File
Session: 2024-25
Submitted To: Submitted By:
Ms. Bhumika Nirmohi Name: Anjali Bhardwaj
Assistant Professor Roll No.: 2301921520022
CSE-AI Department Branch: CSAI Sec: 1
Semester: 4th
INDEX
S. List of Programs Date Date of Signatur
No. Submissio e
n
1. Use Java compiler and eclipse platform
to write and execute a java program.
2. Implement a simple java program
using command line arguments.
3. Implement OOP concept and basics of
Java Programming
4. Implement a Java program using
Inheritance.
5. Implement a Java program using
Polymorphism.
6. Implement error handling techniques
using Exception Handling.
7. Implement error handling techniques
Multithreading.
8. Implement a Java program Using I/O
Package.
9. Implement Java new features using
Java Programs.
INDEX(CBS)
S. No. List of Programs (CBS) Date Date of Signatur
Submissio e
n
G
_
GLBAJAJ
Instirtu
te of'
ecb.r1o
logy
Program No -1
AIM:
To use Java compiler and Eclipse IDE to write, compile, and execute a Java program.
TOOLS REQUIRED:
• Software:
◦ Java Development Kit (JDK)
◦ Eclipse IDE for Java Developers
• Hardware:
◦ PC or Laptop with minimum 4GB RAM
◦ Windows/Linux/macOS Operating System
THEORY:
Java is a high-level, object-oriented programming language used for developing platform-
independent applications. To compile and run Java programs, we need a Java compiler
(provided with the JDK) and optionally, an Integrated Development Environment (IDE) like
Eclipse.
Eclipse IDE is an open-source development environment that simpli es the process of
writing, debugging, and running Java applications. It provides features like syntax
highlighting, auto-completion, and debugging tools, which help increase productivity and
reduce coding errors.
Key components:
• JDK (Java Development Kit): Contains tools required to develop Java programs,
including javac (compiler) and java (runtime).
• Eclipse IDE: Provides a graphical interface to manage projects and run Java
applications easily.
PROCEDURE:
1. Install JDK:
◦ Download and install the latest version of the JDK from https://
www.oracle.com/java/technologies/javase-downloads.html.
2. Install Eclipse IDE:
fi
◦ IDE for Java Developers from https://www.eclipse.org/downloads/.
◦ Extract and run the Eclipse installer.
3. Create a New Java Project:
◦ Open Eclipse.
◦ Go to File → New → Java Project.
◦ Enter the project name and click Finish.
4. Create a Java Class:
◦ Right-click on src folder → New → Class.
◦ Enter the class name (e.g., HelloWorld) and check the option to include
public static void main(String[] args) method.
5. Write the Java Code:
◦ In the editor, write a simple Java program.
6. Compile and Run:
◦ Save the le.
◦ Click the green Run button or press Ctrl + F11 to compile and execute
the program.
Source Code:-
public class HelloWorld {
public static void main(String[] args)
{ System.out.println("Hello, World!");
}
}
Output of vs code -
fi
Source Code:-
public class HelloWorldEclipse
{
public static void main(String[] args)
{ System.out.println("Hello from Eclipse!");
}
}
Output of eclipse -
RESULT:
The Java program was successfully written, compiled, and executed using the Eclipse IDE.
The output displayed on the console was:
Program No -2
AIM:
To implement a simple Java program that takes input from the command line using command
line arguments.
TOOLS REQUIRED:
• Software:
◦ Java Development Kit (JDK)
◦ Any text editor (e.g., Notepad) or IDE (optional)
• Hardware:
◦ PC or Laptop with minimum 4GB RAM
◦ Windows/Linux/macOS Operating System
THEORY:
Command Line Arguments in Java allow the user to pass arguments to the program during
execution from the terminal or command prompt. The main() method in Java accepts a
String array as a parameter, which stores these arguments.
Syntax:
java
public static void main(String[] args)
Here, args[0], args[1], etc., represent the rst, second, and subsequent command line
arguments passed to the program.
Advantages:
• Dynamic input at runtime.
• No need to hardcode values.
• Useful in automation and scripting.
PROCEDURE:
1. Write the Java Program:
◦ Use any text editor or IDE to write the Java code.
fi
2. Save the File:
◦ Save the le with a .java extension (e.g.,
CommandLineExample.java).
3. Open Terminal/Command Prompt:
◦ Navigate to the directory where the le is saved.
4. Compile the Program:
5. Run the Program with Arguments
Source Code:-
// EchoArgs.java
public class EchoArgs {
public static void main(String[] args) {
System.out.println("Number of arguments: " + args.length);
if (args.length > 0) {
System.out.println("Arguments provided:");
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);}
}
else {
System.out.println("No command-line arguments were provided.");
}
}
}
RESULT:
The Java program was successfully written and executed using command line arguments.
Sample Input:
fi
fi
Program No -3
AIM:
To implement Object-Oriented Programming (OOP) concepts and demonstrate the basics of
Java programming using a simple Java program.
TOOLS REQUIRED:
• Software:
◦ Java Development Kit (JDK)
◦ Any text editor (e.g., Notepad++) or IDE (e.g., Eclipse, IntelliJ IDEA)
• Hardware:
◦ PC or Laptop with at least 4GB RAM
◦ Windows/Linux/macOS Operating System
THEORY:
Java is an object-oriented programming language that follows key OOP principles such as:
1. Class: A blueprint for creating objects.
2. Object: A runtime instance of a class.
3. Encapsulation: Wrapping data and methods into a single unit (class).
4. Inheritance: One class can inherit the properties and methods of another.
5. Polymorphism: Ability of one method to behave differently based on context.
6. Abstraction: Hiding internal details and showing only essential features.
Java basics include:
• Syntax (keywords, data types, variables)
• Control structures (if-else, loops)
• Methods (functions)
• Object creation and method invocation
PROCEDURE:
1. Open a Text Editor or IDE:
◦ Write a Java program that de nes a class with attributes and methods.
2. Implement Basic OOP Concepts:
◦ Create a class with elds (variables) and methods (functions).
◦ Create objects of that class.
◦ Demonstrate encapsulation and method invocation.
3. Save the File:
◦ Save the program with a .java extension (e.g., Student.java).
4. Compile the Program
5. Run the program
Source code:-
// De ne a class using encapsula on
public class Student {
// Private elds (data hiding)
private String name;
private int rollNo;
private double marks;
// Constructor to ini alize fields
public Student(String name, int rollNo, double marks)
{ this.name = name;
this.rollNo = rollNo;
this.marks = marks;
// Ge er methods to access data
public String getName() {
return name;
}
fi
tt
fi
fi
ti
fi
ti
public int getRollNo()
{ return rollNo;
public double getMarks()
{ return marks;
// Se er methods to modify data
public void setMarks(double marks) {
if (marks >= 0 && marks <= 100)
{ this.marks = marks;
} else {
System.out.println("Invalid marks!");
// Method to display student details
public void displayInfo() {
System.out.println("Student Name: " + name);
System.out.println("Roll No: " + rollNo);
System.out.println("Marks: " + marks);
}
RESULT:
The Java program was successfully written and executed. It implemented the basic OOP
concepts such as class, object, encapsulation, and method invocation.
tt
Output -
Program No -4
AIM:
To implement a Java program that demonstrates the concept of Inheritance, one of the core
principles of Object-Oriented Programming.
TOOLS REQUIRED:
• Software:
◦ Java Development Kit (JDK)
◦ Text Editor (e.g., Notepad++) or IDE (e.g., Eclipse, IntelliJ IDEA)
• Hardware:
◦ Computer with at least 4GB RAM
◦ Windows/Linux/macOS Operating System
THEORY:
Inheritance is one of the fundamental features of Object-Oriented Programming (OOP). It
allows one class (child or subclass) to inherit properties and methods from another class
(parent or superclass). This promotes code reusability and hierarchical classi cation.
Types of Inheritance in Java:
• Single Inheritance: One subclass inherits from one superclass.
• Multilevel Inheritance: A class inherits from a subclass, which in turn inherits from
another class.
• Hierarchical Inheritance: Multiple classes inherit from one superclass.
Java does not support multiple inheritance with classes (to avoid ambiguity) but it can be
achieved using interfaces.
PROCEDURE:
1. Open a Text Editor or IDE.
2. Write the Java program that demonstrates inheritance (e.g., a superclass Person
and subclass Student).
3. Save the File with the .java extension (e.g., TestInheritance.java).
fi
4. Compile the Program
5. Run the program
Source code:-
class Animal
{ void eat() {
System.out.println("This animal eats food");
class Dog extends Animal
{ void bark() {
System.out.println("The dog barks");
public class Main {
public static void main(String[] args)
{ Dog d = new Dog();
d.eat(); // inherited method
d.bark(); // subclass method
}
Output -
Multi level inheritance :
Source code:-
class Animal
{ void eat() {
System.out.println("Eating...");
class Dog extends Animal
{ void bark() {
System.out.println("Barking...");
class Puppy extends Dog
{ void weep() {
System.out.println("Weeping...");
}
public class Main {
public static void main(String[] args)
{ Puppy p = new Puppy();
p.eat(); // from Animal
p.bark(); // from Dog
p.weep(); // from Puppy
Output -
Hierarchical inheritance :
Source code:-
class Animal
{ void sound() {
System.out.println("Animal makes sound");
}
class Dog extends Animal {
void bark()
{ System.out.println("Dog
barks");
}
}
class Cat extends Animal
{ void meow() {
System.out.println("Cat meows");
}
public class Main {
public static void main(String[] args)
{ Dog d = new Dog();
d.sound();
d.bark();
Cat c = new Cat();
c.sound();
c.meow();
}
Output -
Program No -5
AIM:
To implement a Java program that demonstrates the concept of Polymorphism, one of the
core principles of Object-Oriented Programming (OOP).
TOOLS REQUIRED:
• Software:
◦ Java Development Kit (JDK)
◦ Text Editor (e.g., Notepad++) or IDE (e.g., Eclipse, IntelliJ IDEA)
• Hardware:
◦ PC or Laptop with minimum 4GB RAM
◦ Windows/Linux/macOS Operating System
THEORY:
Polymorphism means “many forms” and it allows one interface to be used for a general
class of actions. The most common use of polymorphism in Java is when a parent class
reference is used to refer to a child class object.
There are two types of polymorphism in Java:
1. Compile-time Polymorphism (Method Overloading):
◦ Multiple methods with the same name but different parameter lists.
2. Runtime Polymorphism (Method Overriding):
◦ Subclass provides a speci c implementation of a method that is already de ned
in its superclass.
Bene ts of Polymorphism:
• Code reusability
• Extensibility
• Easier maintenance and readability
PROCEDURE:
1. Open a Text Editor or IDE.
fi
fi
fi
2. Write the Java program that demonstrates polymorphism using method overriding.
3. Save the File with a .java extension (e.g., PolymorphismExample.java).
4. Compile the Program
5. Run the program
Compile time polymorphism (overloading)
Source code:-
class Calculator {
void add(int a, int b)
{ System.out.println("Sum: " + (a + b));
void add(double a, double b)
{ System.out.println("Double Sum: " + (a + b));
void add(int a, int b, int c)
{ System.out.println("Triple Sum: " + (a + b + c));
public class Main {
public static void main(String[] args)
{ Calculator calc = new Calculator();
calc.add(5, 10); // calls 2-arg int method
calc.add(3.5, 2.5); // calls 2-arg double method
calc.add(1, 2, 3); // calls 3-arg int method
}
Output-
RUN TIME POLYMORPHISM
Source code:-
class Animal
{ void sound() {
System.out.println("Animal makes a sound");
class Dog extends Animal
{ @Override
void sound()
{ System.out.println("Dog
barks");
}
class Cat extends Animal
{ @Override
void sound()
{ System.out.println("Cat
meows");
public class Main {
public static void main(String[] args)
{ Animal a;
a = new Dog(); // upcasting
a.sound(); // calls Dog's version
a = new Cat(); // upcasting
a.sound(); // calls Cat's version
Output-
Program No -6
AIM:
To implement error handling techniques in Java using Exception Handling.
TOOLS REQUIRED:
• Software:
◦ Java Development Kit (JDK)
◦ Any text editor (e.g., Notepad++) or IDE (e.g., Eclipse, IntelliJ IDEA)
• Hardware:
◦ PC or Laptop with minimum 4GB RAM
◦ Windows/Linux/macOS Operating System
THEORY:
Exception Handling in Java is a mechanism to handle runtime errors, allowing the program
to continue execution without crashing. Java provides a robust and object-oriented way to
handle exceptions through the use of the following keywords:
• try: Block of code that might throw an exception.
• catch: Block that handles the exception.
• finally: Block that always executes, used for cleanup.
• throw: Used to explicitly throw an exception.
• throws: Declares exceptions that a method might throw.
Types of Exceptions:
1. Checked Exceptions: Checked at compile-time (e.g., IOException)
2. Unchecked Exceptions: Occur at runtime (e.g., ArithmeticException,
ArrayIndexOutOfBoundsException)
Exception handling improves program stability and makes debugging easier.
PROCEDURE:
1. Open a Text Editor or IDE.
2. Write a Java program that demonstrates the use of try-catch blocks.
3. Include situations that may throw exceptions, such as division by zero or accessing
invalid array indices.
4. Save the le with a .java extension (e.g.,
ExceptionHandlingExample.java).
5. Compile the Program
6. Run the program
1. try ,catch and finally block
Source code:-
public class FinallyExample {
public static void main(String[] args) {
try {
String text = null;
System.out.println(text.length()); // NullPointerException
} catch (NullPointerException e)
{ System.out.println("Error: Null value encountered.");
} finally {
System.out.println("Finally block always runs.");
}
fi
Output -
2. throw keyword
Source code:-
public class ThrowExample {
public static void checkAge(int age)
{ if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
} else {
System.out.println("Eligible to vote");
public static void main(String[] args) {
checkAge(16);
Output -
3. throws keyword
Source code:-
import java.io.*;
public class throwsexample {
public static void readFile() throws IOException {
FileReader file = new FileReader("test.txt"); // file may not exist
BufferedReader fileInput = new BufferedReader(file);
System.out.println(fileInput.readLine());
fileInput.close();
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println("File not found or error reading file.");
Output -
Program No -7
AIM:
To implement Multithreading in Java along with error handling techniques using exception
handling mechanisms.
TOOLS REQUIRED:
• Software:
◦ Java Development Kit (JDK)
◦ Any Text Editor (e.g., Notepad++) or IDE (e.g., Eclipse, IntelliJ IDEA)
• Hardware:
◦ PC or Laptop with minimum 4GB RAM
◦ Windows/Linux/macOS Operating System
THEORY:
Multithreading in Java allows the execution of two or more parts of a program concurrently
for maximum utilization of CPU. Java provides built-in support for multithreading through:
• Extending the Thread class
• Implementing the Runnable interface
Each thread runs independently but shares the same memory space. Multithreaded programs
must handle errors and exceptions gracefully to avoid unexpected termination of threads.
Key Concepts:
• Thread class and Runnable interface
• start() method to initiate thread execution
• try-catch blocks for error handling inside threads
Why Use Exception Handling with Threads?
• Threads may fail due to resource con icts, invalid operations, or runtime exceptions.
• Handling these exceptions ensures the program doesn't crash and other threads
continue execution.
fl
PROCEDURE:
1. Open a Text Editor or IDE.
2. Write a Java program that creates multiple threads using either Thread or
Runnable.
3. Add operations inside each thread that may throw exceptions (e.g., divide by zero).
4. Use try-catch blocks to handle exceptions within the thread code.
5. Save the le with a .java extension (e.g.,
ThreadExceptionExample.java).
6. Compile the program
7. Run the program
Source code:-
class MyThread extends Thread
{ private int number;
public MyThread(int number)
{ this.number = number;
}
public void run()
{ try {
System.out.println("Thread " + number + " is running.");
if (number == 2) {
throw new ArithmeticException("Simulated exception in thread " + number);
Thread.sleep(1000);
System.out.println("Thread " + number + " finished successfully.");
} catch (ArithmeticException e) {
fi
System.err.println("Error in Thread " + number + ": " + e.getMessage());
} catch (InterruptedException e) {
System.err.println("Thread " + number + " was interrupted.");
} finally {
System.out.println("Thread " + number + " ended (success or error).");
public class MultithreadingErrorHandling
{ public static void main(String[] args)
{ MyThread t1 = new MyThread(1);
MyThread t2 = new MyThread(2);
MyThread t3 = new MyThread(3);
t1.start();
t2.start();
t3.start();
}
Output -
Program No -8
AIM:
To implement a Java program using the I/O (Input/Output) package for reading from and
writing to les.
TOOLS REQUIRED:
• Software:
◦ Java Development Kit (JDK)
◦ Any text editor (e.g., Notepad++) or IDE (e.g., Eclipse, IntelliJ IDEA)
• Hardware:
◦ PC or Laptop with at least 4GB RAM
◦ Windows/Linux/macOS Operating System
THEORY:
The java.io package provides classes for system input and output through data streams,
serialization, and the le system. It supports:
• Byte Streams (FileInputStream, FileOutputStream)
• Character Streams (FileReader, FileWriter)
• Buffered Streams for ef cient reading/writing
Common I/O Classes:
• File: Represents le and directory pathnames
• FileReader / BufferedReader: For reading character data from les
• FileWriter / BufferedWriter: For writing character data to les
• IOException: Exception class for I/O errors
PROCEDURE:
1. Open a Text Editor or IDE.
2. Write a Java program that uses classes from the java.io package to:
fi
fi
fi
fi
fi
fi
◦ Write user input to a le.
◦ Read the content back from the le and display it.
3. Save the le with a .java extension (e.g., FileIOExample.java).
4. Compile the program
5. Run the program
Source code:-
import java.io.*;
public class FileIOExample {
public static void main(String[] args)
{ String filename = "example.txt";
String dataToWrite = "This is an example of file I/O in Java.";
// Writing to a file
try (FileWriter writer = new FileWriter(filename))
{ writer.write(dataToWrite);
System.out.println("Data written to file successfully.");
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}
// Reading from the file
try (BufferedReader reader = new BufferedReader(new FileReader(filename)))
{ String line;
System.out.println("Reading data from file:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
fi
fi
fi
}
catch (IOException e) {
System.err.println("Error reading from file: " + e.getMessage());
Output -
Program No -9
AIM:
To implement Java programs using new features introduced in recent versions of Java
(e.g., Java 8 and above), such as Lambda Expressions, Stream API, var keyword, and switch
expressions.
TOOLS REQUIRED:
• Software:
◦ Java Development Kit (JDK 11 or higher recommended)
◦ Text Editor or IDE (Eclipse, IntelliJ IDEA, or VS Code)
• Hardware:
◦ PC or Laptop with minimum 4GB RAM
◦ Windows/Linux/macOS Operating System
THEORY:
Java has introduced several powerful features in its newer versions (Java 8 and above),
enhancing productivity and expressiveness in coding. Some key new features include:
• Lambda Expressions (Java 8): Provide a clear and concise way to represent one
method interface using an expression.
• Stream API (Java 8): Provides functional-style operations on streams of elements,
such as map, lter, and collect.
• var keyword (Java 10): Enables local variable type inference.
• Switch Expressions (Java 14): Enhance the traditional switch statement with more
concise syntax and return values.
These features make Java code more readable, concise, and ef cient.
PROCEDURE:
1. Open a Text Editor or IDE.
2. Write Java code demonstrating new features like Lambda Expressions, Stream API,
var, and enhanced switch.
fi
fi
3. Save the le with .java extension (e.g., JavaNewFeatures.java).
4. Compile the program
5. Run the program
Lambda expression
Source code:-
interface Greeting
{ void sayHello();
}
public class LambdaDemo {
public static void main(String[] args) {
Greeting greet = () -> System.out.println("Hello from Lambda!");
greet.sayHello();
}
}
Output -
Functional interference
Source code:-
@FunctionalInterface
interface MyFunctionalInterface
{ void display();
}
public class FunctionalInterfaceDemo
{ public static void main(String[] args)
{
MyFunctionalInterface msg = () -> {
System.out.println("Hello from a functional interface using lambda!");
};
msg.display();
}
}
fi
Output -
Method reference
Source code:-
public class MethodRef
{ public static void sayHi() {
System.out.println("Hi!");
public static void main(String[] args) {
Runnable r = MethodRef::sayHi;
r.run();
Output -
Stream API
Source code:-
import java.util.*;
public class StreamDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("Anna", "Bob", "Alice");
names.stream()
.filter(n -> n.startsWith("A"))
.forEach(System.out::println);
}
Output -
Local variable type inference
Source code:-
public class Var {
public static void main(String[] args) {
// Using var to infer data types
var number = 10; // int
var name = "Java"; // String
var price = 99.99; // double
var isAvailable = true; // boolean
System.out.println("Number: " + number);
System.out.println("Name: " + name);
System.out.println("Price: " + price);
System.out.println("Available: " + isAvailable);
// var with loop
for (var i = 1; i <= 3; i++)
{ System.out.println("Count: “i);
}
Output -
Switch expression
Source code:-
public class SwitchYieldExample
{ public static void main(String[] args)
int marks = 85;
String grade = switch (marks / 10)
{ case 10, 9 -> "A";
case 8 -> "B";
case 7 -> "C";
case 6 -> "D";
default -> {
String msg = "Fail";
yield msg; // use yield in block
};
System.out.println("Grade: " + grade);
}
}
Output -
Text blocks
Source code:-
public class text {
public static void main(String[] args) {
String json = """
"name": "Alice",
"age": 25,
"city": "New York"
""";
System.out.println("JSON Data:");
System.out.println(json);
}
Output -