Details of the Experiments Conducted
S.No. List of Experiments as per AKTU Page Date of Date of Faculty
recommendation No Conduction Submission Signature
1. Use Java complier and eclipse
platform to write and execute java 1
program.
2. Creating simple java program using
command line arguments. 3
UnderstandingOOP concepts and
3.
basics of java programming. 4
Create java program using 6
4. inheritanceand polymorphism.
Implement error – handling
5. techniques using exception handling
9
and multithreading.
6. Create java program with the use of 14
java packages.
Create Java program using Java I/O 15
7. packages.
Create industry oriented application 16
8. using Spring.
Test RESTful web services using 18
9. Spring Boot.
PROGRAM #1
Use java compiler and eclipse platform to write and execute
java program.
Setting Up:
• Install Eclipse:
1. Download the latest version of Eclipse IDE for Java
Developers from the official website: [Download Eclipse
IDE for Java Developers]
2. Follow the installation instructions for your operating
system.
3. Download and Install JDK (Java Development Kit):
4. The JDK includes the Java compiler (javac) needed to
compile your code.
5. Download the latest version of JDK from Oracle: [Java
SE Downloads]
6. Follow the installation instructions for your operating
system.
7. Writing and Running Your Program in Eclipse:
• Create a New Project:
• Open Eclipse and go to File > New > Java Project.
• Give your project a name and click Finish.
• Create a New Java Class:
In the Package Explorer (left-hand side panel), right-
click on the src folder within your project.
Select New > Class.
Name your class file (e.g., MyFirstProgram.java) and
click Finish.
• Write Your Java Code:
• In the editor window, write your Java code. Here's a simple
example to get you started:
OOPs with Java Lab file Page 1
JAVA PROGRAM :
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
This code defines a class named Hello with a main method. The
main method is the entry point of your program. The
System.out.println statement prints the message "Hello,
World!" to the console.
• Save Your Class:
• Click on File > Save or use the shortcut Ctrl+S.
• Compile and Run the Program:
There are two ways to compile and run your program:
Method 1: - Click the Run button (green arrow) on the toolbar.
- Alternatively, go to Run > Run. - In the Run Configurations
window, select your Java class (e.g., MyFirstProgram.java)
from the list and click Run.
Method 2: - Right-click on your class file in the Package
Explorer. - Select Run As > Java Application.
• View the Output:
The output of your program will be displayed in the Console
view (usually located at the bottom of the Eclipse window). In
this case, you should see "Hello, World!" .
OOPs with Java Lab file Page 2
PROGRAM #2
Creating simple java programs using command line
arguments.
Steps to Create a Java Program with Command-Line Arguments:
1. Define the main method: This is the entry point of your
program where execution begins.
2. Include the args parameter: The main method signature
should look like public static void main(String[] args).
3. Access arguments: Use the args array to retrieve the
provided arguments. You can check the length of the array
using args.length to ensure arguments were supplied.
4. Process arguments: Employ a loop or indexing to iterate
through the args array and process each argument based on
your program's logic.
Example : Printing Command-Line Arguments
public class HelloArgs
{
public static void main(String[] args)
{
if (args.length> 0)
System.out.println("Sorry No arguments provided.");
else
{
for (int i = 0; i<args.length; i++)
System.out.println(“Welcome ”+args[i]);
// for (String n :args) // with foreach loop
//System.out.println(“Welcome ”+n);
}
}
}
Output: Sorry No arguments provided.
Run with command line arguments –
You need to go to: Run Configuration > Argument > Program
argument. Then – Jiya Abhay Abhishek Mayank Golu Run it.
Output:
Welcome Jiya
Welcome Abhay
Welcome Abhishek
Welcome Mayank
Welcome Golu
OOPs with Java Lab file Page 3
PROGRAM #3
Understand OOP concepts and basics of java programming.
OOP Concepts in Java:
1. Objects and Classes:
o An object is an instance of a class, representing a
real-world entity with attributes and
functionalities. Think of it as a specific car.
o A class is a blueprint that defines the properties
(variables) and methods (functions) that objects of
that class will share. It's like the general concept
of a car.
2. Encapsulation:
o Encapsulation binds data and methods together within
an object, restricting direct access to the data.
This promotes data protection and controlled
modification. Imagine a car's engine being
encapsulated, with methods to start or stop it
instead of exposing the internal workings.
3. Inheritance:
o Inheritance allows you to create new classes
(subclasses) that inherit properties and methods
from existing classes (superclasses). This promotes
code reusability and creates hierarchical
relationships between objects. For instance, a
sports car class might inherit from a general car
class, adding properties specific to sports cars.
4. Polymorphism:
o Polymorphism enables objects of different classes to
respond to the same method call in distinct ways. It
allows for flexible and dynamic behavior. Imagine a
makeSound() method that makes a car honk, a dog
bark, and a cat meow depending on the object it's
called on.
5. Abstraction:
o Abstraction focuses on providing essential
functionalities without exposing the underlying
implementation details. It allows users to interact
with objects at a higher level, hiding complexities.
For example, you might interact with a car using
methods like accelerate() and brake() without
needing to know about the engine or mechanics.
OOPs with Java Lab file Page 4
Java Programming Basics:
1. Setting Up the Development Environment:
o You'll need Java Development Kit (JDK) installed,
which provides the compiler and tools to run Java
programs.
o A text editor or IDE (Integrated Development
Environment) is recommended for writing and managing
Java code. Popular options include Eclipse,
Netbeans, or simple code editors like Notepad++.
2. Structure of a Java Program:
o A Java program typically consists of classes. Each
class definition starts with the class keyword
followed by the class name.
o Within a class, you define variables (using data
types like int, double, or String) to hold data and
methods (using the void return type for methods that
don't return a value) to perform actions.
3. Compiling and Running Java Programs:
o Set the environment variables, path with jdk bin
o The javac command is used to compile Java code
(.java files) into bytecode (.class files).
o The java command is used to execute the compiled
bytecode files.
OOPs with Java Lab file Page 5
PROGRAM #4
Create java programs using inheritance and polymorphism.
Example : Employee Hierarchy with Inheritance
class Employee
{
private String name;
private int id;
public Employee(String name, int id)
{
this.name = name;
this.id = id;
}
public String getEmployeeInfo()
{
return "Name: " + name + ", ID: " + id;
}
}
class Manager extends Employee
{
private String department;
public Manager(String name, int id, String department)
{
super(name, id); // Call superclass constructor
this.department = department;
}
public String getManagerInfo()
{
return getEmployeeInfo()+", Department: " + department;
}
}
class Engineer extends Employee
{
private String[] skills;
public Engineer(String name, int id, String[] skills)
{
super(name, id);
this.skills = skills;
}
OOPs with Java Lab file Page 6
public String getEngineerInfo()
{
String skillList = "";
for (String skill : skills)
skillList += skill + ", ";
return getEmployeeInfo() + ", Skills: " + skillList;
}
}
public class EmployeeDemo
{
public static void main(String[] args)
{
Employee emp = new Employee("Abhay Pratap", 1005);
Manager mgr = new Manager("Golu Singh", 1001,"ERP");
Engineer eng = new Engineer("Komal Goel", 1002, new
String[]{"Java", "Python"});
System.out.println(emp.getEmployeeInfo());
System.out.println(mgr.getManagerInfo());
System.out.println(eng.getEngineerInfo());
}
}
Output :
Name: Abhay Pratap, ID:1005
Name: Golu Singh, ID:1001, Department: ERP
Name: Komal Goel, ID:1002, Skills: Java, Python
OOPs with Java Lab file Page 7
Example : Shape Hierarchy with Polymorphism
// Abstract base class
abstract class Shape {
abstract double calculateArea();
}
// Square subclass
class Square extends Shape {
private double sideLength;
public Square(double sideLength) {
this.sideLength = sideLength;
}
@Override
double calculateArea() {
return sideLength * sideLength;
}
}
// Circle subclass
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}
public class ShapeDemo
{
public static void main(String[] args)
{
Shape[] shapes = {new Square(5), new Circle(3)};
// Polymorphism in action - same method call with diff behaviors
for (Shape shape : shapes)
System.out.println("Area: " + shape.calculateArea());
}
}
Output :
Area: 25.0
Area: 28.274333882308138
OOPs with Java Lab file Page 8
PROGRAM #5
Implement error – handling techniques using exception
handling and multithreading.
Exception Handling:
by using the exception handling we can control the abnormal
termination of program.
or
The core advantage of exception handling is to maintain the
normal flow of the application.
An exception normally interrupt the normal flow of the
application. that's why we use exception handling.
or
The Exception Handling in Java is one of the powerful
mechanism to handle the runtime errors so that normal flow of
the application can be maintained.
how to handle– we have 5 keywords for exception handling– try,
catch, throw, throws& finally
try - check the code there is any Exception or not, if yes
then handle in catch block.
catch - Action on that Exception,Catch the general Exception
type to handle any unexpected exceptions.
finally - at the end of try & catch block - this is optional.
Use a finally block to execute code regardless of
whether an exception occurred.
throw - use with condition for generate the new Exception, if
we want to generate the own exception for that we can use
throw keyword.
throws - use with method body for handle the exception.
OOPs with Java Lab file Page 9
// program without exception handling
package my;
class Ex1
{
public static void main(String aa[])
{
int a = Integer.parseInt(aa[0]); // NumberFormat + ArrayIndex
int x = 100 / a; // ArithmeticException
System.out.println("x is = "+x);
System.out.println("Thanxxxxxxxxxxxx");
}
}
/* Thanx msg display only on normal flow of application, if
any exception occurs than terminate the program.
javac -d . Ex1.java
java my.Ex1
*/
// program with exception handling - using single catch block
// 100% use - this is the best algo for exception handling
package my;
class Ex2
{
public static void main(String aa[])
{
try
{
int a = Integer.parseInt(aa[0]); // NumberFormat + ArrayIndex
int x = 100 / a; // ArithmeticException
System.out.println("x is = "+x);
}
catch(Exception ex)
{
System.out.println("Exeption is - "+ex);
}
System.out.println("Thanxxxxxxxxxxxx");
}
}
// Thanx msg always display
// javac -d . Ex2.java
// java my.Ex2
//program with exception handling - using multiple catch block
OOPs with Java Lab file Page 10
package my;
class Ex3
{
public static void main(String aa[])
{
try
{
int a = Integer.parseInt(aa[0]); // NumberFormat + ArrayIndex
int x = 100 / a; // ArithmeticException
System.out.println("x is = "+x);
}
catch(ArithmeticException ex) // only for ArithmeticException
{
System.out.println("Ohh! Sorry this is / by 0");
}
catch(NumberFormatException ex) // only for NumberFormat
{
System.out.println("Sorry invalid Number for Type casting ");
}
catch(ArrayIndexOutOfBoundsException ex) // only for ArrayIndex
{
System.out.println("Sorry no command line arguments. ");
}
System.out.println("Thanxxxxxxxxxxxx");
}
}
// Thanx msg always display
// javac -d . Ex1.java
// java my.Ex1
Multithreading:
Thread –
Thread is a path of Execution / light weight process.
or
Thread is the smallest unit of program – this is the best
definition
Multi-threading in Java is a powerful feature that allows
concurrent execution of two or more threads for maximum
utilization of CPU. Each thread runs in parallel and can
perform different tasks simultaneously. Special kind of
multitasking.
1. Thread Creation: Create threads to perform tasks
concurrently.We have 2 ways for creating a new thread Ist one
is extends with a Thread class and another one is implements
with Runnable Interface
OOPs with Java Lab file Page 11
2. Synchronization: Use locks or other synchronization
techniques to prevent data races and ensure thread safety.
3. Thread Exception Handling: Use try-catch blocks within
threads to handle exceptions.
4. Thread.join(): Use Thread.Join to wait for a thread to
complete and handle any exceptions.
// to control the main Thread
import java.util.*;
class Th2
{
public static void main(String aa[])
{
Calendar c;
for(;;)
{
c = Calendar.getInstance(); // get the System Calendar
System.out.printf("%02d : %02d : %02d\n",
c.get(c.HOUR_OF_DAY),c.get(c.MINUTE),c.get(c.SECOND));
try{ Thread.sleep(1000); }catch(Exception ex){}
}
}
}
// to create the own Thread - without join method.
class MyThread extends Thread
{
MyThread(String s)
{
super(s); // Thread create s name
start(); // start the Thread
}
public void run() {
for(int i=1;i<=5;i++) {
System.out.println(getName()+" Thread here ");
try{ sleep(1000); }catch(Exception ex){}
}
}
}
class Th3
{
public static void main(String aa[])
{
MyThread t1 = new MyThread("Mayank");
MyThread t2 = new MyThread("Abhishek");
MyThread t3 = new MyThread("Ankit");
MyThread t4 = new MyThread("Abhay");
System.out.println("Main Thread exit.............");
}
}
OOPs with Java Lab file Page 12
// to create the own Thread - with join method.
// by using join() we can control the main Thread
class MyThread extends Thread
{
MyThread(String s)
{
super(s); // Thread create s name
start(); // start the Thread
}
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(getName()+" Thread here ");
try{ sleep(2000); }catch(Exception ex){}
}
}
}
class Th4
{
public static void main(String aa[])
{
MyThread t1 = new MyThread("Mayank");
MyThread t2 = new MyThread("Abhishek");
MyThread t3 = new MyThread("Ankit");
MyThread t4 = new MyThread("Abhay");
try {
t1.join();
t2.join();
t3.join();
t4.join();
}catch(Exception ex) {}
System.out.println("Main Thread exit.............");
}
}
OOPs with Java Lab file Page 13
PROGRAM #6
Create java program with the use of java packages.
it is a container that contain the class files, interfaces &
sub packages.
or
Java package is a mechanism of grouping similar type of
classes, interfaces, sub-classes & sub packages collectively
based on functionality.
or
it is a kind of folder that contain the class
files,interfaces & sub folders.
or
packages r like header files in C & C++ or like namespaces in
.Net & C++.
Adv / Need of packages - packages r used for implements the
modular approach -
* Java package removes naming collision.
* simplicity. - easy to use
* Reusability - design once & call/use any where.
* Performence Improve
* Error Handling & Debugging easy.
* team work & time management.
package abhay;
class Wel
{
public static void main(String aa[])
{
System.out.println("Welcome's U");
}
}
// javac -d . Wel.java
// java abhay.Wel
________________________________________________
package golu.singh; // nested / inner package / sub package
class Hello
{
public static void main(String aa[])
{
System.out.println("Welcome's U");
}
}
// javac -d . Hello.java
// java golu.singh.Hello
OOPs with Java Lab file Page 14
PROGRAM #7
Construct java program using java I/O package.
// to read own source code & write data in a file & display on
// console window
import java.io.*;
class F2
{
public static void main(String a[])
{
int x;
try {
// input mode
FileInputStream r = new FileInputStream("F1.java");
// open file in output mode true for append default is false
FileOutputStream w = new FileOutputStream("pranshu.txt",true);
while((x=r.read())!=-1) // while not eof
{
w.write(x);
Thread.sleep(10);
System.out.print((char)x);
}
w.close();
r.close();
}
catch(Exception ex) { System.out.println(ex); }
}
}
// with FileReader&FileWriter
import java.io.*;
class RW
{
public static void main(String a[])
{
int x;
try {
FileReader r = new FileReader("RW.java"); // input mode
FileWriter w = new FileWriter("Pranshu.txt"); // output mode
while((x=r.read())!=-1) // while not eof
{
w.write(x);
Thread.sleep(10);
System.out.print((char)x);
}
w.close();
}
catch(Exception ex) { System.out.println(ex); }
}
}
OOPs with Java Lab file Page 15
PROGRAM #8
Create industry oriented application using Spring Framework.
Steps for design the spring application –
1. Open the net bean -> design the web Application -> select
the spring checkbox also.
2. Now design the simple class with package like – my.Hello
3. Declare one or 2 variables -> like – String msg;
4. Now select the String msg; -> RC -> refactor ->
encapsulate fields -> design the getter + setter methods.
5. Now design the spring config file for bean entries.
6. File -> new -> spring xml config file -> name –
HelloXML.xml inside src/java folder (outside ur package)
define the bean entries –
<bean id="bean1" class="my.Hello">
<property name="msg" value="Hello Spring."/>
</bean>
Now design the simple java file file for spring Application
calling –
try
{
ApplicationContextctx = new
ClassPathXmlApplicationContext("Config.xml");
Hello n = (Hello)ctx.getBean("bean1");
System.out.println(n.getStr());
}
catch(Exception ex) { System.out.println(ex); }
Spring Example:-
1. create the class
2. create the xml file to provide the values
3. create the test class
4. Run the test class
OOPs with Java Lab file Page 16
// design the Bean class with Hello name
package my;
public class Hello {
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
private String str;
}
-- design the Config.xml file for bean config
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/bean
s http://www.springframework.org/schema/beans/spring-beans-
4.0.xsd">
<bean id="bean1" class="my.Hello">
<property name="str" value="Hello World."/>
</bean>
</beans>
// design java file for call/use the spring bean.
import my.Hello;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class Call1
{
public static void main(String[] args) {
try
{
ApplicationContextctx = new
ClassPathXmlApplicationContext("Config.xml");
/*
BeanFactory bean = new ClassPathXmlApplicationContext("Config.xml");
//Here Object are create on load by default singleton object are
created
Hello n = bean.getBean(Hello.class);
*/
Hello n = (Hello)ctx.getBean("bean1");
System.out.println(n.getStr());
}catch(Exception ex) { System.out.println(ex);}
}
}
OOPs with Java Lab file Page 17
PROGRAM #9
Test RESTful web services using Spring Boot.
package com.mvc.controller;
import java.util.List;
import com.mvc.dao.EmpDAO;
import com.mvc.model.EmpDetails;
@Controller
public class MyController
{
@Autowired
EmpDAOdao;
@RequestMapping("/wel")
@ResponseBody
public String wel()
{
return "Welcome to Spring Web Services, this is my 1st
Web Service.....";
}
@GetMapping("/wel1")
@ResponseBody
public String wel1()
{
return "Welcome to Spring Web Services, this is my 1st
Web Service with GetMapping Annotation.....";
}
@PostMapping(value="/Emp",produces= {"application/json"},
consumes= {"application/json"})
@ResponseBody
public EmpDetailssave(@RequestBody EmpDetails emp)
{
System.out.println(emp);
return emp;
}
@PostMapping(value="/EmpAction", consumes=
{"application/json"})
@ResponseBody
public String saveEmp(@RequestBody EmpDetails emp)
{
String msg = dao.addEmp(emp);
System.out.println(emp);
return msg;
}
OOPs with Java Lab file Page 18
@GetMapping(value="/EmpReport", produces=
{"application/json"})
@ResponseBody
public List<EmpDetails>EmpReport()
{
return dao.getEmpReport();
}
}
OOPs with Java Lab file Page 19