Core Java Lab Manual-CS270
Core Java Lab Manual-CS270
LAB MANUAL
Branch :- CSE
Year :- 2nd
Semester :- 3rd
To produce highly skilled personnel who are empowered enough to transform the society by their
education, research and innovations.
MISSION
To offer diverse academic programs at undergraduate, postgraduate, and doctorate levels that are in
line with the current trends in Computer Science and Engineering.
To provide the state of the art infrastructure for teaching, learning and research.
To facilitate collaborations with other universities, industry and research labs.
To produce graduates who have strong foundation of knowledge and skills in the field of
PEO1 computer science and engineering.
PEO3 To produce graduates who can provide solutions to challenging problems in their profession by
applying computer engineering theory and practices.
PEO4 To produce graduates who can provide leadership and are effective in multidisciplinary
environment.
PROGRAM SPECIFIC OUTCOMES ( PSO’s)
PSO 1 Ability to understand the principles and working of computer systems. Students have a sound
knowledge about the hardware and software aspects of computer systems.
PSO 2 Ability to design and develop computer programs and understand the structure and development
methodologies of software systems.
PSO 3 Ability to apply their skills in the field of algorithms, networking, web design, cloud computing
and data analytics.
PSO 4 Ability to apply knowledge to provide innovative novel solutions to existing problem and identify
research gaps
Course Objectives
Course Outcome
After undergoing this laboratory module, the participant should be able to:
1- Demonstrate an understanding of programming paradigms and fundamental Java programming
concepts.
2- Implement Object-Oriented Programming feature of class design, object creation, constructors,
access modifiers and Arrays.
3- Apply inheritance and polymorphism to create modular and reusable JAVA program
4- Perform file handling and input/output operations using Java’s standard I/O streams and file
handling classes.
5- Utilize exception handling techniques for efficient program execution & Develop multithreaded
programs by implementing thread creation, synchronization, and inter-thread communication.
CERTIFICATE
Laboratory Objective
Upon successful completion of this Lab the student will be able to:
1. Understand the concept of OOP as well as the purpose and usage principles of
inheritance, polymorphism, encapsulation and method overloading.
2. Understand fundamentals of programming such as variables, conditional and iterative
execution, methods, etc.
3. Identify classes, objects, members of a class and the relationships among them needed
for a specific problem.
4. Understand fundamentals of object-oriented programming in Java, including defining
classes, invoking methods, using class libraries, etc.
5. Create Java application programs using sound OOP practices (e.g., interfaces and APIs)
and proper program structuring (e.g., by using access control identifies, automatic
documentation through comments, error exception handling)
6. Have the ability to write a computer program to solve specified problems.
7. Develop programs using the Java Collection API as well as the Java standard class
library.
8. Use the Java SDK environment to create, debug and run simple Java programs
Overview of Java
Java Is Important to the Internet, The Internet helped catapult Java to the forefront of
programming, and Java, in turn, has had a profound effect on the Internet. The reason for this is
quite simple: Java expands the universe of objects that can move about freely in cyberspace. In a
network, two very broad categories of objects are transmitted between the server and our
personal computer: passive information and dynamic, active programs.
Java can be used to create two types of programs: applications and applets. An application is a
program that runs on your computer, under the operating system of that computer. An applet is
an application designed to be transmitted over the Internet and executed by a Java- compatible
Web browser.
Features of JAVA
▪ Simple
▪ Secure
▪ Portable
1
▪ Object-oriented
▪ Robust
▪ Multithreaded
▪ Architecture-neutral
▪ Interpreted
▪ High performance
▪ Distributed
▪ Dynamic
JDK
The Java Development Kit (JDK) is an implementation of either one of the Java SE, Java EE or
Java ME platforms. The JDK includes a private JVM and a few other resources to finish the
development of a Java Application.
The JDK has as its primary components a collection of programming tools, including:
▪ appletviewer – this tool can be used to run and debug Java applets without a web
browser
▪ apt – the annotation-processing tool.
▪ extcheck – a utility that detects JAR file conflicts
▪ idlj – the IDL-to-Java compiler. This utility generates Java bindings from a given Java
IDL file.
▪ jabswitch – the Java Access Bridge. Exposes assistive technologies on Microsoft
Windows systems.
▪ java – the loader for Java applications. This tool is an interpreter and can interpret the
class files generated by the javac compiler. Now a single launcher is used for both
development and deployment. The old deployment launcher, jre, no longer comes with
Sun JDK, and instead it has been replaced by this new java loader.
▪ javac – the Java compiler, which converts source code into Java bytecode
▪ javadoc – the documentation generator, which automatically generates documentation
from source code comments
▪ jar – the archiver, which packages related class libraries into a single JAR file. This
tool also helps manage JAR files.
▪ javafxpackager – tool to package and sign JavaFX applications
▪ jarsigner – the jar signing and verification tool
▪ javah – the C header and stub generator, used to write native methods
▪ javap – the class file disassembler
▪ javaws – the Java Web Start launcher for JNLP applications
▪ JConsole – Java Monitoring and Management Console
▪ jdb – the debugger
▪ jhat – Java Heap Analysis Tool (experimental)
▪ jinfo – This utility gets configuration information from a running Java process or
crash dump. (experimental)
▪ jmap – This utility outputs the memory map for Java and can print shared object
memory maps or heap memory details of a given process or core dump.
(experimental)
▪ jmc – Java Mission Control
▪ jps – Java Virtual Machine Process Status Tool lists the instrumented HotSpot Java
Virtual Machines (JVMs) on the target system. (experimental)
▪ jrunscript – Java command-line script shell.
▪ jstack – utility that prints Java stack traces of Java threads (experimental)
▪ jstat – Java Virtual Machine statistics monitoring tool (experimental)
2
▪ jstatd – jstat daemon (experimental)
▪ keytool – tool for manipulating the keystore
▪ pack200 – JAR compression tool
▪ policytool – the policy creation and management tool, which can determine policy for a
Java runtime, specifying which permissions are available for code from various sources
▪ VisualVM – visual tool integrating several command-line JDK tools and lightweight
performance and memory profiling capabilities
▪ wsimport – generates portable JAX-WS artifacts for invoking a web service.
▪ xjc – Part of the Java API for XML Binding (JAXB) API. It accepts an XML schema
and generates Java classes.
3
Data Types used in JDK
Each row contains the data type and size and range of the data type. The list of available
data types in Java is shown in table below
Purpose: The PATH environment variable in Windows tells the operating system where to look for
executable files. When you type a command in the command prompt (e.g., java, javac), the system
searches the directories listed in PATH to find the appropriate executable.
For Java: The PATH variable needs to include the directory where the Java executable files ( java,
javac, etc.) are located. This is typically the bin folder inside the JDK installation directory.
How to Set:
1. Right-click "This PC" (or "My Computer") and click "Properties."
2. Click "Advanced system settings" and then "Environment Variables."
3. Under "System Variables," find Path and click "Edit."
4. Add the path to the bin directory of your JDK installation, such as C:\Program
Files\Java\jdk-<version>\bin.
Effect: Once set, you can run Java commands from any directory in the command prompt without
needing to navigate to the bin folder.
Purpose: The CLASSPATH environment variable tells the Java runtime where to look for class files
and JAR files when running or compiling Java programs. By default, Java looks in the current
directory (.) if CLASSPATH is not set.
How to Set:
1. Go to "Environment Variables" as above.
2. Under "System Variables," click "New" and create a variable called CLASSPATH.
3. Set its value to the path where your .class files are located, or the location of any JAR files
you want to include (e.g., C:\myproject\classes).
Effect: This ensures that the Java runtime can find your class files or libraries when executing Java
programs. You can also add multiple directories or JAR files, separated by semicolons ( ;).
4
Update the PATH Environment Variable (Microsoft Windows)
We can run Java applications just fine without setting the PATH environment variable. Or, we
can optionally set it as a convenience.
Set the PATH environment variable if we want to be able to conveniently run the executables
(javac.exe, java.exe, javadoc.exe, and so on) from any directory without having to type the full
path of the command. If we do not set the PATH variable, we need to specify the full path to the
executable every time we run it, such as:
C:\Java\jdk1.7.0\bin\javac MyClass.java
The PATH environment variable is a series of directories separated by semicolons (;). Microsoft
Windows looks for programs in the PATH directories in order, from left to right. We should
have only one bin directory for the JDK in the path at a time (those following the first are
ignored), so if one is already present, we can update that particular entry.
The following is an example of a PATH environment variable:
C:\Java\jdk1.7.0\bin;C:\Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem
It is useful to set the PATH environment variable permanently so it will persist after rebooting.
To make a permanent change to the PATH variable, use the System icon in the Control Panel.
The precise procedure varies depending on the version of Windows:
Windows XP
1. Select Start, select Control Panel. double click System, and select the Advanced
tab.
2. Click Environment Variables. In the section System Variables, find the PATH
environment variable and select it. Click Edit. If the PATH environment variable does
not exist, click New.
3. In the Edit System Variable (or New System Variable) window, specify the value of
the PATH environment variable. Click OK. Close all remaining windows by clicking
OK.
Suggested Reading:
1. Herbert Scheldt, ―The Complete Reference Java, 7th Edition, Tata McGraw Hill,
2006.
2. James M Slack, Programming and Problem Solving with JAVA, Thomson Learning,
2002.
3. C Thomas Wu, An Introduction to Object Oriented Programming with Java 5th
Edition, McGraw Hill Publishing, 2010.
H. M. Dietel and P. J. Dietel, Java How to Program, Sixth Edition, Pearson Education /
PHI
5
Experiment No 1.1
OBJECTIVE
Java program to display Hello java message
Class Declaration:
class Simple: This defines a class named Simple. In Java, all code must be inside a class.
main Method:
public static void main(String args[]): This is the entry point for the program. The main method is
where execution starts when you run the Java program.
public: The method is public, meaning it can be called from anywhere.
static: The method is static, meaning it belongs to the class itself, not an instance of the class.
void: This means the method does not return any value.
String args[]: This is a parameter that can hold command-line arguments, although it isn't
used in this particular program.
class Simple
{
To compile:
javac Simple.java
To execute:
java Simple
Output:
Hello Java
6
Experiment No 1.2
OBJECTIVE
Create a class named 'Student' with String variable 'name' and integer
variable 'roll_no'. Assign the value of roll_no as '2' and that of name as
"John" by creating an object of the class Student.
To compile:
javac Student.java
To execute:
java Student
Output:
Name = John
Roll no = 2
7
Experiment No 2
OBJECTIVE
Print the average of three numbers entered by user by creating a class named
‘Average' which has a method to calculate and print the average.
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scan.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scan.nextDouble();
System.out.print("Enter the third number: ");
double num3 = scan.nextDouble();
scan.close();
System.out.print("The average of entered numbers is:" + avr(num1, num2, num3) );
}
To compile:
javac Test.java
To execute:
java Test
Input:
Enter the first number: 10
Enter the second number: 20
Enter the third number: 30
Output:
The average of entered numbers is: 20.0
8
Experiment No 3
OBJECTIVE
Twin Prime are the prime numbers whose difference is 2 such as (3, 5), (5, 7), (11, 13).
Write a program to display all twin prime numbers from 1 to n. Where n is the last
range that is to be inputted by the user. Methods to be created are:
• prime() – method which will check whether the number is prime or not.
• main() – which will call the prime() method.
The Twin Prime numbers are the two Prime numbers having a difference of 2 between both of them. A
prime having a prime gap of two is referred to as a twin prime. The twin prime term is used for a pair of
twin primes. The twin primes are also known as prime pair or prime twin.
The pair (2, 3) is generally not considered as a pair of twin prime because 2 is the only even prime, and the
pair is the only pair of prime numbers that differ from one.
import java.util.Scanner;
class Test
{
static boolean isPrime(int n)
{
int i;
for(i=2;i<n;i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
public static void main(String[] args)
{
int i,low,upr;
Scanner sc=new Scanner(System.in);
System.out.println("Enter lower limit : ");
low=sc.nextInt();
System.out.println("Enter upper limit : ");
upr=sc.nextInt();
System.out.println("Twin prime number are : ");
for(i=low;i<=upr-2;i++)
{
if(isPrime(i) && isPrime(i+2))
9
System.out.println(i+" "+(i+2));
}
}
}
Input
Enter lower limit :
10
Enter upper limit :
50
Output
Twin prime number are :
11 13
17 19
29 31
41 43
10
Experiment No 4
OBJECTIVE
Write a program to print the area and perimeter of a triangle by creating a class
named 'Triangle' with a Parameterized constructor having the three sides as its
parameters.
Problem Description
Constructors are used to assign initial values to instance variables of the class. A default constructor with
no arguments will be called automatically by the Java Virtual Machine (JVM). Constructor is always
called by new operator. Constructors are declared just like as we declare methods, except that the
constructor doesn‘t have any return type. Constructor can be overloaded provided they should have
different arguments because JVM differentiates constructors on the basis of arguments passed in the
constructor.
// Parameterized constructor
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
11
t.display();
}
}
12
Experiment No 5
OBJECTIVE
Write a program to display the Fibonacci series from 1 to n using a
recursive function. Where n is the last range that is to be inputted by the
user.
In fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8,
13, 21, 34, 55 etc. The first two numbers of fibonacci series are 0 and 1.
import java.io.*;
class Test
{
// Recursive call
return fib(n - 1) + fib(n - 2);
}
// Driver Code
public static void main(String args[])
{
// Given Number N
int N = 10;
Output
0 1 1 2 3 5 8 13 21 34
13
Experiment No 6
OBJECTIVE
Write a Java program to calculate the average value of array elements where
array elements are {20,30,25,25,- 16,60,-100}.
Java Arrays:
Normally, an array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements. We
can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on
1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the
sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an
array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.
14
Instantiation of an Array in Java
int sum = 0;
for (int num : numbers) {
sum += num;
}
// Calculate average
double average = (double) sum / numbers.length;
// Print result
System.out.println("Average value of the array elements is: " + average);
}
}
Output:
15
Experiment No 7
OBJECTIVE
Write a program to print the volume of a Cube, Cuboid, and Sphere by using the
concept of Method Overloading. Create a class named ‘Volume’.
Problem Description
In Java it is possible to define two or more methods within the same class that share the same name, as long
as their parameter declarations are different. When this is the case, the methods are said to be overloaded,
and the process is referred to as method overloading. Method overloading is one of the ways that Java
implements polymorphism.
16
}
}
Output
17
Experiment No 8
OBJECTIVE
Write a program to perform a single inheritance on two classes and also incorporating the
concept of method overriding.
Problem Description
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at
run time, rather than compile time. Dynamic method dispatch is important because this is how Java
implements run-time polymorphism. Let's begin by restating an important principle: a superclass
reference variable can refer to a subclass object.
Java uses this fact to resolve calls to overridden methods at run time. Here is how. When an
overridden method is called through a superclass reference, Java determines which version of that
method to execute based upon the type of the object being referred to at the time the call occurs. Thus,
this determination is made at run time. When different types of objects are referred to, different
versions of an overridden method will be called.
// Parent class
class Animal {
// Method to be overridden
public void sound() {
System.out.println("Animal makes a sound");
}
// Main class
18
public class Main {
public static void main(String[] args) {
// Create object of Dog class
Dog dog = new Dog();
Output:
Dog barks
Animal eats food
Breed: Labrador
19
Experiment No 9
OBJECTIVE
Write a Java program to perform employee payroll processing using
packages. Create a package Employee. In the package create 2 files:
1. Emp.java: Declare the variables name, empid, category, bpay, hra, da, npay, pf,
grosspay, incometax, and allowance. Calculate the values in methods.
2. Emppay.java.: Create an object e to call the methods to perform and print values.
The salary is calculated according to the following rules:
Salary = Basic pay+HRA+DA
HRA = 30% of basic pay
DA = 40% of basic pay
Problem Description
Package is a collection of related classes and interfaces as a single unit.
Package is a folder contains .class files.
It is an Encapsulation mechanism to group related classes and interfaces into a single
unit.
It provides security to the classes and interfaces. So that outside person cannot access
directly.
Predefined packages:-
The java predefined packages are introduced by sun peoples these packages contains predefined
classes and interfaces.
Ex:- java.lang
Java.io
Java.awt
Java.util
Java.net………………………..etc
20
1. Emp.java
This file declares variables and contains methods to calculate HRA, DA, Salary,
etc.
package Employee;
21
System.out.println("Gross Pay : " + grosspay);
System.out.println("Net Pay : " + npay);
System.out.println("==============================================");
}
}
2. Emppay.java
This is the main class which creates an employee object and calls the methods.
package Employee;
// Display payroll
e.display();
}
}
Output:
22
Experiment No 10
OBJECTIVE
Write a Java program that implements a Library Management System with
the following features:
Object-Oriented Programming (OOP): Create a Book class with attributes title and author,
Implement a Library class that manages a collection of books.
File Handling: Implement methods in the Library class to save and load books using serialization.
Exception Handling: Handle exceptions in file operations using try-catch blocks.
Multithreading: Implement a background task using multithreading that runs parallel to user
operations.
User Interaction: Provide a menu-driven interface where users can:
o Add a book (by entering title and author).
o View the list of books.
o Save the book list to a file.
o Load the book list from a file.
o Exit the program
import java.io.*;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
class Library {
private List<Book> books;
public Library() {
books = new CopyOnWriteArrayList<>();
}
23
System.out.println("Book added successfully.");
}
24
backgroundTask.start();
while (true) {
System.out.println("\n--- Library Menu ---");
System.out.println("1. Add a book");
System.out.println("2. View books");
System.out.println("3. Save books to file");
System.out.println("4. Load books from file");
System.out.println("5. Exit");
System.out.print("Choose an option (1-5): ");
case "2":
library.viewBooks();
break;
case "3":
library.saveToFile("library.ser");
break;
case "4":
library.loadFromFile("library.ser");
break;
case "5":
System.out.println("Exiting program. Goodbye!");
return;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
Compile:
javac LibraryManagementSystem.java
Run:
java LibraryManagementSystem
25