OOPS With Java Lab Manual 2023-24
OOPS With Java Lab Manual 2023-24
JAVA LAB
LABORATORY MANUAL
B.Tech., Semester -IV
Subject Code: BCS-
452
Roll. No.:
Group/Branch:
JSS MAHAVIDYAPEETHA
DEPARTMENT OF INFORMATION TECHNOLOGY
JSS ACADEMY OF TECHNICAL EDUCATION
C-20/1, SECTOR-62, NOIDA
C212: Object Oriented Programming with Java Lab (BCS-452)
Table of Contents
1. Vision and Mission of the Institute
2. Vision and Mission of the Department
3. Programme Educational Objectives (PEOs)
4. Programme Outcomes (POs)
5. Programme Specific Outcomes (PSOs)
6. University Syllabus
7. Course Outcomes (COs)
8. CO- PO and CO-PSO mapping
9. Course Overview
10. List of Experiments
11. DOs and DON’Ts
12. General Safety Precautions
13. Guidelines for students for report preparation
14. Lab assessment criteria
15. Details of Conducted Experiments
16. Lab Experiments
Mission:
M1: Develop a platform for achieving globally acceptable level of intellectual acumen and
technological competence.
M2: Create an inspiring ambience that raises the motivation level for conducting quality
research.
M3: Provide an environment for acquiring ethical values and positive attitude.
Mission:
M1: To create an environment where students can be equipped with strong fundamental
concepts, programming and problem solving skills.
M2: To provide an exposure to emerging technologies by providing hands on experience for
generating competent professionals.
M3: To promote Research and Development in the frontier areas of Information Technology
and encourage students for pursuing higher education
M4: To inculcate in students ethics, professional values, team work and leadership skills.
PEO2: To develop research oriented analytical ability among students and to prepare them
for making technical contribution to the society.
PEO3: To develop in students the ability to apply state-of-the–art tools and techniques for
designing software products to meet the needs of Industry with due consideration for
environment friendly and sustainable development.
PEO4:To prepare students with effective communication skills, professional ethics and
managerial skills.
PEO5: To prepare students with the ability to upgrade their skills and knowledge for life-
long learning.
PSO2: Design, implement and evaluate processes, components and/or programs using
modern techniques, skills and tools of core Information Technologies to effectively
integrate secure IT-based solutions into the user environment.
PSO3: Develop impactful IT solutions by using research based knowledge and research
methods in the fields of integration, interface issues, security & assurance and
implementation.
University Syllabus
1. Use Java compiler and eclipse platform to write and execute java program.
2. Creating 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 exception handling and multithreading.
6. Create java program with the use of java packages.
7. Construct java program using Java I/O package.
8. Create industry oriented application using Spring Framework.
9. Test RESTful web services using Spring Boot.
10. Test Frontend web application with Spring Boot
CO-PO Mapping:
PO 1 PO 2 PO 3 PO 4 PO 5 PO 6 PO 7 PO 8 PO 9 PO1 0 PO1 1 P1 2
C212.3 3 3 3 3 2 2 3 3
1
C212.3 3 3 3 3 2 2 3 3
2
C212.3 3 3 3 3 2 2 3 3
3
C212.3 3 3 3 3 2 2 3 3
4
C212.3 3 3 3 3 2 2 3 3
5
CO-PSO Mapping
PSO1PSO2
C212.1 2 3
C212.2 2 3
C212.3 2 3
C212.4 2 3
C212.5 2 3
Course Overview
This “JAVA PROGRAMMING” lab manual is intended to teach the basic Java Applications
and Java Applets. Readers of this manual must be familiar with the basic syntax of C or C++
and Object Oriented features. Java is increasingly becoming the default choice of the IT
industry especially industries involved in software development at system level. Therefore,
for proper development of Java Applications among the students, this practical lab manual
has been prepared. The manual contains the exercise programs and their solution for easy &
quick understanding of the students. We hope that this practical manual will be helpful for
students of IT for understanding the subject from the point of view of applied aspects. There
is always scope for improvement in the manual. We would appreciate to receive valuable
suggestions from readers and users for future use.
DON’Ts
1. Do not share your username and password.
2. Do not remove or disconnect cables or hardware parts.
3. Do not personalize the computer setting.
4. Do not run programs that continue to execute after you log off.
5. Do not download or install any programs, games or music on computer in Lab.
6. Personal Internet use chat room for Instant Messaging (IM) and Sites Strictly
Prohibited.
7. No Internet gaming activities allowed.
8. Tea, Coffee, Water & Eatables are not allowed in the Computer Lab.
1. To break the victim with live electric source .Use an insulator such as fire wood or
plastic to break the contact. Do not touch the victim with bare hands to avoid the risk
of electrifying yourself.
2. Unplug the risk of faulty equipment. If main circuit breaker is accessible, turn the
circuit off.
3. If the victim is unconscious, start resuscitation immediately, use your hands to press
the chest in and out to continue breathing function. Use mouth-to-mouth resuscitation
if necessary.
4. Immediately call medical emergency and security. Remember! Time is critical; be best.
1) All files must contain a title page followed by an index page. The files will not be signed
by the faculty without an entry in the index page.
2) Student’s Name, Roll number and date of conduction of experiment must be written on all
pages.
Note:
1. Students must bring their lab record along with them whenever they come for the lab.
Grading Needs
Exemplary (4) Competent
Criteria Improvement Poor (1)
(3)
(2)
AC1:
Complete procedure Underlined
Pre-Lab written Underlined concept
with concept is
Not able to write
work (for last is not clearly
underlined written but concept and
lab class, this understood
concept procedure
is is procedure
may be assessed
properly written incomplete
through viva)
Assigned problem
Assigned problem
is
is
properly
properly
analyzed, correct
AC2: analyzed, Assigned problem
solution
Program correct is properly Assigned problem
designed,
Writing/ solution analyzed & is
appropriate
Modeling designed, correct solution properly
language
appropriate designed analyzed
constructs/ tools
language
are applied,
constructs/
Program/solution
tools are
written is
applied
readable
Unable to
Able Is dependent totally
to
understand the
AC3: identify errors/ on
Able to identify reason for
Identification & bugs andsomeone for
errors/ bugs and errors/ bugs even
Removal of remove them identification of
remove them after they are
errors/ bugs with little bit errors/ bugs and
explicitly
of guidance their removal
pointed out
All variants of
All variants of Only few
input /output are input /output variants of input Solution is not well
AC4:Execution& tested, Solution is are not tested,/output are demonstrated
Demonstration well However, tested, and
demonstrated and solution is Solution is well implemented
implemented well demonstrated
demonstrated
LAB EXPERIMENTS
LAB EXPERIMENT 1
OBJECTIVE: Use Java Compiler and Eclipse platform to write and execute java
program.
Following are some useful instructions needed for developing and executing a program in
java:
a) Install the Eclipse IDE. If you don’t have installed it, download the Eclipse IDE and install
it. For this, go to this tutorial: Download and Install Eclipse IDE for Java
Ad
b) Writing the java program.
c) Compiling java program.
d) Run java program.
Hope that you have successfully installed Eclipse IDE by following all instructions. Now, we
will understand to create a java project in Eclipse.
Before creating Java programs in Eclipse IDE, we need to first create a project. A project is
like a folder structure that holds Java programs and all supporting files. We need to create
a project only once.
Follow all the steps below to create a Java project in Eclipse:
1. First of all, open Eclipse IDE and choose File > New > Java Project to display the New
Project wizard, as shown in Figure.
2. A new project wizard will be displayed. Select java project and then click on Next button
as shown in the below figure.
3. Type Java Project in the Project name field. As we type, the location field will be
automatically set by default. You may also customize the location for your project. Look
at the below figure to understand better.
4. Make sure that you chose the options “Use project folder as root for sources and
class files” so that the .java and .class files are in the same folder for easy access.
5. Click on the Finish button to create the project, as shown in the above Figure.
Now java project is created with the “src” folder as shown in the below figure. The next step is
to create a package folder.
Follow all the steps below to create a package in java in Eclipse IDE:
1. Right-click on the newly created Java project > New > Package. A new java package
wizard will be open as shown in the below figure.
2. Type a package name “javaProgram” and click on Finish button. A package folder named
javaProgram is created on the left side.
After the creation of package in the java project, we can create a program in java in the java
project using the following steps:
1. Right-click on package name “javaProgram” and choose File > New > Class to display the
New Java Class wizard.
2. Type Hello in the Name field > check the option public static void main(String[] args)
as shown in the below figure.
3. Click on Finish button to produce template for the program source code named Hello.java.
A class named Hello.java will be created below the package name on the left-hand side.
Now we will write the first simple java program in the template as written in the following
source code.
Program source code:
package javaProgram;
System.out.println("Hello World");
We have developed a simple java program in the Eclipse IDE. The next step is compiling and
executing a java program.
To run java program, right-click the class in the project to display a context menu. Choose
Run As > Java Application in the context menu to run java program.
The output is displayed in the Console pane, as shown in the below figure.
Input:
Java program with finite set of Input.
Output:
Program specific containing finite set of sequence.
1. What happens when the following program is compiled and run? Select the one
correct answer?
public class example
{ int i[] = {0};
public static void main(String args[]) {
int i[] = {1};
change_i(i);
System.out.println(i[0]);
}
public static void change_i(int i[])
{ int j[] = {2};
i = j;
}
}
A .The program does not compile.
B. prints 0
C. prints 1
D. prints 2
Correct Answer: C
LAB EXPERIMENT 2
BRIEF DESCRIPTION: The java command-line argument is an argument i.e. passed at the
time of running the java program.
The arguments passed from the console can be received in the java program and it can be
used as an input.
So, it provides a convenient way to check the behavior of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
PRE-EXPERIMENT QUESTIONS:
What are command line arguments with example?
Which data type is used to store command line arguments?
Which of the following is used to handle command line arguments?
What are the properties of command line arguments?
In this example, we are receiving only one argument and printing it. To run this java program, you
must pass at least one argument from the command prompt.
1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }
1. compile by > javac CommandLineExample.java
2. run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo
Input:
Java program
Output:
Finite set of output.
POST-EXPERIMENT QUESTIONS:
1. What is a command line argument in Java with example?
2. How many command line arguments we can pass in Java?
3. Which data type is used to store command line arguments in Java?
4. What are the two strings as command line arguments in Java?
LAB EXPERIMENT 3
BRIEF DESCRIPTION:
The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
The main aim of object-oriented programming is to implement real-world entities, for example,
object, classes, abstraction, inheritance, polymorphism, etc.
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes
and objects. It simplifies software development and maintenance by providing some
concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Apart from these concepts, there are some other terms which are used in Object-Oriented
design:
o Coupling
o Cohesion
o Association
o Aggregation
o Composition
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up
some space in memory. Objects can communicate without knowing the details of each other's
data or code. The only necessary thing is the type of message accepted and the type of
response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Class
A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
Coupling
Cohesion
Cohesion refers to the level of a component which performs a single well-defined task. A
single well-defined task is done by a highly cohesive method. The weakly cohesive method
will split the task into separate parts. The java.io package is a highly cohesive package
because it has
I/O related classes and interface. However, the java.util package is a weakly cohesive
package because it has unrelated classes and interfaces.
Association
Association represents the relationship between the objects. Here, one object can be
associated with one object or many objects. There can be four types of association between
the objects:
o One to One
o One to Many
o Many to One, and
o Many to Many
Let's understand the relationship with real-time examples. For example, One country can
have one prime minister (one to one), and a prime minister can have many ministers (one to
many). Also, many MP's can have one prime minister (many to one), and many ministers can
have many departments (many to many).
Aggregation
Composition
The composition is also a way to achieve Association. The composition represents the
relationship where one object contains other objects as a part of its state. There is a strong
relationship between the containing object and the dependent object. It is the state where
containing objects do not have an independent existence. If you delete the parent object, all
the child objects will be deleted automatically.
PRE-EXPERIMENT QUESTIONS:
1. What are 4 types of OOPs?
2. What are the 5 aspects of OOP?
3. Why polymorphism is used in OOPS?
4. Why do we use OOP?
3) OOPs provides the ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented Programming
language.
Object-based programming language follows all the features of OOPs except Inheritance.
JavaScript and VBScript are examples of object-based programming languages.
Input:
Java Program
Output:
Finite set of Output sequence.
POST-EXPERIMENT QUESTIONS:
LAB EXPERIMENT 4
DESCRIPTION:
Inheritance in Java
When defining a child class in Java, we use the keyword extends to inherit from a parent class.
// Parent Class
class Animal {
// Animal class members
}
// Child Class
class Dog extends Animal {
// Dog inherits traits from Animal
In simple Java programs, you may work with just one class and one file. However, as your
programs become more complex you will work with multiple classes, each of which requires
its own file. Only one of these files in the Java package requires a main() method, and this is
the file that will be run in the package.
For example, say we have two files in our Java package for two different classes:
If the Java file containing our Shape class is the only one with a main() method, this is the file
that will be run for our Java package.
// Shape.java file
class Shape {
public static void main(String[] args) {
Square sq = new Square();
}
}
// Square.java file
class Square extends Shape {
super() in Java
In Java, a child class inherits its parent’s fields and methods, meaning it also inherits the
parent’s constructor. Sometimes we may want to modify the constructor, in which case we
can use the super() method, which acts like the parent constructor inside the child class
constructor.
Alternatively, we can also completely override a parent class constructor by writing a new
constructor for the child class.
// Parent class
class Animal {
String sound;
Animal(String snd) {
this.sound = snd;
}
}
// Child class
class Dog extends Animal {
// super() method can act like the parent constructor inside the child class constructor.
Dog() {
super("woof");
}
// alternatively, we can override the constructor completely by defining a new constructor.
Dog() {
this.sound = "woof";
}
}
When creating classes in Java, sometimes we may want to control child class access to parent
class members. We can use the protected and final keywords to do just that.
protected keeps a parent class member accessible to its child classes, to files within its own
package, and by subclasses of this class in another package.
Adding final before a parent class method’s access modifier makes it so that any child classes
cannot modify that method - it is immutable.
class Student {
protected double gpa;
// any child class of Student can access gpa
PRE-EXPERIMENT QUESTIONS:
1. What is Polymorphism?
2. What is Inheritance?
Polymorphism in Java
Polymorphism allows a child class to share the information and behavior of its parent class
while also incorporating its own functionality. This allows for the benefits of simplified
syntax and reduced cognitive overload for developers.
// Parent class
class Animal {
public void greeting() {
System.out.println("The animal greets you.");
}
}
// Child class
class Cat extends Animal {
public void greeting() {
System.out.println("The cat meows.");
}
}
class MainClass {
public static void main(String[] args) {
Animal animal1 = new Animal(); // Animal object
Animal cat1 = new Cat(); // Cat object
animal1.greeting(); // prints "The animal greets you."
Input:
Java code
Output :
Finite set of output sequence.
POST-EXPERIMENT QUESTIONS:
1. How does inheritance used in polymorphism in Java?
2. Which polymorphism concept is used in inheritance question?
3. Does polymorphism require inheritance?
4. Is inheritance and overriding required for polymorphism?
LAB EXPERIMENT 5
BRIEF DESCRIPTION:
Exception handling and multithreading are two essential concepts in the Java programming
language that are used to improve the performance and reliability of a program. Exception
handling is a mechanism that allows a program to handle errors and exceptional events,
while multithreading is a technique that enables a program to perform multiple tasks
simultaneously. In this article, we will discuss the basics of exception handling and
multithreading in Java and how they can be used to improve the performance and reliability
of your programs.
PRE-EXPERIMENT QUESTIONS:
Try-catch-finally blocks are used in Java to handle exceptions. The catch block provides intended
to catch exceptions, and the try block is utilized to contain code that might throw them. Any
resources spent in the try block are cleaned up in the finally block. For example, the
following code snippet shows how to handle a FileNotFoundException, which is thrown
when a file that is to be read cannot be found:
try {
FileInputStream file = new FileInputStream("file.txt");
int data = file.read();
// do something with data
} catch (FileNotFoundException e)
{ System.err.println("File not found: " +
e.getMessage());
} finally {
file.close();
}
In this example, the try block is used to open the file and read its contents, while the catch block
is used to handle the FileNotFoundException that may be thrown. No matter whether this
exception was thrown, closing the file is done in the finally block.
Another important feature of exception handling in Java is the ability to throw custom
exceptions. It allows you to create your own exception classes that can be thrown and caught
in your code. For example, you might create a custom exception class called
InvalidDataException, which is thrown when the data read from a file is invalid:
class InvalidDataException extends Exception
{ public InvalidDataException(String message) {
super(message);
}
}
In this example, the InvalidDataException class is a subclass of the Exception class, and it
takes a message as its constructor argument. Just like any other Java exception, such
customized exception can indeed be thrown and handled in the same manner.
When a class inherits the thread class as well as overrides the run() method, a new thread is
created in this instance. This activates the new thread's entry point that was generated in the
class that extended the thread class. Additionally, the program's thread is launched and
operated using the start() method.
File name: Aman.java
// Java programme that uses threads and exceptions
// Importing Files and Classes
import java.io.*;
// The parent Class, which the child Class (Thread) inherits (Aman)
class Aman extends Thread {
// The ability to determine whether a thread is active
public void run()
{
System.out.println("It is a running thread");
// iterating with a for loop
for (int s = 0; s < 10; ++s) {
System.out.println("running the thread loop" + s);
}
}
// Loading the Main Driver Method
public static void main(String[] args)
{
// attempt-catch block for exception detection
try {
LAB EXPERIMENT 6
BRIEF DESCRIPTION:
In Java, a package is a group of classes, interfaces, enumeration, and annotations. Java contains
many pre-defined packages such as java.lang, java.io, java.net, etc. When we create any
Java program the java.lang package is imported by default. We need not to write the
package name at the top of the program. We can also create our own package by providing
the name that we want. In this section, we will learn how to create a package in Java.
o The package makes the search easier for the classes and interfaces.
o It provides a fully qualified name that avoids naming conflicts.
o It also controls access.
o It organizes classes in a folder structure.
o It improves code reusability.
o Programmer can group classes and interfaces into a related package.
PRE-EXPERIMENT QUESTIONS
1. What are the basics of packages in Java?
2. What are the 6 packages in Java?
3. Which is the main package in Java?
4. How to import packages in Java?
Creating a Package
We follow the naming convention rules to name a package. Java has some predefined packages
and also allows us to create our own package. So, it is possible that a programmer can create
a class with the same name as a package that already contains that type in a predefined
package.
Department of Information Technology 2024-25
C212: Object Oriented Programming with Java Lab (BCS-452)
Suppose, a programmer creates a class with the name Rectangle in the package shape. The
class with the same name is already present in java.awt package. The compiler allows both
classes if they belong to the different packages. The fully qualified name of each class
contains the package name that differentiate both Rectangle classes. Therefore, the package
name of the user-defined class will be shape.Rectangle and the package name of the
predefined class will be java.awt.Rectangle.
o Package name must be in lower case that avoids conflict with the name of classes and
interfaces.
o Organizations used their internet domain name to define their package names. For
example, com.javatpoint.mypackage. Sometimes, the organization also uses the
region after the company name to name the package. For
example, com.javatpoint.region.mypackage.
o We use underscore in the package name if the domain name contains hyphen or other
special characters or package names begin with a digit or reserved keyword.
Hyphenated-name.example.org org.example.hyphenated_name
Example.int int_.example
123name.example.com com.example._123name
Importing a Package
If we want to use a package in Java program it is necessary to import that package at the top
of the program by using the import keyword before the package name.
Syntax:
1. import packageName;
Add.java
1. package p1;
2. import java.util.*;
3. public class Add
4. {
5. int s;
6. public void sum()
7. {
Sub.java
1. package p2;
2. import java.util.*;
3. public class Sub
4. {
5. int d;
6. public void diff()
7. {
8. System.out.print("Enter the first number: ");
9. Scanner scan=new Scanner(System.in);
10. int x=scan.nextInt();
11. System.out.print("Enter the second number: ");
12. Scanner scan1=new Scanner(System.in);
13. int y=scan1.nextInt();
14. d=x-y;
15. System.out.println("Difference="+d);
16. }
17. }
Mult.java
1. package p3;
2. import java.util.*;
3. public class Mult
4. {
5. int m;
6. public void pro()
7. {
8. System.out.print("Enter the first number: ");
9. Scanner scan=new Scanner(System.in);
10. int x=scan.nextInt();
Div.java
1. package p4;
2. import java.util.*;
3. public class Div
4. {
5. int q;
6. public void divd()
7. {
8. System.out.print("Enter the first number: ");
9. Scanner scan=new Scanner(System.in);
10. int x=scan.nextInt();
11. System.out.print("Enter the second number: ");
12. Scanner scan1=new Scanner(System.in);
13. int y=scan1.nextInt();
14. q=x/y;
15. System.out.println("Division="+q);
16. }
17. }
Now, we are going to create the main class named Calculator. In this class, we have imported all
the packages that we have created above. It includes all the classes in the Calculator class.
Calculator.java
1. package p5;
2. //importing pre-defined package
3. import java.util.*;
4. //importing user-defined package
5. import p1.Add;
6. import p2.Sub;
7. import p3.Mult;
8. import p4.Div;
9. public class Calculator
10. {
11. public static void main(String args[])
12. {
When we compile the above program, it creates corresponding .class files in packages named p1,
p2, p3, p4, and p5, respectively.
The .class files are generated. Now, we can run the above program.
Output:
Input:
Java program containing set of functionalities to create packages.
Output:
Finite set of output sequence.
POST-EXPERIMENT QUESTIONS:
1. What are the advantages of a java package?
2. Define Packages in Java?
3. Why are the packages used?
4. Can we import same package/class twice?
5. Explain the usage of Java packages?
6. What is the base class of all classes?
7. What do you think is the logic behind having a single base class for all classes?
LAB EXPERIMENT 7
BRIEF DESCRIPTION:
Java brings various Streams with its I/O package that helps the user to perform all the
input-output operations. These streams support all the types of objects, data-types,
characters, files etc to fully execute the I/O operations.
Before exploring various input and output streams let’s look at 3 standard or default
streams that Java has to provide which are also most common in use:
1. System.in: This is the standard input stream that is used to read characters from the
keyboard or any other standard input device.
2. System.out: This is the standard output stream that is used to produce the result of a
program on an output device like the computer screen.
PRE-EXPERIMENT QUESTIONS
1. What is use of io package in Java?
2. What is the package for input output in Java?
3. Which three classes belong to the Java io package?
Here is a list of the various print functions that we use to output statements:
print(): This method in Java is used to display a text on the console. This text is
passed as the parameter to this method in the form of String. This method prints the
text on the console and the cursor remains at the end of the text at the console. The
next printing takes place from just here.
Syntax:
System.out.print(parameter);
1.
Example:
import java.io.*;
class Demo_print {
// using print()
// same line
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
Output:
GfG! GfG! GfG!
println(): This method in Java is also used to display a text on the console. It prints
the text on the console and the cursor moves to the start of the next line at the
console. The next printing takes place from the next line.
Syntax:
System.out.println(parameter);
Example:
import java.io.*;
class Demo_print {
// using println()
// different line
System.out.println("GfG! ");
System.out.println("GfG! ");
System.out.println("GfG! ");
Output:
GfG!
GfG!
GfG!
printf(): This is the easiest of all methods as this is similar to printf in C. Note that
System.out.print() and System.out.println() take a single argument, but printf() may
take multiple arguments. This is used to format the output in Java.
Example:
class JavaFormatter1 {
int x = 100;
System.out.printf(
"Printing simple"
x);
// 2 decimal places
System.out.printf(
"Formatted with"
Math.PI);
float n = 5.2f;
System.out.printf( "Formatte
d to "
n);
n = 2324435.3f;
// width of 20 characters
System.out.printf(
"Formatted to "
n);
Output:
Printing simple integer: x = 100
Formatted with precision: PI = 3.14
Formatted to specific width: n = 5.2000
Formatted to right margin: n = 2324435.2500
2. System.err: This is the standard error stream that is used to output all the error data
that a program might throw, on a computer screen or any standard output device.
This stream also uses all the 3 above-mentioned functions to output the error data:
print()
println()
printf()
Example:
import java.io.*;
throws IOException
char c;
do {
c = (char)inp.read();
System.out.println(c);
} while (c != '0');
Input:
GeeksforGeeks0
Output:
Enter characters, and '0' to quit.
G
e
e
k
s
f
o
r
G
e
e
k
s
0
Types of Streams:
Depending on the type of operations, streams can be divided into two primary classes:
1. Input Stream: These streams are used to read data that must be taken as an input
from a source array or file or any peripheral device. For eg., FileInputStream,
BufferedInputStream, ByteArrayInputStream etc.
2. Output Stream: These streams are used to write data as outputs into an array or file
or any output peripheral device. For eg., FileOutputStream, BufferedOutputStream,
ByteArrayOutputStream etc.
Depending on the types of file, Streams can be divided into two primary classes which
can be further divided into other classes as can be seen through the diagram below
followed by the explanations.
1. ByteStream: This is used to process data byte by byte (8 bits). Though it has many
classes, the FileInputStream and the FileOutputStream are the most popular ones.
The FileInputStream is used to read from the source and FileOutputStream is used
to write to the destination. Here is the list of various ByteStream Classes:
Stream class Description
PrintStream This contains the most used print() and println() method
DataOutputStream This contains method for writing java standard data types.
Example:
import java.io.*;
try {
sourceStream
= new FileInputStream("sorcefile.txt");
targetStream
= new FileOutputStream("targetfile.txt");
int temp;
while ((
temp = sourceStream.read())
!= -1)
targetStream.write((byte)temp);
finally {
if (sourceStream != null)
sourceStream.close();
if (targetStream != null)
targetStream.close();
Output:
Shows contents of file test.txt
CharacterStream: In Java, characters are stored using Unicode conventions (Refer
this for details). Character stream automatically allows us to read/write data
character by character. Though it has many classes, the FileReader and the
FileWriter are the most popular ones. FileReader and FileWriter are character
streams used to read from the source and write to the destination respectively. Here
is the list of various CharacterStream Classes:
Stream class Description
PrintWriter This contains the most used print() and println() method
Example:
// and IOException
import java.io.*;
try {
sourceStream
= new FileReader("test.txt");
// character by character.
int temp;
while ((
temp = sourceStream.read())
!= -1)
System.out.println((char)temp);
finally {
if (sourceStream != null)
sourceStream.close();
Input:
Java Program
Output:
Finite sequence of output.
POST-EXPERIMENT QUESTIONS:
1. Which package is imported by default in Java?
2. What are types of package in Java?
LAB EXPERIMENT 8
BRIEF DESCRIPTION:
Projects
From configuration to security, web apps to big data—whatever the infrastructure needs of your
application may be, there is a Spring Project to help you build it. Start small and use just what
you need—Spring is modular by design.
LAB EXPERIMENT 9
BRIEF DESCRITPTION:
A Spring Boot RESTful service is typically divided into three layers: Repository,
Service, and Controller. This layering helps to segregate the RESTful application
responsibilities and enabling loose coupling between the objects.
When you develop a layered RESTful application, you will also need to test the different
layers.
In this post, I will discuss testing Spring Boot RESTful Services with Spring MVC Test
and JUnit5.
Mockito
, JUnit
,
Hamcrest
,
AssertJ
.
PRE-EXPERIMENT QUESTIONS:
1. How to test Spring Boot REST service?
2. What are RESTful web services in Spring Boot?
3. How to test RESTful web services?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
Testing the Repository Layer
@Repository
public interface ProductRepository extends JpaRepository <Product, Integer> {
}
Let’s start writing the test class,
ProductRepositoryTest
.
@ExtendWith(SpringExtension.class)
@DataJpaTest
class ProductRepositoryTest {
The first statement annotates the class with
@ExtendWith(SpringExtension.class)
. This integrates the Spring test context framework into the JUnit 5 Jupiter programming
model.
Our test will be an integration test as an external database is used. Being an integration
test, we need to load the Spring context in our test. We can do that using the
@SpringBootTest
annotation.
However, loading the entire Spring context is heavy and makes the tests slow.
Therefore, we will only load the Spring Data JPA slice of the Spring context. The
@DataJpaTest
annotation in the code does exactly that.
Next, let’s autowire the
ProductRepository
that we will test and write the
setup()
and
teardown()
methods.
@Autowired
private ProductRepository productRepository;
private Product product;
@BeforeEach
public void setUp() {
product = new Product(1,"Bat",2500);
}
@AfterEach
public void tearDown() {
productRepository.deleteAll();
product = null;
}
@Test
public void givenProductToAddShouldReturnAddedProduct(){
productRepository.save(product);
Product fetchedProduct = productRepository.findById(product.getId()).get();
assertEquals(1, fetchedProduct.getId());
}
@Test
public void GivenGetAllProductShouldReturnListOfAllProducts(){
Product product1 = new Product(1,"ball",400);
Product product2 = new Product(2,"bat",500);
productRepository.save(product1);
productRepository.save(product2);
List<Product> productList = (List<Product>) productRepository.findAll();
assertEquals("bat", productList.get(1).getName());
}
@Test
public void givenIdThenShouldReturnProductOfThatId()
{ Product product1 = new Product(1,"bat",3000);
Product product2 = productRepository.save(product1);
Optional<Product> optional = productRepository.findById(product2.getId());
assertEquals(product2.getId(), optional.get().getId());
assertEquals(product2.getName(), optional.get().getName());
}
@Test
public void givenIdTODeleteThenShouldDeleteTheProduct()
{ Product product = new Product(4, "pen",160);
productRepository.save(product);
productRepository.deleteById(product.getId());
Optional optional = productRepository.findById(product.getId());
assertEquals(Optional.empty(), optional);
}
Let’s run the tests, as you can see from the output provided below, all the test case passes.
ProductServiceImpl
is responsible for using the repository for performing CRUD operation.
This is the code of the
ProductServiceImpl
class.
ProductServiceImpl.java
@Service
public class ProductServiceImpl implements
ProductService{ private ProductRepository productRepository;
@Autowired
public void setProductRepository(ProductRepository productRepository){
this.productRepository =productRepository;
}
@Override
public Product addProduct(Product product) throws ProductAlreadyExistsException {
if(productRepository.existsById(product.getId())){
throw new ProductAlreadyExistsException();
}
return productRepository.save(product);
}
@Override
public List<Product> getAllProducts() {
return (List<Product>) productRepository.findAll();
}
@Override
public Product getProductByid(int id) {
return productRepository.findById(id).orElse(null);
}
@Override
public Product deleteProductById(int id) {
Product product = null;
Optional optional = productRepository.findById(id);
if (optional.isPresent()) {
product = productRepository.findById(id).get();
productRepository.deleteById(id);
}
return product;
}
We will write pure unit tests of the service implementation –
ProductServiceImpl
. The reason is that unit tests are super-fast and therefore cuts down developers’ time.
Note that in unit testing, when we have external dependencies, we mock the
dependencies. So in this example, we will mock the
ProductRepository
class.
For more information on mocking, refer to my post Mocking in Unit Tests with Mockito.
Let’s start writing the code. The code for the unit test is this.
@ExtendWith(MockitoExtension.class)
class ProductServiceTest {
@Mock
private ProductRepository productRepository;
@Autowired
@InjectMocks
private ProductServiceImpl productService;
private Product product1;
private Product product2;
List<Product> productList;
@BeforeEach
public void setUp() {
productList = new ArrayList<>();
product1 = new Product(1, "bread",20);
product2 = new Product(2, "jam",200);
productList.add(product1);
productList.add(product2);
}
@AfterEach
public void tearDown()
{ product1 = product2 =
null; productList = null;
}
Line 1 uses annotation. This
MockitoExtension
is a part of the Mockito library that is used to perform mocking. It initializes mocks in test
classes.
Then, Line5 – Line 6 uses the
@Mock
annotation on
ProductRepository
. At run time, Mockito will create a mock of
ProductRepository
.
Finally, Line 8-Line10 uses the
@Autowired
annotation to autowire in
ProductServiceImpl
. The
@InjectMock
the annotation will initialize the
ProductServiceImpl
object with the
ProductRepository
mock.
@Test
void givenProductToAddShouldReturnAddedProduct() throws
ProductAlreadyExistsException{
//stubbing
when(productRepository.save(any())).thenReturn(product1);
productService.addProduct(product1);
verify(productRepository,times(1)).save(any());
}
@Test
@Test
public void givenIdThenShouldReturnProductOfThatId() {
Mockito.when(productRepository.findById(1)).thenReturn(Optional.ofNullable(product1)
);
assertThat(productService.getProductByid(product1.getId())).isEqualTo(product1);
}
@Test
public void givenIdTODeleteThenShouldDeleteTheProduct(){
when(productService.deleteProductById(product1.getId())).thenReturn(product1);
//assertThat(productService.);
verify(productRepository,times(1)).findAll();
}
Let’s run the tests.
As you can see from the output provided below, all the test cases pass.
@RestController
@RequestMapping("api/v1")
public class ProductController {
private ProductService productService;
public ProductController(ProductService productService)
{ this.productService = productService;
}
@PostMapping("product")
public ResponseEntity<Product> addProduct(@RequestBody Product product) throws
ProductAlreadyExistsException {
Product saveProduct = productService.addProduct(product);
return new ResponseEntity<>(saveProduct, HttpStatus.CREATED);
}
@GetMapping("products")
public ResponseEntity<List<Product>> getAllProducts()
{ return new ResponseEntity<List<Product>>(
(List <Product>) productService.getAllProducts(),HttpStatus.OK);
}
@GetMapping("product/{id}")
public ResponseEntity<Product> getProductById(@PathVariable("id") int id){
return new ResponseEntity<>(productService.getProductByid(id),HttpStatus.OK);
}
@DeleteMapping("product/{id}")
public ResponseEntity<Product> deleteProduct(@PathVariable("id") int id) {
ResponseEntity responseEntity;
Product deletedProduct = productService.deleteProductById(id);
responseEntity = new ResponseEntity<Product>(deletedProduct, HttpStatus.OK);
return responseEntity;
}
}
As you can see in the preceding code, the controller has a dependency on the service
class,
ProductService
.
So in our test, we will use Mockito to mock
ProductService
and inject a mock on
ProductController
.
Now, let’s start writing the test class.
@ExtendWith(MockitoExtension.class)
class ProductControllerTest {
@Mock
@Mock
annotation on
ProductService
. At run time, Mockito will create a mock of
ProductService
.
Next, Line 12-Line13 uses the
@Autowired
annotation to autowire in
MockMvc
. The
@InjectMock
annotation will initialize the
ProductController
object.
We need to send HTTP requests to the controller from our test class to assert they are
responding as expected. For that, Line 18 uses
MockMvc
.
MockMvc
provides a powerful way to mock Spring MVC. Through
@MockMvc
you can send
MockHttp
request to a controller and test how the controller responds.
You can create instance of
mockMvc
@Test
public void PostMappingOfProduct() throws Exception{
when(productService.addProduct(any())).thenReturn(product);
mockMvc.perform(post("/api/v1/product").
contentType(MediaType.APPLICATION_JSON).
content(asJsonString(product))).
andExpect(status().isCreated());
verify(productService,times(1)).addProduct(any());
}
In-Line 4-Line 7,
mockMvc
performs a post-operation of product on the URL
"/api/v1/product"
whose content type is
APPLICATION_JSON
. The status is
isCreated()
.
mockMvc
to send a GET request to retrieve all products
@Test
public void GetMappingOfAllProduct() throws Exception {
when(productService.getAllProducts()).thenReturn(productList);
mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/products").
contentType(MediaType.APPLICATION_JSON).
content(asJsonString(product))).
andDo(MockMvcResultHandlers.print());
verify(productService).getAllProducts();
verify(productService,times(1)).getAllProducts();
}
In-Line 4-Line 7,
mockMvc
performs a GET request to retrieve all products from the URL
"/api/v1/products "
whose content type is
Json
. The content is
JsonString
of product details.
This is the output on running the test.
mockMvc
to send a GET request to retrieve a product with a given id.
@Test
public void GetMappingOfProductShouldReturnRespectiveProducct() throws Exception {
when(productService.getProductByid(product.getId())).thenReturn(product);
mockMvc.perform(get("/api/v1/product/1").
contentType(MediaType.APPLICATION_JSON).
content(asJsonString(product))).
andExpect(MockMvcResultMatchers.status().isOk()).
andDo(MockMvcResultHandlers.print());
}
Similarly, in Line 4-Line 8,
mockmvc
performs a GET request to retrieve a product with given product id 1 from the URL
"/api/v1/product/1 "
. Its content type is
Json
and content is
JsonString
of product details.
The output on running the test is this.
mockMvc
to send a DELETE request to delete a product with a given id.
@Test
public void DeleteMappingUrlAndIdThenShouldReturnDeletedProduct() throws
Exception {
when(productService.deleteProductById(product.getId())).thenReturn(product);
mockMvc.perform(delete("/api/v1/product/1")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(product)))
.andExpect(MockMvcResultMatchers.status().isOk()).
andDo(MockMvcResultHandlers.print());
}
public static String asJsonString(final Object obj){
try{
return new ObjectMapper().writeValueAsString(obj);
}catch (Exception e){
mockmvc
performs a DELETE request to delete a product with id 1 from the URL
"/api/v1/product/1 "
. The content type is
Json
. The content is
JsonString
of product details.
Now, let’s run the test cases.
The output shows below that all the test cases passed.
Input:
What are RESTful web services in Spring Boot?
Output:
Client and server applications that communicate over the WWW
POST EXPERIMENT QUESTIONS:
1. What is a REST API and how does it function?
2. How does REST APIs differ from SOAP APIs?
3. What are the primary components of an HTTP request and response in a REST API?
LAB EXPERIMENT 10
BRIEF DESCRIPTION:
There are so many different testing approaches in Spring Boot used for deploying the application
server. Testing in Spring Boot is an important feature of software development which ensures
that your application behaves as per the requirement and meets all the testing criteria. Spring
Boot provides a robust testing framework that supports Unit Testing, Integration Testing,
and End-to-End Testing.
1. Unit Tests:
The Focus is on testing individual components or units of the code in isolation.
Use tools like JUnit and Mockito for the writing unit tests.
2. Integration Tests:
Test the interactions between the multiple components or modules.
Ensures that different parts of the application work together perfectly.
Typically involves testing repositories, services, and controllers.
3. End-to-End (E2E) Tests:
Test the entire application from the end to end simulating real user scenarios.
Involve testing application’s behavior through its external interfaces.
Use tools like Selenium for the web applications.
PRE-EXPERIMENT QUESTIONS:
How Java is used in Spring Boot?
What are the important topics in Spring Boot?
What is the main class in Spring Boot?
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
Explanation:
@RunWith(SpringRunner.class):The Specifies the runner that JUnit should use to run
the tests. The SpringRunner is the new name for the SpringJUnit4ClassRunner.
@SpringBootTest: Used to indicate that the annotated class is the Spring Boot test
class.
Property File Configuration:
For testing, you might want to have a separate the application-test.properties file. The
Spring Boot automatically picks up properties from this file during the tests.
2. @TestConfiguration (Test Configuration)
The @TestConfiguration is used to the specify additional configuration for the tests. It is
often used to define @Bean methods for the test-specific beans.
@TestConfiguration
public class TestConfig {
@Bean
public MyService myService()
{ return new MyService();
}
}
3. @MockBean (Mocking)
The @MockBean is used to mock a bean of the specific type, making it convenient to test
components that depend on bean.
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyServiceTest {
@Autowired
private MyService myService;
@MockBean
private ExternalService externalService;
@Test
public void testServiceMethod() {
// Define behavior for the mocked external service
when(externalService.getData()).thenReturn("Mocked Data");
// Now test the method from MyService that uses externalService
String result = myService.processData();
assertEquals("Processed: Mocked Data", result);
}
}
Additional Annotations
@AutoConfigureMockMvc: Used with the @SpringBootTest to automatically
configure a MockMvc instance.
@DirtiesContext: Indicates that the ApplicationContext associated with test is dirty and
should be closed after the test.
@Transactional: Used to indicate that a test-managed transaction should be used.
Conclusion
The Spring Boot’s testing support combined with the popular testing libraries like JUnit
and Mockito enables the developers to create comprehensive test suites for their
applications. By using the appropriate testing annotations and strategies you can ensure the
reliability and correctness of the your Spring Boot applications.
POST-EXPERIMENT QUESTIONS:
1. Can springboot be used for frontend?
2. How do I test my spring boot application?
3. How to test web client in Spring Boot?
4. Can we use spring boot for web application?