lOMoARcPSD|49223878
JAVA Lab Manual
[Link] (Dr. A.P.J. Abdul Kalam Technical University)
Scan to open on Studocu
Studocu is not sponsored or endorsed by any college or university
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
ABES Ins琀椀tute of Technology
Ghaziabad
A昀케liated to Dr. A.P.J. AKTU, Lucknow
LAB MANUAL
Department of Computer Science & Engineering
Subject Name: Object Oriented Programming with Java Lab
Subject Code: BCS452
Session: 2023-24
Semester: 4th
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
To be leading ins琀椀tu琀椀on in technical educa琀椀on providing educa琀椀on and
Ins琀椀tute Vision training enabling human resource to serve na琀椀on and world at par with
global standards in educa琀椀on
1)Developing state of art infrastructure which also includes establishment
of centre of excellence in pursuit of academic and technical excellence
Ins琀椀tute Mission 2)Valuing work force inculca琀椀ng belongingness and professional integrity
3)To develop human resource to solve local, regional and global problems
to make technology relevant to those who mean it most
To provide excellence by impar琀椀ng knowledge to the learners
Department Vision
enabling them to become skilled professionals to be recognized as
a responsible ci琀椀zen.
1) Provide quality educa琀椀on in the 昀椀eld of computer science and
engineering through experienced and quali昀椀ed faculty members.
2) Mo琀椀vate learners for higher studies and research oriented ac琀椀vi琀椀es
Department
Mission by u琀椀lizing resources of Centers of Excellence.
3) Inculcate societal values, professional ethics, team work, and
leadership quali琀椀es by having exposure at Na琀椀onal and
Interna琀椀onal level ac琀椀vi琀椀es.
Program Educa琀椀onal Objec琀椀ves (PEOs)
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
Graduates of the program are expected to be employed in IT industry or
PEO1
indulge in higher studies and research.
Graduates of the program are expected to exhibit curiosity to learn new technologies and
PEO2
work with ethical values and team work.
Graduates of the program are expected to design and develop innova琀椀ve solu琀椀ons related
PEO3
to real world problems of the society.
Program Outcomes (PSOs)
Solve complex problems using data structures and other advanced suitable algorithms.
PSO 1
Interpret fundamental concepts of computer systems and understand its hardware and
PSO 2
so昀琀ware aspect.
Analyze the constraints of the exis琀椀ng data base management systems and get experience on
PSO 3
large-scale analy琀椀cal methods in the evolving technologies.
Develop intelligent systems and implement solu琀椀ons to cater the business speci昀椀c
PSO 4
requirements.
PO1 Engineering knowledge
PO2 Problem analysis
PO3 Design/development of solu琀椀ons
PO4 Conduct inves琀椀ga琀椀ons of complex problems
PO5 Modern tool usage
PO6 The engineer and society
PO7 Environment and sustainability
PO8 Ethics
PO9 Individual and team work
PO10 Communica琀椀on
PO11 Project management and 昀椀nance
PO12 Life-long learning
Program Speci昀椀c Outcomes (POs)
Course – [Link]
Course Outcomes (COs)
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
Academic Year Class/Semester Course Name Course Code
2023-24 4th Object Oriented BCS-452
Programming with
Java Lab
A昀琀er the successful comple琀椀on of the course students will be able:
CO1 Understand the basics of object-oriented programming using JAVA..
Apply the concept of classes, Java, JDK Components and develop Simple Java Programs.
CO2
CO3 Develop Simple Java Programs using inheritance and Excep琀椀on handling ,Mul琀椀threading.
Demonstrate the concept of Collec琀椀ons, Comparators and Interfaces.
CO4
CO5 Interpret the need for advanced Java concepts like spring, Auto Boxing and annota琀椀ons.
_____________
( Name &Signature)
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
BCS452- Object Oriented Programming with Java
List of Experiments (Indica琀椀ve & not limited to)
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
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
LAB PLAN
Object oriented with Java Programming Lab(BCS 452)
[Link]. Contents Experiments Lab Turn
1 Simple print the text “Welcome”
Programs print the area of triangle
without classes check the number is Prime or not Turn-01
program to display Fibonacci series
and objects,
Program to generate a Ladder of numbers
methods
Program to 昀椀nd the binary of decimal
number
2 Program based on Object instan琀椀a琀椀on
the concepts of Constructors
classes and Methods (de昀椀ning & Calling)
Types of constructor Turn-02
objects,
Parameter passing to methods
constructor,
parameterized
constructor
3 Method Method overloading
overloading, Constructor overloading Turn-03
constructor Abstract classes
overloading Interfaces
4 Single level Inheritance
Single level & Mul琀椀ple inheritance
Mul琀椀 level Super
inheritance Turn-04
Order of Constructor calling
Method overriding
Final keyword
5 Array and String Simple programs using
Array and String Turn-05
6 Excep琀椀on handling Excep琀椀on handling through-
& Packages Try ,Catch ,Throw
Turn-06
Finally
Making own package
7 Mul琀椀threading Simple programs of mul琀椀threading
Thread Synchroniza琀椀on Turn-07
8 I/O& File Input from user
Handling Crea琀椀on of 昀椀le Turn-8
Reading data from 昀椀le
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
Wri琀椀ng data in to 昀椀le
9 Collec琀椀ons Array List
Stack
Turn-9
Queue
Hash Set
Tree Set
10 Spring Create industry oriented applica琀椀on
Framework Test RESTful & Frontend web applica琀椀on Turn-10
with Spring Boot
Content Beyond Syllabus
11 AWT Design a Student Registra琀椀on Form using
Component di昀昀erent AWT Component Turn -11
12 JDBC Show the Data Base Connec琀椀vity of AWT
Connec琀椀vity components and sql Server Turn -12
COURSE OBJECTIVES:
To write programs using abstract classes.
To write programs for solving real world problems using java collec琀椀on frame
work.
To write mul琀椀threaded programs.
To write GUI programs using swing controls in Java.
To introduce java compiler and eclipse pla琀昀orm.
To impart hands on experience with java programming.
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.
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
1. Write a Program to print the text “Welcome to World of Java”. Save it with name [Link]
in your folder.
Class Welcome
{
public static void main (String args[])
{
[Link] (“welcome to world of Java”);
}
}
2. Write a Program to print the area of triangle. Save it with name [Link] in your folder.
class Area
{
public static void main(String args[])
{
int height =10, base=6; float
area=0.5F*base* height;
[Link](“area of triangle = ”+area);
}
}
3. Write a java Program to check the number is Prime or not.
Import java. util. Scanner;
class Prime
{
public static void main(String arr[])
{
int c;
Scanner in=new Scanner([Link]);
[Link]("Enter the number to be tested for prime ");
int n=[Link]();
for ( c = 2 ; c <= n - 1 ; c++ )
{
if ( n%c == 0 )
{
[Link](n+">>>>> not prime");
break;
} }
if ( c == n )
[Link](n+ ">>>>Number is prime.");
}
4. Write a java Program to generate a Fibonacci Series
8
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
class FibonacciExample1{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
[Link](n1+" "+n2);//printing 0 and 1
for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
[Link](" "+n3);
n1=n2;
n2=n3;
} } }
5. Write a java Program to generate a Ladder of number.
Import [Link];
class Ladder
{
public static void main(String arr[])
{
Scanner in=new Scanner([Link]);
[Link]("Enter the number of rows");
int a=[Link]();
for(int i=1;i<=a;i++)
{
for(int j=1;j<=i;j++)
[Link](j);
for(int k=i-1;k>=1;k--)
[Link](k);
[Link]("\n");
}
}
}
6. Write a java Program to Convert any decimal number into its binary equivalent
public class Convert
{
public static void main(String[] args)
9
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
{
int decimal = 10;
String binary = decimalToBinary(decimal);
[Link]("Decimal: " + decimal);
[Link]("Binary: " + binary);
}
public static String decimalToBinary(int n)
{
int remainder, quotient = n;
String binaryNum = "";
while (quotient > 0) {
remainder = quotient % 2;
binaryNum
= [Link](remainder) + binaryNum;
quotient = quotient / 2;
}
return binaryNum;
}
}
Lab Turn 2
Program based on the concepts of classes and objects, constructor, parameterized constructor
10
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
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()
{
[Link]("Student name = "+name);
[Link]("Student city = "+city);
[Link]("Student age = "+age);
}
}
Class Stest
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
[Link]="Amit";
[Link]="Dehradun";
[Link]=22;
[Link]="Kapil";
[Link]="Delhi";
[Link]=23;
[Link]();
[Link]();
s1.m=20;
s2.m=22;
Student.m=27;
[Link]("s1.m = "+s1.m);
[Link]("s2.m = "+s2.m);
[Link]("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
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
age=t;
}
public void printData()
{
[Link]("Student name ="+name);
[Link]("Student city ="+city);
[Link]("Student age ="+age);
}
}
Class STtest
{
public static void main(String args[])
{
Student2 s1=new Student2();
Student2 s2=new Student2();
[Link]("Kapil","Delhi",23);
[Link]();
[Link]("Amit","Dehradun",22);
[Link]();
}
}
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)
{
[Link] = id;
[Link] = name;
}
void info()
{
[Link]("Id: "+empId+" Name: "+empName);
}
public static void main(String args[])
{
Employee obj1 = new Employee(10245,"Chaitanya");
Employee obj2 = new Employee(92232,"Negan");
[Link]();
[Link]();
}}
Lab Turn 3
Method overloading, constructor overloading, Abstract Class and Interface
12
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
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()
{
[Link]("p = "+p);
[Link](" 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 );
[Link]();
float m=7.2F, n=5.2F;
int k=[Link](x,y);
int t=[Link](x,y,z);
float ft=[Link](m, n);
[Link]("k = "+k);
[Link]("t = "+t);
[Link]("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
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
class Bird
{
int age;
String name ;
Bird()
{
[Link]("this is the perrot");
}
Bird(String x)
{
name=x;
[Link]("this is the "+name);
}
Bird(int y,String z)
{
age=y;
name=z;
[Link]("this is the "+age+"years\t"+name);
}
public static void main(String arr[])
{
Bird a=new Bird();
[Link]();
Bird b=new Bird("maina");
Bird c=new Bird(20,"sparrow");
}
}
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()
{
[Link]("call me from B");
}
public static void main(String arr[])
{
B b=new B();
[Link]();
}
}
14
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
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();
}
class A1 implements add ,sum
{
public void suma()
{
[Link](+sm);
}
public void adda()
{
[Link](+ad);
}
public static void main(String arr[])
{
A1 n= new A1();
[Link]();
[Link]();
}
}
Lab Turn 4
Single level & Multi level inheritance , Method Overriding
15
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
14. Java program to illustrate the concept of single inheritance
[Link].*;
[Link].*;
[Link].*;
class one
{
Public void print_geek()
{
[Link]("Geeks");
}
}
Class two extends one
{
Public void print_for()
{
[Link]("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();
}
}
15.// Java program to illustrate the concept of Multilevel inheritance
Import [Link].*;
Import [Link].*;
Import [Link].*;
Class one
{
Public void print_geek()
{
[Link]("Geeks");
}
}
Class two extends one
{
Public void print_for()
{
[Link]("for");
}
}
16
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
Class three extends two
{
Public void print_geek()
{
[Link]("Geeks");
}
}
// Drived class
Public classMain
{
Public static void main(String[] args)
{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}
16// A Simple Java program to demonstrate method overriding in java
Class Parent
{
Void show()
{
[Link]("Parent's show()");
}
Class Child extends Parent
{ // This method overrides show() of Parent @Override
Void show()
{
[Link]("Child'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
Parent obj1 = new Parent();
[Link]();
// If a Parent type reference refers // to a Child object Child's show()
17
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
// is called. This is called RUN TIME // POLYMORPHISM.
Parent obj2 = new Child();
[Link]();
}
}
17 Super Keyword in Java Use of super with variables
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) */
[Link]("Maximum Speed: "+ [Link]);
}
}
/* Driver program to test */
classTest
{
Public static void main(String[] args)
{
Car small = newCar();
[Link]();
}
}
Lab Turn 5
Array and String
18
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
[Link] a Java Program to to find maximum in arr[]
// Driver Class
class Test
{
// array declared
static int arr[] = {10, 324, 45, 90, 9808};
// Method to find maximum in arr[]
static int largest()
{
int i;
// Initialize maximum element
int max = arr[0];
// Traverse array elements from second and
// compare every element with current max
for (i = 1; i < [Link]; i++)
if (arr[i] > max)
max = arr[i];
return max;
}
// Driver method
public static void main(String[] args)
{
[Link]("Largest in given array is " + largest());
}
}
19. implementation of the sort() function across different scenarios of the Arrays class
import [Link];
class GFG {
public static void main(String args[])
{
int[] arr = { 5, -2, 23, 7, 87, -42, 509 };
[Link]("The original array is: ");
for (int num : arr) {
[Link](num + " ");
}
[Link](arr);
[Link]("\nThe sorted array is: ");
for (int num : arr) {
[Link](num + " ");
19
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
}
}
}
20.// Java program for addition of two matrices
import [Link].*;
class GFG {
// Function to print Matrix
static void printMatrix(int M[][],
int rowSize,
int colSize)
{
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++)
[Link](M[i][j] + " ");
[Link]();
}
}
// Function to add the two matrices
// and store in matrix C
static int[][] add(int A[][], int B[][],
int size)
{
int i, j;
int C[][] = new int[size][size];
for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
C[i][j] = A[i][j] + B[i][j];
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
[Link]("\nMatrix A:");
printMatrix(A, size, size);
20
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
int B[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
// Print the matrices B
[Link]("\nMatrix B:");
printMatrix(B, size, size);
// Add the two matrices
int C[][] = add(A, B, size);
// Print the result
[Link]("\nResultant Matrix:");
printMatrix(C, size, size);
}
}
21./ java program to reverse a word
import [Link].*;
import [Link];
class GFG {
public static void main (String[] args) {
String str= "Geeks", nstr="";
char ch;
[Link]("Original word: ");
[Link]("Geeks"); //Example word
for (int i=0; i<[Link](); i++)
{
ch= [Link](i); //extracts each character
nstr= ch+nstr; //adds each character in front of the existing string
}
[Link]("Reversed word: "+ nstr);
}
}
Lab Turn 6
Exception handling & Packages
21
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
[Link] 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=[Link](arr[0]);
if(a50) throw(new outofRangeException("valid range is 10 to 50"));
{
int s=a*a;
[Link]("Square is:"+s);
}
}catch(Exception ex)
{
[Link](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([Link]<2)
throw(new Exception("two argument must be provided"));
int a= [Link](arr[0]);
int
b=[Link](arr[1])
;
if(b==0)
throw(new Exception("second argument should be non zero"));
int c=a/b;
[Link]("result:"+c);
22
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
}
catch(Exception e)
{
[Link](e);
}
}}
24. Example of package that import the packagename.*
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
//save by [Link]
package mypack;
import pack.*;
class B
public static void main(String args[])
A obj = new A();
[Link]();
25. Example of package by import fully qualified name
//save by [Link]
package pack;
23
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
public class A{
public void msg()
{
[Link]("Hello");}
}
//save by [Link]
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
[Link]();
} }
Output: Hello
Lab Turn7
Multithreading
24
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
26 Write a java program in which thread sleep for 5 sec and change the name of
thread.
Import [Link].*;
Class ThreadTest extends Thread
{
static
{
Thread t = [Link]();
//Thread t=new [Link]();
[Link]("thread test is loaded by"+[Link]()
+"thread"); [Link]("vishal");
[Link]("changed the name
of thread");
[Link]("suspending thread
for 5 sec"); try
{
[Link](5000);
}
catch(Exception ex){}
}
public static void main(String arr[])
{
Thread t=[Link]();
[Link]("main() is invoked in"+[Link]()+"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.
Class UserThread extends Thread
{
public void run()
{
Thread t=[Link]();
[Link]("run() is invoked in"+[Link]()
+"thread..."); for(int i=1;i<=10;i++)
{
[Link]("run:"+i);
try
{
[Link](1000);
}
catch(Exception e)
{ }
}
[Link]("run() is completed");
}
}
classMultiThread
{
25
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
public static void main(String arr[])
{
[Link]("main() started creating an object of user Thread. ");
UserThread t=new UserThread();
[Link]("directly invoking run() of
user thread"); [Link]();
[Link]("control back in main() ");
[Link]("launching new thread for run() of user thread. ");
[Link]();
for(int i=10;i>0;i--)
{
[Link]("
main:"+i); try
{
[Link](1000);
}
catch(Exception e){}
}[Link]("main() completed");
}}
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)
{
[Link]("producer enter monitor out of turn..suspend. ");
try
{
wait();
}catch(Exception e)
{}
}
value=x;
[Link](value+"is
produced"); produced=true;
notify();
}
public synchronized void consume()
{
if(! produced)
{
[Link]("consumer enterd the monitor out of turn,suspend.................");
try
{
wait();
}
catch(Exception e)
26
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
{ }
}
[Link](value+"is consumed");
produced=false;
notify();
}
}
class Producer extends Thread
{
Buffer buffer;
public Producer(Buffer b)
{
buffer =b;
}
Public void run()
{
{
[Link]("producer started ,producing value.....................");
for(int i=1;1<=10;i++)
[Link](i);
}
}
class Consumer extends Thread
{
Buffer buffer;
public Consumer(Buffer b)
{
buffer =b;
}
public void run()
{
[Link]("consumer started,consuming value.................");
for(int i=1;i<=10;i+
+) [Link]();
}
}
class PC1
{
public static void main(String arr[])
{
Buffer b=new Buffer();
Producer p=new Producer(b);
Consumer c=new Consumer(b);
[Link]();
[Link]();
}
}
27
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
Lab Turn 8
I/O and File Handling
29 .Write a java program to create a 昀椀le and write the text in it and
save the 昀椀le. import [Link].*;
Class CreateFile
{
public sta琀椀c void main(String arr[])
{
if([Link]<1)
{
try
[Link]("usage:javacreate昀椀le 昀椀le name");
[Link](0);
}
{
Bu昀昀eredReader b=new Bu昀昀eredReader(new
InputStreamReader([Link]));
PrintStreamfos=new PrintStream(new
FileOutputStream(arr[0])); [Link]("Enter text end
to save");
PrintStream
temp=[Link];
[Link](fos);
do
{
String str=[Link]();
if([Link]("e
nd"));
[Link]
ntln(str);
brea
k;
}while(true);
[Link](te
mp);
[Link]();
[Link]();
[Link]("successfully created");
28
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
}
catch(Excep琀椀on ex)
{
[Link](ex);
}
}
}
[Link] a java program to read a 昀椀le and display the content
on screen.
import [Link].*;
class input
{
public sta琀椀c void main(String arr[])
{
try
{
FileInputStreamf is=new FileInputStream("[Link]");
int a=昀椀[Link]();
[Link](a);
}
catch(IOExcep琀椀on e)
{
}
}
}
Lab Turn 9
Collection in Java
31 .Write a java program to create an array list collec琀椀on.
29
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
import java.u琀椀l.*;
class TestJavaCollec琀椀on1{
public sta琀椀c void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Crea琀椀ng arraylist
[Link]("Ravi");//Adding object in arraylist
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing list through Iterator
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
32 .Write a java program to create a stack collec琀椀on
import [Link].*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
[Link]("Ayush");
[Link]("Garvit");
[Link]("Amit");
[Link]("Ashish");
[Link]("Garima");
[Link]();
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
33 .Write a java program to create an queue list collec琀椀on.
import java.u琀椀l.*;
30
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
class TestCollec琀椀on12{
public sta琀椀c void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
[Link]("Amit");
[Link]("Vijay");
[Link]("Karan");
[Link]("Jai");
[Link]("Rahul");
[Link]("head:"+[Link]());
[Link]("head:"+[Link]());
[Link]("itera琀椀ng the queue elements:");
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
[Link]();
[Link]();
[Link]("a昀琀er removing two elements:");
Iterator<String> itr2=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
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();
[Link]("One");
[Link]("Two");
[Link]("Three");
[Link]("Four");
[Link]("Five");
Iterator<String> i=[Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
35 .Write a java program to create an Tree set collec琀椀on
import java.u琀椀l.*;
class TreeSet1{
public sta琀椀c void main(String args[]){
31
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
//Crea琀椀ng and adding elements
TreeSet<String> al=new TreeSet<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing elements
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
32
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
Lab Turn 10
Spring Framework
37 .Implement a spring framework based project en琀椀tled “ Health and Fitness App”
Create Your First Spring MVC Application
Consider the following example:
Step 0: Setup your project with maven use the required archtype to get the required folders
directory and configure the server with your project.
Step 1: Load the spring jar files or add the dependencies if Maven is used. Add the
following dependencies in [Link]
[Link]
XML
<project xmlns="[Link] \
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>SpringMVC</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringMVC Maven Webapp</name>
<url>[Link]
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- [Link] -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-webmvc</artifactId>
<version>[Link]</version>
</dependency>
<!-- [Link] -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>servlet-api</artifactId>
33
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
<version>3.0-alpha-1</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMVC</finalName>
</build>
</project>
Step 2: Defining a Controller
Let us Create the Controller Class
[Link]
Java
@Controller
public class HelloGeek {
@RequestMapping("/")
public String display()
{
return "hello";
}
}
Step 3: Provide the name of the controller in the [Link] file as follows:
DispatcherServlet is the front controller in Spring Web MVC. Incoming requests for the
HTML file are forwarded to the DispatcherServlet.
[Link]
XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="[Link]
xmlns="[Link]
xsi:schemaLocation="[Link]
[Link]
id="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>[Link]</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
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
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
[Link]
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xmlns:context="[Link]
xmlns:mvc="[Link]
xsi:schemaLocation="
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
<!-- This element defines the base-package where
DispatcherServlet will search the controller class. -->
<context:component-scan base-package="[Link]" />
<!--Provide support for conversion,
formatting and also for validation -->
<mvc:annotation-driven/>
</beans>
Step 5: Use JSP to display the message
[Link]
HTML
<html>
<body>
<p>Spring MVC Tutorial!!</p>
</body>
</html>
Step 6: Start the server and run the project. The output is displayed as follows:
Spring MVC Tutorial!!
35
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
38 . Building a RESTful Web Service with Spring Boot Actuator
package [Link];
public class Gree琀椀ng {
private 昀椀nal long id;
private 昀椀nal String content;
public Gree琀椀ng(long id, String content) {
[Link] = id;
[Link] = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
Now that you need to create the endpoint controller that will serve the representa琀椀on class.
Create a Resource Controller
In Spring, REST endpoints are Spring MVC controllers. The following Spring MVC controller (from
src/main/java/com/example/actuatorservice/[Link]) handles a GET request for
the /hello-world endpoint and returns the Gree琀椀ng resource:
package [Link];
import java.u琀椀[Link];
import [Link];
import [Link]琀椀[Link];
import [Link]琀椀[Link];
import [Link]琀椀[Link];
@Controller
public class HelloWorldController {
private sta琀椀c 昀椀nal String template = "Hello, %s!";
private 昀椀nal AtomicLong counter = new AtomicLong();
@GetMapping("/hello-world")
@ResponseBody
36
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
public Gree琀椀ng sayHello(@RequestParam(name="name", required=false,
defaultValue="Stranger") String name) {
return new Gree琀椀ng([Link](), [Link](template, name));
}
}
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琀椀[Link]) shows the applica琀椀on
class:
package [Link];
import [Link]琀椀on;
import [Link]昀椀[Link]琀椀on;
@SpringBootApplica琀椀on
public class HelloWorldApplica琀椀on {
public sta琀椀c void main(String[] args) {
SpringApplica琀椀[Link](HelloWorldApplica琀椀[Link], args);
}
}
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.
The @SpringBootApplica琀椀on annota琀椀on also brings in a @ComponentScan annota琀椀on, which tells
Spring to scan the [Link] package for those controllers (along with any other
annotated component classes).
Build an executable JAR
37
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
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:
java -jar build/libs/[Link]
If you use Maven, you can run the applica琀椀on by using ./mvnw spring-boot:run. Alterna琀椀vely, you
can build the JAR 昀椀le with ./mvnw clean package and then run the JAR 昀椀le, as follows:
java -jar target/[Link]
The steps described here create a runnable JAR. You can also build a classic WAR 昀椀le.
Once the service is running (because you ran spring-boot:run in a terminal), you can test it by
running the following command in a separate terminal:
$ 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琀椀[Link]琀椀es 昀椀le, you
can override that se琀�ng. The following lis琀椀ng (from
src/main/resources/applica琀椀[Link]琀椀es)shows that 昀椀le with the necessary changes:
[Link]: 9000
[Link]: 9001
[Link]: [Link]
Run the server again by running the following command in a terminal:
$ ./gradlew clean build && java -jar build/libs/[Link]
The service now starts on port 9000.
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琀椀[Link] ensures that
Your controller is responsive.
Your management endpoint is responsive.
Note that the tests start the applica琀椀on on a random port. The following lis琀椀ng shows the test class:
38
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
/*
package [Link];
import java.u琀椀[Link];
import [Link];
import [Link]琀椀[Link];
import [Link]琀椀[Link];
import [Link];
import [Link];
import [Link];
import [Link].h琀琀p.H琀琀pStatus;
import [Link].h琀琀[Link]琀椀ty;
import [Link];
import sta琀椀c [Link]琀椀[Link];
/**
* Basic integra琀椀on tests for service demo applica琀椀on.
*
* @author Dave Syer
*/
@SpringBootTest(webEnvironment = [Link].RANDOM_PORT)
@TestPropertySource(proper琀椀es = {"[Link]=0"})
public class HelloWorldApplica琀椀onTests {
@LocalServerPort
private int port;
@Value("${[Link]}")
private int mgt;
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void shouldReturn200WhenSendingRequestToController() throws Excep琀椀on {
@SuppressWarnings("rawtypes")
ResponseEn琀椀ty<Map> en琀椀ty = [Link]琀椀ty(
"h琀琀p://localhost:" + [Link] + "/hello-world", [Link]);
then(en琀椀[Link]()).isEqualTo(H琀琀[Link]);
}
@Test
public void shouldReturn200WhenSendingRequestToManagementEndpoint() throws Excep琀椀on {
39
Downloaded by Bhanu Pratap singh ([Link]@[Link])
lOMoARcPSD|49223878
@SuppressWarnings("rawtypes")
ResponseEn琀椀ty<Map> en琀椀ty = [Link]琀椀ty(
"h琀琀p://localhost:" + [Link] + "/actuator", [Link]);
then(en琀椀[Link]()).isEqualTo(H琀琀[Link]);
}
40
Downloaded by Bhanu Pratap singh ([Link]@[Link])