Lab Manual
Lab Manual
Experiment No. 1
Objective / Aim : Students will learn about how to create simple java programs using command line arguments
return 1;
}
System.out.println("Yes");
else
System.out.println("No");
}
else
System.out.println("No command line "
+ "arguments found.");
}
}
Output:
D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>
D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>javac Prime.java
No
Yes
Experiment No. 1
Objective / Aim : Students will learn about how to create simple java programs using command line arguments
}
}
Output:
at Palindrome.main(Palindrome.java:31)
Experiment No. 3
Objective / Aim : Students will learn about OOP concepts and basics of Java programming
Apparatus Used : Jdk11, Eclipse, Notepad++, Visual Studio
• Class: A blueprint for creating objects (instances). It defines attributes (variables) and behaviors
(methods).
• Object: An instance of a class, representing a real-world entity with state and behavior.
Encapsulation
• Definition: Encapsulation is the bundling of data (attributes) and methods that operate on the data
within a single unit (class), restricting access to some of the object's components.
• Purpose: Protects the internal state of the object and provides controlled access through public
methods (getters and setters).
Inheritance
• Definition: Inheritance is a mechanism that allows one class (child) to inherit the attributes and
behaviors (methods) of another class (parent).
• Purpose: Promotes code reuse and creates a hierarchical relationship between classes.
• Example: A Dog class inherits from an Animal class.
Polymorphism
• Definition: Polymorphism allows objects to be treated as instances of their parent class, enabling
methods to take multiple forms (overloading and overriding).
o Method Overloading: Same method name, different parameters.
o Method Overriding: Subclass provides a specific implementation of a method already
defined in the superclass.
• Purpose: Increases flexibility and reusability.
Abstraction
• Achieved by: Abstract classes (with or without abstract methods) and interfaces (providing method
signatures).
Constructor
• Definition: A special method used to initialize objects. It is called when an object is created.
• Types:
o Default Constructor: No parameters, initializes default values.
o Parameterized Constructor: Takes parameters to initialize an object with specific values.
Program1: Write a Java program to create a class called "Person" with a name and age attribute. Create two instances
of the "Person" class, set their attributes using the constructor, and print their name and age.
Source Code:
// Define the Person class
class PersonExample {
// Attributes: name and age
String name;
int age;
// Constructor to initialize name and age
public PersonExample(String name, int age) {
this.name = name;
this.age = age;
}
// Method to print person's details
public void printDetails() {
System.out.println("Name: " + name);
System.out.println("Person 2 Details:");
person2.printDetails();
}
}
Output:
D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>javac PersonExample.java
D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>java Main
Person 1 Details:
Name: Alice
Age: 30
Person 2 Details:
Name: Bob
Age: 25
Program2: Write a Java program to create a class called Person with private instance variables name, age. and country.
Provide public getter and setter methods to access and modify these variables.
Source Code:
class PersonExample1{
// Private instance variables
private String name;
private int age;
private String country;
// Constructor to initialize Person object
this.country = country;
}
// Getter and Setter methods for name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Getter and Setter methods for age
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// Getter and Setter methods for country
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
// Method to print Person details
public void printDetails() {
System.out.println("Name: " + name);
}
}
// Main class to test the Person class
public class Main1{
public static void main(String[] args) {
// Create an instance of Person
PersonExample1 person = new PersonExample1("Alice", 30, "USA");
// Print initial details
System.out.println("Initial Details:");
person.printDetails();
// Modify details using setter methods
person.setName("Bob");
person.setAge(25);
person.setCountry("Canada");
// Print updated details
System.out.println("\nUpdated Details:");
person.printDetails();
}
}
Output;
D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>javac Main1.java
D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>java Main1
Initial Details:
Name: Alice
Age: 30
Country: USA
Updated Details:
Name: Bob
Age: 25
Country: Canada
Viva Questions:
Experiment No. 4
Objective / Aim : Students will learn about how to create Java programs using inheritance and polymorphism
Inheritance is an OOP concept where a new class (child or subclass) is derived from an existing class
(parent or superclass). The child class inherits the attributes and methods of the parent class, enabling code
reuse and establishing a relationship between the two classes.
Advantages:
• Reusability: Inheritance allows the child class to reuse code from the parent class without having to
rewrite it.
• Extensibility: The child class can extend the functionality of the parent class by adding its own
attributes and methods or overriding the inherited methods.
• "is-a" Relationship: Inheritance models an "is-a" relationship. For example, a Dog class is-a type
of Animal.
Polymorphism is an OOP concept that allows objects to be treated as instances of their parent class,
enabling methods to have different behaviors based on the object's actual type. It literally means "many
forms."
1. Compile-time Polymorphism (Method Overloading): Occurs when multiple methods with the
same name are defined in the same class but with different parameter lists (either by changing the
number or types of parameters).
2. Runtime Polymorphism (Method Overriding): Occurs when a subclass provides a specific
implementation of a method that is already defined in its superclass.
Program1: “Java does not support multiple inheritance but we can achieve it by interface”. Write a program to justify
the above statement
Source Code:
interface A{
public static final int x=10;
public abstract void display();
}
interface B{
public static final int y=20;
public abstract void show();
}
class C implements A,B{
public void display(){
System.out.println(x);
}
public void show(){
System.out.println(y);
}
}
class InterfaceExample{
public static void main(String []args){
C ob=new C();
ob.display();
ob.show();
}
}
Output
D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>javac InterfaceExample.java
D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>java InterfaceExample
10
20
Program2: Write a program in java to implement the following types of inheritance: • Single Inheritance • Multilevel
Inheritance
Source Code: Single Inheritance
import java.util.*;
class Person{
String name;
int age;
void inputPerson(){
Scanner sc=new Scanner(System.in);
System.out.println("Enter name");
name=sc.nextLine();
System.out.println("Enter Age");
age=sc.nextInt();
}
void displayPerson(){
System.out.println(name+" "+age);
}
}
}
void displayEmployee(){
System.out.println("Eployee Id: "+eid+" Employee Salary: "+sal);
}
public static void main(String []args){
Employee e=new Employee();
e.inputPerson();
e.displayPerson();
e.inputEmployee();
e.displayEmployee();
}
}
Output:
D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>java Employee
Enter name
ram
Enter Age
33
ram 33
Enter eid
22
Enter salary
50000
Eployee Id: 22 Employee Salary: 50000.0
B(){
System.out.println("Intermediate base class B constructor");
}
void displayB(){
System.out.println("Intermediate base class B");
}
void show(){
System.out.println("Intermediate base class B");
}
}
class C extends B{
C(){
System.out.println("child class C constructor");
}
void displayC(){
System.out.println("In child C class");
void show(){
System.out.println("In child class C show method");
}
}
public class InheritanceExample{
public static void main(String []args){
A ob=new A();
ob.displayA();
ob.show();
B b1=new B();
b1.displayB();
b1.show();
C c1=new C();
c1.displayC();
c1.displayB();
c1.displayA();
c1.show();
}
Output:
D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>java InheritanceExample
base class A constructor
In base A class
In base class A show method
base class A constructor
Intermediate base class B constructor
Intermediate base class B
Intermediate base class B
base class A constructor
Intermediate base class B constructor
child class C constructor
In child C class
Intermediate base class B
In base A class
In child class C show method
Viva Questions:
Inheritance
Interface
Polymorphism
1. What is polymorphism in Java?
2. Explain the difference between method overloading and method overriding.
3. What is compile-time polymorphism?
4. What is runtime polymorphism?
5. Can you achieve polymorphism through interfaces?
Experiment No. 5
Objective / Aim: Students will learn about how to error-handling techniques using exception handling and
understanding of multithreading.
Apparatus Used : Jdk11, Eclipse, Notepad++, Visual Studio
Literature / Theory / Formula :
The exception handling in java is one of the powerful mechanisms to handle the runtime errors so that normal flow
of the application can be maintained. In java, exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime. Exception Handling is a mechanism to handle runtime errors such as
ClassNotFound, IO, SQL, Remote etc. Java try block is used to enclose the code that might throw an exception. It
must be used within the method. Java try block must be followed by either catch or finally block.
Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Program1: Write a Java program to implement user defined exception handling for negative amount entered.
Source Code:
import java.util.Scanner;
// Define a custom exception for negative amounts
class NegativeAmountException extends Exception {
public NegativeAmountException(String message) {
super(message);
}
}
public class NegativeAmountHandler {
// Method to deposit an amount
public static void depositAmount(double amount) throws NegativeAmountException {
if (amount < 0) {
throw new NegativeAmountException("Error: Negative amount entered. Please enter a positive value.");
}
System.out.println("Amount " + amount + " deposited successfully.");
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter an amount to deposit: ");
double amount = scanner.nextDouble();
depositAmount(amount);
} catch (NegativeAmountException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close();
System.out.println("Transaction process completed.");
}
}
}
Output:
D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>javac NegativeAmountHandler.java
D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>java NegativeAmountHandler
Enter an amount to deposit: 12
Amount 12.0 deposited successfully.
Transaction process completed.
n=r.nextInt(20);
if(n%2==0){
Thread.sleep(2000);
Thread t1=new Thread(new Even(n));
t1.start();
}
else{
Thread.sleep(5000);
Thread t2=new Thread(new Odd(n));
t2.start();
}
}
}
catch(Exception e){e.printStackTrace();
}
}
public class MainThread{
public static void main(String []args){
TestEvenOdd obj=new TestEvenOdd();
obj.start();
}
}
Output:
D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>javac MainThread.java
D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>java MainThread
The Thread 3 is Odd and Cube of 3 is : 27
The Thread 19 is Odd and Cube of 19 is : 6859
The Thread 17 is Odd and Cube of 17 is : 4913
The Thread 1 is Odd and Cube of 1 is : 1
The Thread 17 is Odd and Cube of 17 is : 4913
The Thread 18 is EVEN and Square of 18 is : 324
The Thread 12 is EVEN and Square of 12 is : 144
The Thread 7 is Odd and Cube of 7 is : 343
The Thread 7 is Odd and Cube of 7 is : 343
The Thread 1 is Odd and Cube of 1 is : 1
Viva Question:
1. What is exception handling?
2. What is the difference between checked and unchecked exceptions?
3. What are the key keywords in Java exception handling?
4. What is the difference between throw and throws?
5. What is the use of the finally block?
6. What is a user-defined exception?
7. Why would you use custom exceptions?
8. When should you use finally?
9. Why is catching generic exceptions (Exception) considered bad practice?
10. Can we have multiple catch blocks for a single try block?
11. What happens if an exception occurs in the catch block?
12. Can we have a try block without a catch block?
Experiment No. 6
Objective / Aim: Students will learn about how to create java program with the use of java packages
Apparatus Used: Jdk11, Eclipse, Notepad++, Visual Studio
Literature / Theory / Formula:
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are used for: Preventing naming conflicts. For example there can be two classes with name Employee in
two packages, college.staff.cs.Employee and college.staff.ee.Employee. Making searching/locating and usage of
classes, interfaces, enumerations, and annotations easier.
• Providing controlled access: protected and default have package level access control.
• A protected member is accessible by classes in the same package and its subclasses.
• A default member (without any access specifier) is accessible by classes in the same package only.
• Packages can be considered as data encapsulation (or data-hiding).
Program1: Create a package named “Mathematics” and add a class “Matrix” with methods to add and subtract
matrices (2x2). Write a Java program importing the Mathematics package and use the classes defined in it.
Source Code:
//MyClass.java
package com1.myPackage;
public class MyClass{
protected static void getName(String s){
System.out.println("My name is"+s);
}
}
///MyClassTest.java
package com2.myPackage;
public class MyClassTest{
void getName(String s){
System.out.println(s);
}
}
Viva Questions:
1. What are the types of packages in Java?
2. How do you create a package in Java?
3. How do you access a class from a package?
Experiment No. 7
Objective / Aim: Students will learn about how to construct java program using Java I/O package
Apparatus Used: Jdk11, Eclipse, Notepad++, Visual Studio
Literature / Theory / Formula:
The Java I/O (Input/Output) package (java.io) provides classes and interfaces for system input and output operations
such as reading and writing data to files, console, and other streams. It is part of the Java Standard Edition and offers
a wide range of functionality for handling both character-based and byte-based data.
Program: Write a program in java to take input from user by using all the following methods: • DataInputStream Class
• BufferedReader Class • Scanner Class • Console Class
Source Code:
import java.io.*;
class IOExample{
public static void main(String []args)throws IOException{
//int a=Integer.parseInt(args[0]);
//System.out.println("Data read from command Line"+a);
FileInputStream in=null;
FileOutputStream out=null;
FileReader fr=null;
FileWriter fw=null;
//BufferedReader br=null;
//BufferedWriter bw=null;
/*try{
in=new FileInputStream("file.txt");
out=new FileOutputStream("file1.txt");
int ch;
while((ch=in.read())!=-1){
//System.out.print((char)ch);
out.write(ch);
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
finally{
if(in!=null){
in.close();
}
}*/
/*try{
fr=new FileReader("file.txt");
fw=new FileWriter("file2.txt");
int ch;
String s="";
while((ch=fr.read())!=-1){
System.out.print((char)ch);
s+=(char)ch;
}
fw.write(s);
}
catch(FileNotFoundException e){
e.printStackTrace();
}
finally{
if(fr!=null){
fr.close();
}
}*/
/*try{
fr=new FileReader("file.txt");
br=new BufferedReader(fr);
fw=new FileWriter("file2.txt");
bw=new BufferedWriter(fw);
InputStreamReader isr=new InputStreamReader(System.in);
int ch;
String s="";
while((ch=br.read())!=-1){
System.out.print((char)ch);
//s+=(char)ch;
}
bw.write("GCET Engineering College!!");
br=new BufferedReader(isr);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Name"+name);
}
catch(FileNotFoundException e){
e.printStackTrace();
}
finally{
if(br!=null){
fr.close();
}
}*/
/*Console c=System.console();
System.out.println("Enter User Name:");
String name=c.readLine();
System.out.println("Enter User Password:");
char pass[]=c.readPassword();
System.out.println("User Name:"+name);
System.out.println("User Password:"+pass);*/
Experiment No. 8
Objective / Aim: Students will learn about how Create industry-oriented application using Spring Framework.
Apparatus Used: Jdk11, Eclipse, Notepad++, Visual Studio
Literature / Theory / Formula:
• Open-Source Framework
• Standalone and Enterprise application can be developed
• Released in 2003(initial), 2004(production) developed by Rod Johnson
• The Spring container is the core of the Spring Framework.
• Manages Bean Objects(create, initialize, destroy)[Life cycle of bean]
• It is responsible for creating, configuring, and managing the objects that make up your application.
• The container uses a technique called dependency injection to manage the relationships between objects.
• Transaction Management
Spring container are of TWO TYPES
1. BeanFactory(old Method)
2. ApplicationContext(new Method)
Program1: Create industry-oriented application using Spring Framework
Source Code:
Code: Pojo Class
package in.abes.CSEDS;
return Name;
return rollno;
this.rollno = rollno;
}
return email;
this.email = email;
XML Configuration:
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</bean>
</beans>
Main file:
package in.abes.main;
Viva Questions:
1. What is the Spring Framework, and why is it popular for Java development?
2. Explain the concept of Dependency Injection (DI) in Spring.
3. What are the different types of Dependency Injection supported by Spring?
4. What is the difference between @Component, @Repository, @Service, and @Controller annotations in
Spring?
Experiment No. 9
Objective / Aim : Students will learn about how to Test Frontend web application with Spring Boot.
Apparatus Used : Jdk11, Eclipse, Notepad++, Visual Studio
Literature / Theory / Formula :
• Spring Boot is a project that is built on top of the Spring Framework. It provides an easier and faster way to
set up, configure, and run both simple and web-based applications.
• It is a Spring module that provides the RAD (Rapid Application Development) feature to the Spring
Framework used to create a stand-alone Spring-based application that you can just run because it needs
minimal Spring configuration.
Source Code:
}
OOPs with Java Lab (BCS 452) 39
Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA
EmployeeControllerTest.java
package com.example.demo.controller;
import com.example.demo.model.Employee;
import com.fasterxml.jackson.databind.ObjectMapper; import
org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import
org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
@Test
public void testCreateEmployee() throws Exception {
mockMvc.perform(post("/employees")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(employee)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value(employee.getName()))
.andExpect(jsonPath("$.role").value(employee.getRole()));
}
@Test
public void testGetEmployeeById() throws Exception {
mockMvc.perform(post("/employees")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(employee)))
.andExpect(status().isOk());
mockMvc.perform(get("/employees/{id}", 1L))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value(employee.getName()))
.andExpect(jsonPath("$.role").value(employee.getRole()));
}
Viva Questions:
1. What is Spring Boot, and how is it different from the Spring Framework?
2. What are the key features of Spring Boot?
3. Explain the purpose of the @SpringBootApplication annotation.
4. What is an embedded server in Spring Boot? Which servers are supported?
5. What is the role of the application.properties or application.yml file in Spring Boot?
6. How does Spring Boot simplify dependency management?
7. What is Spring Boot Starter, and how is it useful?
8. How do you configure a Spring Boot application to connect to a database?
9. Explain the use of Spring Boot Actuator.
10. What is the role of @EnableAutoConfiguration in Spring Boot?
11. How do you run a Spring Boot application? Can it be packaged as a JAR or WAR file?
12. What are Spring Boot profiles, and how are they configured?
13. How do you implement logging in Spring Boot applications?
14. What is the difference between @RestController and @Controller in Spring Boot?
15. Explain the use of @Configuration and @Bean in Spring Boot applications.
16. How do you create REST APIs in Spring Boot?
17. What is the purpose of @PathVariable and @RequestParam annotations?
18. How do you handle exceptions globally in a Spring Boot application?
Experiment No. 10
Objective / Aim : Students will learn about how to Test RESTful web services using Spring Boot.
Apparatus Used : Jdk11, Eclipse, Notepad++, Visual Studio
Literature / Theory / Formula :
REST stands for REpresentational State Transfer. It is developed by Roy Thomas Fielding, who also developed HTTP.
The main goal of RESTful web services is to make web services more effective. RESTful web services try to define
services using the different concepts that are already present in HTTP. REST is an architectural approach, not a
protocol.
Source Code:
POST
http://localhost:8080/api/users
GET
http://localhost:8080/api/users
PUT
http://localhost:8080/api/users/1
DELETE
http://localhost:8080/api/users/1
Viva Questions:
1. What is Spring Boot, and how is it different from the Spring Framework?
2. What are the key features of Spring Boot?
3. Explain the purpose of the @SpringBootApplication annotation.
4. What is an embedded server in Spring Boot? Which servers are supported?
5. What is the role of the application.properties or application.yml file in Spring Boot?
6. How does Spring Boot simplify dependency management?
7. What is Spring Boot Starter, and how is it useful?
8. How do you configure a Spring Boot application to connect to a database?
9. Explain the use of Spring Boot Actuator.
10. What is the role of @EnableAutoConfiguration in Spring Boot?
DemoApplication.java:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
BookController.Java:
package com.example.demo.Controllers;
import org.springframework.web.bind.annotation.*; import
java.util.ArrayList;
import java.util.List; @RestController
@RequestMapping("/books") public
class BookController {
private List<String> books = new ArrayList<>();
// Handler method to return a string (GET) @GetMapping
public List<String> getBooks() { if
(books.isEmpty()) {
books.add("Sample Book");
}
return books;
}
Controllers:
package Controllers;
import org.springframework.web.bind.annotation.GetMapping; import
org.springframework.web.bind.annotation.RestController; @RestController
public class BookController {
//handler method return string
@GetMapping(path= "/books") public
String getBooks()
{
Pom.Xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.1</version>
<relativePath/> <!-- lookup parent from repository -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</project>
================