[go: up one dir, main page]

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

Lab Manual

The document outlines a series of experiments for students at Galgotia's College of Engineering & Technology, focusing on Java programming concepts such as command-line arguments, object-oriented programming (OOP) principles, and inheritance. It includes sample programs for checking prime numbers and palindromes, as well as explanations of OOP concepts like encapsulation, inheritance, polymorphism, and abstraction. Additionally, it provides viva questions to assess students' understanding of these topics.
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 views49 pages

Lab Manual

The document outlines a series of experiments for students at Galgotia's College of Engineering & Technology, focusing on Java programming concepts such as command-line arguments, object-oriented programming (OOP) principles, and inheritance. It includes sample programs for checking prime numbers and palindromes, as well as explanations of OOP concepts like encapsulation, inheritance, polymorphism, and abstraction. Additionally, it provides viva questions to assess students' understanding of these topics.
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/ 49

Galgotia’s College of Engineering & Technology

1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

Experiment No. 1
Objective / Aim : Students will learn about how to create simple java programs using command line arguments

Apparatus Used : Jdk11, Eclipse, Notepad++, Visual Studio

Literature / Theory / Formula :


In Java, command-line arguments are used to pass information to a program when it is executed. These arguments are
provided as a string array to the main method of the program.
Syntax
public static void main(String[] args){
}
Program1: WAP that takes input from user through command line argument and then prints whether a number is
prime or not.
Source Code:
class Prime {
public static int isPrime(int x)
{
int i;
for (i = 2; i < x / 2 + 1; i++) {
if (x % i == 0) {
return 0;
}
}

return 1;
}

public static void main(String[] args)


{
if (args.length > 0) {
int n = Integer.parseInt(args[0]);
if (isPrime(n) == 1)

OOPs with Java Lab (BCS 452) 1


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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

D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>java Prime

No command line arguments found.

D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>java Prime 25

No

D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>java Prime 3

Yes

Questions for Viva-voice:


D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>
1. What are command-line arguments in Java? How are they passed to a program?
2. How do you access command-line arguments in a Java program?
3. What happens if the required command-line arguments are not provided when running the program?
4. Can command-line arguments be used to pass non-string values? How would you handle such cases?
5. Write a small Java code snippet to calculate the sum of integers passed as command-line arguments.
6. Explain the role of the args array in the main method.
7. How can you run a program with command-line arguments in Eclipse IDE?
8. What is the difference between command-line arguments and user inputs using Scanner in Java?

OOPs with Java Lab (BCS 452) 2


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

Experiment No. 1

Objective / Aim : Students will learn about how to create simple java programs using command line arguments

Apparatus Used : Jdk11, Eclipse, Notepad++, Visual Studio

Literature / Theory / Formula:


In Java, command-line arguments are used to pass information to a program when it is executed. These arguments are
provided as a string array to the main method of the program.
Syntax
public static void main(String[] args){
}
Program2: Write a program to enter number through command line and check whether it is palindrome or not.
Source Code:
class Palindrome
{
/* Iterative function to reverse digits of num*/
static int reverseDigits(int num)
{
int rev_num = 0;
while (num > 0) {
rev_num = rev_num * 10 + num % 10;
num = num / 10;
}
return rev_num;
}

OOPs with Java Lab (BCS 452) 3


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

/* Function to check if n is Palindrome*/

static int isPalindrome(int n)


{

// get the reverse of n


int rev_n = reverseDigits(n);

// Check if rev_n and n are same or not.


if (rev_n == n)
return 1;
else
return 0;
}
/*Driver program to test reverseDigits*/
public static void main(String []args)
{
int n = Integer.parseInt(args[0]);
System.out.println("Is" + n + "a Palindrome number? -> " +
(isPalindrome(n) == 1 ? "true" : "false"));

}
}

OOPs with Java Lab (BCS 452) 4


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

Output:

D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>javac Palindrome.java

D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>java Palindrome

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

at Palindrome.main(Palindrome.java:31)

D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>java Palindrome 121

Is121a Palindrome number? -> true

D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>java Palindrome 120

Is120a Palindrome number? -> false

Questions for Viva-voice:


D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>
1. What are command-line arguments in Java? How are they passed to a program?
2. How do you access command-line arguments in a Java program?
3. What happens if the required command-line arguments are not provided when running the program?
4. Can command-line arguments be used to pass non-string values? How would you handle such cases?
5. Write a small Java code snippet to calculate the sum of integers passed as command-line arguments.
6. Explain the role of the args array in the main method.
7. How can you run a program with command-line arguments in Eclipse IDE?
8. What is the difference between command-line arguments and user inputs using Scanner in Java?

OOPs with Java Lab (BCS 452) 5


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

Experiment No. 3

Objective / Aim : Students will learn about OOP concepts and basics of Java programming
Apparatus Used : Jdk11, Eclipse, Notepad++, Visual Studio

Literature / Theory / Formula:

Class and Object

• 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

OOPs with Java Lab (BCS 452) 6


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches


• Definition: Abstraction involves hiding complex implementation details and showing only essential
features to the user.
• Purpose: Simplifies interaction with objects and reduces complexity.

• 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);

OOPs with Java Lab (BCS 452) 7


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

System.out.println("Age: " + age);


}
}
// Main class to test the Person class
class Main {
public static void main(String[] args) {
// Create two instances of the Person class

PersonExample person1 = new PersonExample("Alice", 30);


PersonExample person2 = new PersonExample("Bob", 25);

// Print details of both persons


System.out.println("Person 1 Details:");
person1.printDetails();
System.out.println(); // Blank line for separation

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:

OOPs with Java Lab (BCS 452) 8


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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

public PersonExample1(String name, int age, String country) {


this.name = name;
this.age = age;

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() {

OOPs with Java Lab (BCS 452) 9


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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);

System.out.println("Age: " + age);


System.out.println("Country: " + country);

}
}
// 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

OOPs with Java Lab (BCS 452) 10


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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:

1. What are the key principles of Object-Oriented Programming?


2. How is encapsulation achieved in Java? Provide an example.
3. Explain inheritance in Java with a real-world analogy.
4. What is polymorphism in Java? Differentiate between compile-time and runtime polymorphism.

OOPs with Java Lab (BCS 452) 11


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches


5. Can a class in Java implement multiple interfaces? How is this different from multiple inheritance using
classes?
6. How does abstraction differ from encapsulation in Java?
7. Explain the use of the this keyword in Java with an example.
8. Write a basic program in Java to demonstrate the concept of inheritance and method overriding.
9. What is the purpose of constructors in Java? Can a constructor be overloaded?
10. How are objects created in Java? What is the role of the new keyword?

OOPs with Java Lab (BCS 452) 12


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

Experiment No. 4
Objective / Aim : Students will learn about how to create Java programs using inheritance and polymorphism

Apparatus Used : Jdk11, Eclipse, Notepad++, Visual Studio

Literature / Theory / Formula :

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."

There are two main types of polymorphism in Java:

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

OOPs with Java Lab (BCS 452) 13


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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();

OOPs with Java Lab (BCS 452) 14


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

}
}
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);
}
}

OOPs with Java Lab (BCS 452) 15


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

public class Employee extends Person{


int eid;
double sal;
void inputEmployee(){
Scanner sc=new Scanner(System.in);
System.out.println("Enter eid");
eid=sc.nextInt();
System.out.println("Enter salary");
sal=sc.nextDouble();

}
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

OOPs with Java Lab (BCS 452) 16


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

ram
Enter Age
33
ram 33
Enter eid
22
Enter salary
50000
Eployee Id: 22 Employee Salary: 50000.0

Source Code: Multilevel Inheritance


class A{
A(){
System.out.println("base class A constructor");
}
void displayA(){
System.out.println("In base A class");
}
void show(){
System.out.println("In base class A show method");
}
}
class B extends A{

OOPs with Java Lab (BCS 452) 17


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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();

OOPs with Java Lab (BCS 452) 18


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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

OOPs with Java Lab (BCS 452) 19


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

In base A class
In child class C show method
Viva Questions:
Inheritance

1. What is inheritance in Java? Why is it used?


2. Explain the difference between single, multilevel, and hierarchical inheritance.
3. Why does Java not support multiple inheritance with classes?
4. What is the role of the super keyword in inheritance? Provide an example.
5. Can a subclass override a private method of the superclass? Why or why not?
6. Write a Java program to demonstrate method overriding.
7. What happens if a constructor is not explicitly defined in a subclass?
8. Explain the difference between method overloading and method overriding.

Interface

1. What is an interface in Java, and why is it used?


2. How is an interface different from an abstract class?
3. Can an interface contain constructors? Why or why not?
4. How do you implement multiple interfaces in a class? Provide an example.
5. What is the default access modifier for interface methods and variables?
6. How can an interface extend another interface?
7. Can we declare a method in an interface as private or static?
8. Write a program to demonstrate the use of interfaces for achieving polymorphism.

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?

OOPs with Java Lab (BCS 452) 20


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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) {

OOPs with Java Lab (BCS 452) 21


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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.

OOPs with Java Lab (BCS 452) 22


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

D:\SESSION 2023-24 EVEN\OOPs with Java\Java Program>java NegativeAmountHandler


Enter an amount to deposit: -2
Error: Negative amount entered. Please enter a positive value.
Transaction process completed.
Program2: WAP in java which creates two threads, “Even” thread and “Odd” thread and print the even no using
Even Thread after every two seconds and odd no using Odd Thread after every five second.
Source Code:
import java.util.*;
import java.io.*;
class Even implements Runnable{
int a;
Even(int a){
this.a=a;
}
public void run(){
System.out.println("The Thread "+ a +" is EVEN and Square of " + a + " is : " + a*a);
}
}
class Odd implements Runnable{
int a;
Odd(int a){
this.a=a;
}
public void run(){
System.out.println("The Thread "+ a +" is Odd and Cube of " + a + " is : " + a*a*a);
}
}

OOPs with Java Lab (BCS 452) 23


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

class TestEvenOdd extends Thread{


public void run(){
int n=0;
try{
Random r=new Random();
for(int i=0;i<10;i++){

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();

OOPs with Java Lab (BCS 452) 24


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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?

OOPs with Java Lab (BCS 452) 25


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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);

OOPs with Java Lab (BCS 452) 26


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

}
}

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?

OOPs with Java Lab (BCS 452) 27


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

4. Can a class belong to multiple packages?


5. Why are packages used in Java?
6. What is the default package in Java?
7. How do you compile and run a Java program with packages?
8. What are some commonly used built-in packages?
9. What is the difference between import and static import?
10. Can two classes in different packages have the same name?
11. How is access control affected by packages?
12. What happens if two packages contain classes with the same name?
13. What is the role of the CLASSPATH environment variable?
14. What is the naming convention for packages?
15. Why should you avoid using the default package in large projects?
16. What is the difference between java.util and java.lang?

OOPs with Java Lab (BCS 452) 28


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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){

OOPs with Java Lab (BCS 452) 29


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

//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();
}

OOPs with Java Lab (BCS 452) 30


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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();

OOPs with Java Lab (BCS 452) 31


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

}
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);*/

DataOutputStream dout = new DataOutputStream(new FileOutputStream("file1.txt"));


dout.writeInt(45);
dout.writeFloat(98.7F);
dout.writeLong(123456);
dout.close();
DataInputStream din =new DataInputStream(new FileInputStream("file1.txt"));
int intData= din.readInt();
float floatData=din.readFloat();
long longData=din.readLong();
din.close();
System.out.println("int data: " + intData);
System.out.println("float data: " + floatData);

OOPs with Java Lab (BCS 452) 32


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

System.out.println("long data: " + longData);


}
}

OOPs with Java Lab (BCS 452) 33


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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;

public class Student { private


String Name; private int rollno;
private String email; public String
getName() {

return Name;

public void setName(String name) { Name = name;

OOPs with Java Lab (BCS 452) 34


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches


}

public int getRollno() {

return rollno;

public void setRollno(int rollno) {

this.rollno = rollno;
}

public String getEmail() {

return email;

public void setEmail(String email) {

this.email = email;

public void display()

System.out.println("Name :" +Name); System.out.println("Rollno


:" +rollno); System.out.println("Email :" +email);
}

XML Configuration:

<?xml version="1.0" encoding="UTF-8"?>

OOPs with Java Lab (BCS 452) 35


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="

http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- bean definitions here -->


<bean class= "in.abes.CSEDS.Student" id="stdId">

<property name ="Name" value="Yash" />

<property name= "rollno" value="101" />

<property name="email" value="xyz@gmail.com" />

</bean>
</beans>
Main file:
package in.abes.main;

import org.springframework.context.ApplicationContext; import


in.abes.CSEDS.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
String config_loc= "/in/abes/resources/applicationContext.xml"; ApplicationContext context
=new
ClassPathXmlApplicationContext(config_loc); Student s=(Student)context.getBean("stdId"); s.display(); } }

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?

OOPs with Java Lab (BCS 452) 36


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches


5. What is the purpose of the Spring IoC (Inversion of Control) container?
6. Explain the difference between BeanFactory and ApplicationContext in Spring.
7. What are Spring beans, and how are they managed in the Spring container?
8. How do you define a bean in Spring XML configuration? How can it be done with annotations?
9. What is Spring AOP (Aspect-Oriented Programming)? Provide a real-world use case.
10. What is the role of the @Transactional annotation in Spring?
11. Explain the difference between singleton and prototype bean scopes in Spring.
12. What is the role of the DispatcherServlet in Spring MVC?
13. How do you handle exceptions in Spring MVC applications?
14. What is the use of @RestController in Spring?
15. What are the key differences between @RequestMapping and @GetMapping?

OOPs with Java Lab (BCS 452) 37


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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:

Step 1: Add Dependencies to pom.xml


<dependencies>

<!-- Spring Boot Web Starter -->


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Test Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- For JSON processing -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>

OOPs with Java Lab (BCS 452) 38


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

Step 2: Create a RESTful Web Service


Employee.java
package com.example.demo.model;

public class Employee { private

long id; private String name;


private String role;
// Constructors, getters, and setters public
Employee() {}
public Employee(long id, String name, String role) { this.id = id;
this.name = name; this.role =
role;
}

public long getId() { return id;


}

public void setId(long id) { this.id = id;


}

public String getName() {


return name;
}

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


name;
}

public String getRole() { return role;


}

public void setRole(String role) { this.role = role;


}

}
OOPs with Java Lab (BCS 452) 39
Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

Step 3: Write Unit Tests for the RESTful Web


Service Create a test class for EmployeeController.

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;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static


org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@WebMvcTest(EmployeeController.class) public class


EmployeeControllerTest {
@Autowired
private MockMvc mockMvc; @Autowired
private ObjectMapper objectMapper; private
Employee employee; @BeforeEach
public void setup() {
employee = new Employee(1L, "John Doe", "Developer");
}

@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()));
}

OOPs with Java Lab (BCS 452) 40


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches


@Test
public void testGetAllEmployees() throws Exception {
mockMvc.perform(get("/employees"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}

@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?

OOPs with Java Lab (BCS 452) 41


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches


19. What is the difference between synchronous and asynchronous request handling in Spring Boot?
20. How do you secure a Spring Boot application? Explain the role of Spring Security.

OOPs with Java Lab (BCS 452) 42


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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:

We have used POSTMAN to test Application developed in Experiment 9 as follows

POST
http://localhost:8080/api/users

GET
http://localhost:8080/api/users

OOPs with Java Lab (BCS 452) 43


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

PUT

http://localhost:8080/api/users/1

OOPs with Java Lab (BCS 452) 44


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

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?

OOPs with Java Lab (BCS 452) 45


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches

Experiment No. 11 (Beyond Syallabus)


Objective / Aim : Students will learn about CRUD Operations using REST API using ArrayList or Map
Apparatus Used : Jdk11, Eclipse, Notepad++, Visual Studio
Literature / Theory / Formula :

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;
}

// Handler method to add a book (POST) @PostMapping


public String addBook(@RequestBody String book) { books.add(book);
return "Book added successfully: " + book;
}
OOPs with Java Lab (BCS 452) 46
Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches


// Handler method to delete a book (DELETE)
@DeleteMapping("/{book}")
public String deleteBook(@PathVariable String book) { if
(books.remove(book)) {
return "Book removed successfully: " + book;
} else {
return "Book not found: " + book;
}

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()
{

return "this is testing book first";


}

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 -->

OOPs with Java Lab (BCS 452) 47


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches


</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<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>

OOPs with Java Lab (BCS 452) 48


Galgotia’s College of Engineering & Technology
1, Knowledge Park II, Greater Noida – 201 310 (UP) INDIA

Dept. of Computer Science and Allied Branches


</plugins>
</build>

</project>

================

OOPs with Java Lab (BCS 452) 49

You might also like