OOPS With Java BCS452 Lab File
OOPS With Java BCS452 Lab File
1. Use Java compiler and eclipse pla琀昀orm to write and execute java program.
2. Crea琀椀ng simple java programs using command line arguments
3. Understand OOP concepts and basics of Java programming.
4. Create Java programs using inheritance and polymorphism.
5. Implement error-handling techniques using excep琀椀on handling and mul琀椀threading.
6. Create java program with the use of java packages.
7. Construct java program using Java I/O package.
8. Create industry oriented applica琀椀on using Spring Framework.
9. Test RESTful web services using Spring Boot.
10. Test Frontend web applica琀椀on with Spring Boot
LAB PLAN
Object oriented with Java Programming Lab(BCS 452)
S.No. Contents Experiments Lab Turn
COURSE OBJECTIVES:
COURSE OUTCOMES:
Able to write programs for solving real world problems using java collec琀椀on
frame work.
Able to write programs using abstract classes.
Able to write mul琀椀threaded programs.
Able to write GUI programs using swing controls in Java.
Lab Turn1
Java Basic.
1. Write a Program to print the text “Welcome to World of Java”. Save it with name Welcome.java
in your folder.
Class Welcome
{
public static void main (String args[])
{
System.out.println (“welcome to world of Java”);
}
}
2. Write a Program to print the area of triangle. Save it with name Area.java in your folder.
class Area
{
public static void main(String args[])
{
int height =10, base=6; float
area=0.5F*base* height;
System.out.println(“area of triangle = ”+area);
}
}
class FibonacciExample1{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1
Import java.util.Scanner;
class Ladder
{
public static void main(String arr[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of rows");
int a=in.nextInt();
for(int i=1;i<=a;i++)
{
for(int j=1;j<=i;j++)
System.out.print(j);
for(int k=i-1;k>=1;k--)
System.out.print(k);
System.out.print("\n");
}
}
}
6. Write a java Program to Convert any decimal number into its binary equivalent
{
int decimal = 10;
String binary = decimalToBinary(decimal);
System.out.println("Decimal: " + decimal);
System.out.println("Binary: " + binary);
}
public static String decimalToBinary(int n)
{
int remainder, quotient = n;
String binaryNum = "";
while (quotient > 0) {
remainder = quotient % 2;
binaryNum
= Integer.toString(remainder) + binaryNum;
quotient = quotient / 2;
}
return binaryNum;
}
}
Lab Turn 2
Program based on the concepts of classes and objects, constructor, parameterized constructor
10
7. Write a program to create a class Student with data ‘name, city and age’ along with method
printData to display the data. Create the two objects s1 ,s2 to declare and access the values.
class Student
{
String name, city; int age;
Static int m;
Void printData()
{
System.out.println("Student name = "+name);
System.out.println("Student city = "+city);
System.out.println("Student age = "+age);
}
}
Class Stest
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.name="Amit";
s1.city="Dehradun";
s1.age=22;
s2.name="Kapil";
s2.city="Delhi";
s2.age=23;
s2.printData();
s1.printData();
s1.m=20;
s2.m=22;
Student.m=27;
System.out.println("s1.m = "+s1.m);
System.out.println("s2.m = "+s2.m);
System.out.println("Student.m ="+Student.m);
}
}
8. Write a program to create a class Student2 along with two method getData(),printData() to get
the value through argument and display the data in printData. Create the two objects s1 ,s2 to
declare and access the values from class STtest.
class Student2
{
private String name, city;
private int age;
public void getData(String x, Stringy, int t)
{
name=x;
city=y;
11
age=t;
}
public void printData()
{
System.out.println("Student name ="+name);
System.out.println("Student city ="+city);
System.out.println("Student age ="+age);
}
}
Class STtest
{
public static void main(String args[])
{
Student2 s1=new Student2();
Student2 s2=new Student2();
s2.getData("Kapil","Delhi",23);
s2.printData();
s1.getData("Amit","Dehradun",22);
s1.printData();
}
}
9. WAP using parameterized constructor with two parameters id and name. While creating the
objects obj1 and obj2 passed two arguments so that this constructor gets invoked after creation of
obj1 and obj2.
class Employee
{
int empId;
String empName; //parameterized constructor with two parameters
Employee(int id, String name)
{
this.empId = id;
this.empName = name;
}
void info()
{
System.out.println("Id: "+empId+" Name: "+empName);
}
public static void main(String args[])
{
Employee obj1 = new Employee(10245,"Chaitanya");
Employee obj2 = new Employee(92232,"Negan");
obj1.info();
obj2.info();
}}
Lab Turn 3
Method overloading, constructor overloading, Abstract Class and Interface
12
10. Write a program in JAVA to demonstrate the method and constructor overloading.
class Cs
{
Int p,q;
public Cs()
{}
public Cs(int x, int y)
{
p=x; q=y;
}
Public int add(int i, int j)
{
return (i+j);
}
Public int add(int i, int j, int k)
{
return (i+j+k);
}
public float add(float f1, float f2)
{
return (f1+f2);
}
public void printData()
{
System.out.print("p = "+p);
System.out.println(" q = "+q);
}
}
Class ConstructorOverlaoding
{
public static void main(String args[])
{
int x=2, y=3, z=4;
Cs c=new Cs();
Cs c1=new Cs(x, z );
c1.printData();
float m=7.2F, n=5.2F;
int k=c.add(x,y);
int t=c.add(x,y,z);
float ft=c.add(m, n);
System.out.println("k = "+k);
System.out.println("t = "+t);
System.out.println("ft = "+ft);
}
}
11. Write a program in JAVA to create a class Bird also declares the different parameterized constructor
to display the name of Birds.
13
class Bird
{
int age;
String name ;
Bird()
{
System.out.println("this is the perrot");
}
Bird(String x)
{
name=x;
System.out.println("this is the "+name);
}
Bird(int y,String z)
{
age=y;
name=z;
System.out.println("this is the "+age+"years\t"+name);
}
12. Write a program in java to generate an abstract class A also class B inherits the class A.
generate the object for class B and display the text “call me from B”.
abstract class A
{
abstract void call();
}
class B extends A
{
public void call()
{
System.out.println("call me from B");
}
public static void main(String arr[])
{
B b=new B();
b.call();
}
}
14
13. Write a java program in which you will declare two interface sum and Add inherits these
interface through class A1 and display their content.
interface sum
{
Int sm=90;
Void suma();
}
Interface add
{
int ad=89;
voidadda();
}
Lab Turn 4
Single level & Multi level inheritance , Method Overriding
15
importjava.util.*;
importjava.lang.*;
importjava.io.*;
class one
{
Public void print_geek()
{
System.out.println("Geeks");
}
}
Class two extends one
{
Public void print_for()
{
System.out.println("for");
}
}
// Driver class
Public class Main {
Public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Import java.util.*;
Import java.lang.*;
Import java.io.*;
Class one
{
Public void print_geek()
{
System.out.println("Geeks");
}
}
Class two extends one
{
Public void print_for()
{
System.out.println("for");
}
}
16
Class Parent
{
Void show()
{
System.out.println("Parent's show()");
}
// Driver class
Class Main
{
Public static void main(String[] args)
{
// If a Parent type reference refers // to a Parent object, then Parent's // show is called
Class Vehicle
{
Int maxSpeed = 120;
}
/* sub class Car extending vehicle */ 20
Class Car extends Vehicle
{ int maxSpeed = 180;
Void display()
{ /* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: "+ super.maxSpeed);
}
}
/* Driver program to test */
classTest
{
Public static void main(String[] args)
{
Car small = newCar();
small.display();
}
}
Lab Turn 5
Array and String
18
// Driver Class
class Test
{
// array declared
static int arr[] = {10, 324, 45, 90, 9808};
return max;
}
// Driver method
public static void main(String[] args)
{
System.out.println("Largest in given array is " + largest());
}
}
19. implementation of the sort() function across different scenarios of the Arrays class
import java.util.Arrays;
class GFG {
public static void main(String args[])
{
int[] arr = { 5, -2, 23, 7, 87, -42, 509 };
System.out.println("The original array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
Arrays.sort(arr);
System.out.println("\nThe sorted array is: ");
for (int num : arr) {
System.out.print(num + " ");
19
}
}
}
20.// Java program for addition of two matrices
import java.io.*;
class GFG {
System.out.println();
}
}
return C;
}
// Driver code
public static void main(String[] args)
{
int size = 4;
int A[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
// Print the matrices A
System.out.println("\nMatrix A:");
printMatrix(A, size, size);
20
int B[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
// Print the matrices B
System.out.println("\nMatrix B:");
printMatrix(B, size, size);
import java.io.*;
import java.util.Scanner;
class GFG {
public static void main (String[] args) {
Lab Turn 6
Exception handling & Packages
21
22.Write a program in java if number is less than 10 and greater than 50 it generate the
exception out of range. Else it displays the square of number
Class CustomTest
{
public static void main(String arr[])
{
try
{
int a=Integer.parseInt(arr[0]);
if(a50) throw(new outofRangeException("valid range is 10 to 50"));
{
int s=a*a;
System.out.println("Square is:"+s);
}
}catch(Exception ex)
{
System.out.println(ex);
} } }
23 Write a program in java to enter the number through command line argument if first and
second number is not entered it will generate the exception. Also divide the first number with
second number and generate the arithmetic exception.
class Divide2
{
public static void main(String arr[])
{
try
{
if(arr.length<2)
}
catch(Exception e)
{
System.out.println(e);
}
}}
//save by A.java
package pack;
public class A{
//save by B.java
package mypack;
import pack.*;
class B
obj.msg();
//save by A.java
package pack;
23
public class A{
public void msg()
{
System.out.println("Hello");}
}
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
} }
Output: Hello
Lab Turn7
Multithreading
24
26 Write a java program in which thread sleep for 5 sec and change the name of
thread.
Import java.lang.*;
Class ThreadTest extends Thread
{
static
{
Thread t = Thread.currentThread();
//Thread t=new Thread.currentThread();
System.out.println("thread test is loaded by"+t.getName()
+"thread"); t.setName("vishal");
System.out.println("changed the name
of thread");
System.out.println("suspending thread
for 5 sec"); try
{
Thread.sleep(5000);
}
catch(Exception ex){}
}
public static void main(String arr[])
{
Thread t=Thread.currentThread();
System.out.println("main() is invoked in"+t.getName()+"thread...");
}
}
27. Write a java program for multithread in which user thread and thread started from main
method invoked at a time each thread sleep for 1 sec.
28 Write a java program for to solve producer consumer problem in which a producer produce
a value and consumer consume the value before producer generate the next value.
class Buffer
{
int value;
boolean produced=false;
public synchronized void produce(int x)
{
if(produced)
{
System.out.println("producer enter monitor out of turn..suspend. ");
try
{
wait();
}catch(Exception e)
{}
}
value=x;
System.out.println(value+"is
produced"); produced=true;
notify();
}
public synchronized void consume()
{
if(! produced)
{
System.out.println("consumer enterd the monitor out of turn,suspend.................");
try
{
wait();
}
catch(Exception e)
26
{ }
}
System.out.println(value+"is consumed");
produced=false;
notify();
}
}
class Producer extends Thread
{
Buffer buffer;
public Producer(Buffer b)
{
buffer =b;
}
Public void run()
{
{
System.out.println("producer started ,producing value.....................");
for(int i=1;1<=10;i++)
buffer.produce(i);
}
}
27
Lab Turn 8
try
System.out.println("usage:javacreate昀椀le 昀椀le name");
System.exit(0);
}
{
Bu昀昀eredReader b=new Bu昀昀eredReader(new
InputStreamReader(System.in));
PrintStreamfos=new PrintStream(new
FileOutputStream(arr[0])); System.out.println("Enter text end
to save");
PrintStream
temp=System.out;
System.setOut(fos);
do
{
String str=b.readLine();
if(str.equalsIgnoreCase("e
nd"));
System.out.pri
ntln(str);
brea
k;
}while(true);
System.setOut(te
mp);
fos.close();
b.close();
System.out.println("successfully created");
28
}
catch(Excep琀椀on ex)
{
System.out.println(ex);
}
}
}
on screen.
import java.io.*;
class input
{
public sta琀椀c void main(String arr[])
{
try
{
FileInputStreamf is=new FileInputStream("J.text");
int a=昀椀s.read();
System.out.println(a);
}
catch(IOExcep琀椀on e)
{
}
}
}
Lab Turn 9
Collection in Java
31 .Write a java program to create an array list collec琀椀on.
29
import java.u琀椀l.*;
class TestJavaCollec琀椀on1{
public sta琀椀c void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Crea琀椀ng arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
import java.u琀椀l.*;
30
class TestCollec琀椀on12{
public sta琀椀c void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("itera琀椀ng the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("a昀琀er removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
34 .Write a java program to create an Hash set collec琀椀on
import java.u琀椀l.*;
class HashSet1{
public sta琀椀c void main(String args[]){
//Crea琀椀ng HashSet and adding elements
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
import java.u琀椀l.*;
class TreeSet1{
public sta琀椀c void main(String args[]){
31
32
Lab Turn 10
Spring Framework
37 .Implement a spring framework based project en琀椀tled “ Health and Fitness App”
<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
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javatpoint</groupId>
<artifactId>SpringMVC</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringMVC Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
33
<version>3.0-alpha-1</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMVC</finalName>
</build>
</project>
@Controller
public class HelloGeek {
@RequestMapping("/")
public String display()
{
return "hello";
}
}
Step 3: Provide the name of the controller in the web.xml file as follows:
DispatcherServlet is the front controller in Spring Web MVC. Incoming requests for the
HTML file are forwarded to the DispatcherServlet.
web.xml
XML
Step 4: We have to define the bean in a separate XML file. We have specified the view
components in this file. It is located in the WEB-INF directory.
34
spring-servlet.xml
XML
</beans>
<html>
<body>
</body>
</html>
Step 6: Start the server and run the project. The output is displayed as follows:
Spring MVC Tutorial!!
35
package com.example.actuatorservice;
}
Now that you need to create the endpoint controller that will serve the representa琀椀on class.
package com.example.actuatorservice;
import java.u琀椀l.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annota琀椀on.GetMapping;
import org.springframework.web.bind.annota琀椀on.RequestParam;
import org.springframework.web.bind.annota琀椀on.ResponseBody;
@Controller
public class HelloWorldController {
@GetMapping("/hello-world")
@ResponseBody
36
}
The key di昀昀erence between a human-facing controller and a REST endpoint controller is in how the
response is created. Rather than rely on a view (such as JSP) to render model data in HTML, an
endpoint controller returns the data to be wri琀琀en directly to the body of the response.
The @ResponseBody annota琀椀on tells Spring MVC not to render a model into a view but, rather, to
write the returned object into the response body. It does so by using one of Spring’s message
converters. Because Jackson 2 is in the classpath, MappingJackson2H琀琀pMessageConverter will
handle the conversion of a Gree琀椀ng object to JSON if the request’s Accept header speci昀椀es that
JSON should be returned.
How do you know Jackson 2 is on the classpath? Either run mvn dependency:tree or ./gradlew
dependencies, and you get a detailed tree of dependencies that includes Jackson 2.x. You can also
see that it comes from /spring-boot-starter-json, itself imported by spring-boot-starter-web.
Run the Applica琀椀on
You can run the applica琀椀on from a custom main class or directly from one of the con昀椀gura琀椀on
classes. For this simple example, you can use the SpringApplica琀椀on helper class. Note that this is the
applica琀椀on class that the Spring Ini琀椀alizr created for you, and you need not even modify it for it to
work for this simple applica琀椀on. The following lis琀椀ng (from
src/main/java/com/example/actuatorservice/HelloWorldApplica琀椀on.java) shows the applica琀椀on
class:
package com.example.actuatorservice;
import org.springframework.boot.SpringApplica琀椀on;
import org.springframework.boot.autocon昀椀gure.SpringBootApplica琀椀on;
@SpringBootApplica琀椀on
public class HelloWorldApplica琀椀on {
}
In a conven琀椀onal Spring MVC applica琀椀on, you would add @EnableWebMvc to turn on key
behaviors, including con昀椀gura琀椀on of a DispatcherServlet. But Spring Boot turns on this annota琀椀on
automa琀椀cally when it detects spring-webmvc on your classpath. This sets you up to build a
controller in an upcoming step.
You can run the applica琀椀on from the command line with Gradle or Maven. You can also build a
single executable JAR 昀椀le that contains all the necessary dependencies, classes, and resources and
run that. Building an executable jar makes it easy to ship, version, and deploy the service as an
applica琀椀on throughout the development lifecycle, across di昀昀erent environments, and so forth.
If you use Gradle, you can run the applica琀椀on by using ./gradlew bootRun. Alterna琀椀vely, you can
build the JAR 昀椀le by using ./gradlew build and then run the JAR 昀椀le, as follows:
$ curl localhost:8080/hello-world
{"id":1,"content":"Hello, Stranger!"}
Switch to a Di昀昀erent Server Port
Spring Boot Actuator defaults to running on port 8080. By adding an applica琀椀on.proper琀椀es 昀椀le, you
can override that se琀�ng. The following lis琀椀ng (from
src/main/resources/applica琀椀on.proper琀椀es)shows that 昀椀le with the necessary changes:
server.port: 9000
management.server.port: 9001
management.server.address: 127.0.0.1
Run the server again by running the following command in a terminal:
You can test that it is working on port 9000 by running the following commands in a terminal:
$ curl localhost:8080/hello-world
curl: (52) Empty reply from server
$ curl localhost:9000/hello-world
{"id":1,"content":"Hello, Stranger!"}
$ curl localhost:9001/actuator/health
{"status":"UP"}
Test Your Applica琀椀on
To check whether your applica琀椀on works, you should write unit and integra琀椀on tests for your
applica琀椀on. The test class in
src/test/java/com/example/actuatorservice/HelloWorldApplica琀椀onTests.java ensures that
Note that the tests start the applica琀椀on on a random port. The following lis琀椀ng shows the test class:
38
/*
package com.example.actuatorservice;
import java.u琀椀l.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annota琀椀on.Autowired;
import org.springframework.beans.factory.annota琀椀on.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.h琀琀p.H琀琀pStatus;
import org.springframework.h琀琀p.ResponseEn琀椀ty;
import org.springframework.test.context.TestPropertySource;
/**
* Basic integra琀椀on tests for service demo applica琀椀on.
*
* @author Dave Syer
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(proper琀椀es = {"management.port=0"})
public class HelloWorldApplica琀椀onTests {
@LocalServerPort
private int port;
@Value("${local.management.port}")
private int mgt;
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void shouldReturn200WhenSendingRequestToController() throws Excep琀椀on {
@SuppressWarnings("rawtypes")
ResponseEn琀椀ty<Map> en琀椀ty = this.testRestTemplate.getForEn琀椀ty(
"h琀琀p://localhost:" + this.port + "/hello-world", Map.class);
then(en琀椀ty.getStatusCode()).isEqualTo(H琀琀pStatus.OK);
}
@Test
public void shouldReturn200WhenSendingRequestToManagementEndpoint() throws Excep琀椀on {
39
@SuppressWarnings("rawtypes")
ResponseEn琀椀ty<Map> en琀椀ty = this.testRestTemplate.getForEn琀椀ty(
"h琀琀p://localhost:" + this.mgt + "/actuator", Map.class);
then(en琀椀ty.getStatusCode()).isEqualTo(H琀琀pStatus.OK);
}
40