Core Java Lab Manual-CS271 (2024-25)
Core Java Lab Manual-CS271 (2024-25)
LAB MANUAL
CS271
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 produce graduates who have strong foundation of knowledge and skills in the
PEO1 field of computer science and engineering.
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
Experiment Objective Page
No. No.
1 Introduction about Java 1-5
2 Create a class named 'Student' with String variable 'name' and integer 6-7
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.
3 Print the average of three numbers entered by user by creating a class 8-9
named 'Average' which has a method to calculate and print the average.
4 Twin Prime are the prime numbers whose difference is 2 such as 10-11
(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. •
show() – which will print the twin prime numbers and will call
the prime() method. • main() – which will call the show() method
5 Write a program to print the area and perimeter of a triangle by creating a 12-14
class named 'Triangle' with a parameterized constructor having the three
sides as its parameters.
6 Write a program to print the volume of a Cube, Cuboid, and Sphere by 15-16
using the concept of Method Overloading. Create a class named ‘Volume’.
7 Write a Java program to calculate the average value of array elements 17
where array elements are {20,30,25,25,- 16,60,-100}
8 Write a Java program for exception handling using a try-catch block 18-19
9 Write a program to display the Fibonacci series from 1 to n using a 20-21
recursive function. Where n is the last range that is to be inputted by the
user.
10 Write a program to perform a single inheritance on two classes. 22-24
11 Write a Java program to perform employee payroll processing using 25-28
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
Introduction TO JAVA Programming Laboratory
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.
1
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
▪ 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
2
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)
▪ 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
After installing the software, the JDK directory will have the structure shown below.
The bin directory contains both the compiler and the launcher.
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\Syste
m32\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 / PH
5
Program 1
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.
In object-oriented programming (OOP), classes and objects are fundamental concepts used
to model real-world entities and their behaviors.
Class
Definition: A class is a blueprint or template for creating objects. It defines the
properties (attributes) and behaviors (methods or functions) that the objects created
from the class will have.
Structure: A class typically contains:
o Attributes: These are variables that hold data related to the class (e.g., name,
roll_no).
o Methods: These are functions that define the behavior of the objects (e.g.,
methods to display information).
Object
Definition: An object is an instance of a class. When a class is defined, no memory is
allocated until an object of that class is created. Objects contain actual values and
represent specific instances of the class.
Characteristics: Each object has its own state (attribute values) and behavior
(methods). Multiple objects can be created from the same class, each with different
attribute values.
6
Program
7
Program 2
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.
Scanner is a class in Java that belongs to the java.util package. It is primarily used for
obtaining input from various sources, including user input from the console, files, and other
input streams.
In the context of OOP in Java, a method is a block of code that performs a specific task.
Methods are associated with classes and define the behaviors of the objects created from
those classes.
Key Features of Methods
1. Encapsulation: Methods help encapsulate the behavior of an object. You can think of
methods as the functions that operate on the data contained in the object.
2. Reusability: Methods allow code reuse. Once a method is defined, it can be called
multiple times, reducing code duplication.
3. Parameters and Return Types:
o Methods can take parameters (inputs) and can return a value.
o They can also be void, meaning they do not return a value.
8
Program
import java.util.Scanner;
class Average {
// Method to calculate and print the average
void calculateAverage(double num1, double num2, double num3) {
double average = (num1 + num2 + num3) / 3;
System.out.println("The average of the three numbers is: " + average);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Creating an object of the Average class
Average avgCalculator = new Average();
// Prompting user for input
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter third number: ");
double num3 = scanner.nextDouble();
// Calling the method to calculate and print the average
avgCalculator.calculateAverage(num1, num2, num3);
// Closing the scanner
scanner.close();
}
}
9
Program 3
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. • show() – which will print the
twin prime numbers and will call the prime() method. • main() – which will call the
show() method .
Twin Prime are the prime numbers whose difference is 2 such as (3, 5), (5, 7), (11, 13).
prime() – method which will check whether the number is prime or not.
It returns false for numbers less than or equal to 1.
For other numbers, it checks divisibility from 2 to the square root of num. If num is divisible
by any of these, it returns false.
show() – which will print the twin prime numbers and will call the prime() method .
This method takes the upper limit n as input.
It iterates through numbers from 2 to n−2n-2n−2 and checks if both i and i + 2 are prime
using the prime() method.
If both are prime, it prints them as a twin prime pair.
10
Program
import java.util.Scanner;
class TwinPrime {
// Method to check if a number is prime
boolean prime(int num) {
if (num <= 1) return false; // 0 and 1 are not prime
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false; // Not prime
}
}
return true; // Prime
}
// Method to print twin prime numbers
void show(int n) {
for (int i = 2; i <= n - 2; i++) {
if (prime(i) && prime(i + 2)) {
System.out.println("(" + i + ", " + (i + 2) + ")");
}
}
}
// Main method
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
TwinPrime twinPrime = new TwinPrime();
System.out.print("Enter the range (n): ");
int n = scanner.nextInt(); // Input the upper limit
System.out.println("Twin prime numbers from 1 to " + n + ":");
twinPrime.show(n); // Call the show method to display twin primes
scanner.close(); // Close the scanner
}
}
11
Program 4
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.
A constructor in Java is a special method that is called when an object of a class is created. It
is used to initialize the object's attributes and to perform any setup steps required for the
object. Constructors have the same name as the class and do not have a return type, not even
void.
Types of Constructors
12
Program
class Triangle {
// Instance variables for the three sides of the triangle
private double side1;
private double side2;
private double side3;
// Parameterized constructor
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
13
public static void main(String[] args) {
// Example sides of the triangle
Triangle triangle = new Triangle(3, 4, 5);
14
Program 5
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’
Method Overloading is a feature in Java that allows a class to have more than one method
with the same name, provided that the methods have different parameter lists. This means
that methods can differ in the number of parameters, types of parameters, or both.
1. Same Method Name: All overloaded methods must have the same name.
2. Different Parameters: Methods must differ in their parameter lists. This can be
achieved by:
o Changing the number of parameters.
o Changing the types of parameters.
o Changing the order of parameters.
3. Return Type: The return type of the overloaded methods can be the same or different.
However, the return type alone cannot be used to distinguish between overloaded
methods.
15
Program
class Volume
{
// Method to calculate the volume of a cube
double calculateVolume(int side)
{
return side * side * side; // Volume = side^3
}
// Cuboid
double cuboidVolume = calculateVolume(4, 5, 6); // Example: length = 4, width = 5,
height = 6
System.out.printf("Volume of the Cuboid: %.2f\n", cuboidVolume);
// Sphere
double sphereVolume = calculateVolume(3, true); // Example: radius = 3
System.out.printf("Volume of the Sphere: %.2f\n", sphereVolume);
}
// Main method
public static void main(String[] args) {
Volume volumeCalculator = new Volume();
volumeCalculator.displayVolume(); // Display the volumes
}
}
16
Program 6
Write a Java program to calculate the average value of array elements where array
elements are {20,30,25,25,- 16,60,-100}
An array in Java is a data structure that can hold a fixed number of values of a single type.
The size of an array is determined when it is created and cannot be changed. Arrays are used
to store multiple values in a single variable instead of declaring separate variables for each
value.
Program
17
Program 7
Exception handling in Java is a mechanism that allows a program to deal with runtime
errors in a controlled way. Instead of crashing when an error occurs, Java provides a
framework to catch exceptions, allowing the program to continue executing or
terminate gracefully.
18
Program
import java.util.InputMismatchException;
import java.util.Scanner;
try {
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
19
Program 8
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
The Fibonacci series is a sequence of numbers where each number (after the first two) is the
sum of the two preceding ones. The series typically starts with 0 and 1, although some
variations start with 1 and 1. The Fibonacci sequence can be expressed mathematically as
follows:
F(0)=0F(0) = 0F(0)=0
F(1)=1F(1) = 1F(1)=1
F(n)=F(n−1)+F(n−2)F(n) = F(n-1) + F(n-2)F(n)=F(n−1)+F(n−2) for n>1n > 1n>1
A recursive function is a function that calls itself in order to solve a problem. This
technique is useful for breaking down complex problems into simpler subproblems. In
recursion, there are typically two components:
1. Base Case: This stops the recursion and prevents an infinite loop. It returns a value
without making any further recursive calls.
2. Recursive Case: This calls the function itself with a modified argument, moving
towards the base case.
20
Program
import java.util.Scanner;
21
Program 9
Single Inheritance:
A derived class inherits from only one base class.
Method Overriding:
A derived class can provide a specific implementation of a method that is already defined in
its base class.
22
Program
// Base class
class Animal
{
String name;
// Constructor
public Animal(String name)
{
this.name = name;
}
// Method
public String speak() {
return "I am an animal.";
}
}
// Derived class
class Dog extends Animal {
String breed;
// Constructor
public Dog(String name, String breed) {
super(name); // Call the constructor of the base class
this.breed = breed;
}
// Overridden method
@Override
public String speak() {
return "Woof! I am a dog.";
}
}
23
// Main class to test the functionality
public class Main {
public static void main(String[] args)
{
Animal myAnimal = new Animal("Generic Animal");
System.out.println(myAnimal.name); // Output: Generic Animal
System.out.println(myAnimal.speak()); // Output: I am an animal.
24
Program 10
In Java, packages are a way to group related classes and interfaces together
Tpes of Packages
1. Built-in Packages:
o Java comes with several built-in packages, such as:
java.lang: Contains fundamental classes like String, Math, etc.
java.util: Contains utility classes like collections, date and time classes,
etc.
java.io: Contains classes for input and output operations.
2. User-defined Packages:
o Developers can create their own packages to group related classes and
interfaces.
25
Program
First, create a directory structure for your package. You can name the root directory as
Employee. Inside this directory, you will create two Java files:
Employee/
Emp.java and Emppay.java.
File 1: Emp.java
package Employee;
// Constructor
26
this.bpay = bpay;
calculatePay();
}
File 2: Emppay.java
package Employee;
27
// Displaying payroll information
e.displayPayroll();
}
}
28