Java Practical
Java Practical
Java Practical
Title
1 Introduction to Java Environment
1. Installation of JDK.
2. Setting of path variable (Temporary and Permanent).
3. Introduction to Java IDE’s.
2 Basic Java Programming
1. Write and execute my first java program.
2. Write a program to print Fibonacci series using java loop.(up to 10 numbers)
3. Write a program to find the largest of 3 numbers.
4. Write a program to find the sum of all integers greater than 40 and less than
250 that are divisible by 5.
3 Basic Java Programming
1. Write a program to input a number of a month (1 - 12) and print its equivalent
name of the month.( e.g 1 to Jan, 2 to Feb. 12 to Dec.) Hint-use switch case
2. Write a program to add two number using command line arguments.
3. Write a program to implement a command line calculator.
4. Write a program that takes student’s info from user(through Scanner class) and
display on output screen. Use appropriate mutator and accessor.
setInfo(),getInfo()
4 Class, Objects and Methods
1. Write a JAVA program to implement class mechanism. – Create a class,
methods and invoke them inside main method.
2. Write a JAVA program to implement compile time polymorphism.
3. Write a JAVA program to implement type promotion in method
overloading.
5 TITLE Inheritance
1. Write a Java program to show that private member of a super class cannot be
accessed from derived classes.
2. Write a program in Java to create a Player class. Inherit the classes Cricket
_Player, Football _Player and Hockey_ Player from Player class.
3. Write a class Worker and derive classes DailyWorker and SalariedWorker
from it. Every worker has a name and a salary rate. Write method ComPay
(int hours) to compute the week pay of every worker. A Daily Worker is
paid on the basis of the number of days he/she works. The Salaried Worker
gets paid the wage for 40 hours a week no matter what the actual hours are.
Test this program to calculate the pay of workers. You are expected to use
the concept of polymorphism to write this program.
4. Design a class employee of an organization. An employee has a name,
empid, and salary. Write the default constructor, a constructor with
parameters (name, empid, and salary) and methods to return name and
salary. Also write a method increaseSalary that raises the employee’s salary
by a certain user specified percentage. Derive a subclass Manager from
employee. Supply a test program that uses theses classes and methods.
6 Interface
1. Write a program to create interface named test. In this interface the member
function is square. Implement this interface in arithmetic class. Create one
new class called ToTestInt. In this class use the object of arithmetic class.
2. Write a program to create interface A, in this interface we have two method
meth1 and meth2. Implements this interface in another class named
MyClass.
3. Implement Multiple and multilevel Inheritance using Interface.
4. Write a program to create an Interface having two methods division and
modules. Create a class, which overrides these methods.
7 Package
1. Write a Java program to implement the concept of importing classes from
user defined package and created packages.
2. Write a program to make a package Balance. This has an Account class with
Display_Balance method. Import Balance package in another program to
access Display_Balance method of Account class.
3. Write a java program that creates a package calculation. Add following classes in it:
a) Addition
b) Subtraction
c) Division
d) Multiplication
Write another Test class, import and use the above package.
8 TITLE: Exceptions
1) Write a program in Java to display the names and roll numbers of students.
Initialize respective array variables for 10 students. Handle
ArrayIndexOutOfBoundsExeption, so that any such problem doesn’t cause
illegal termination of program.
2) Write a Java program to enable the user to handle any chance of divide by zero
exception.
9 TITLE: Threads
1) Write a program to implement the concept of threading by extending Thread
Class and Runnable interface.
2) Write a program to implement the concept of threading by implementing
Runnable interface.
3) Write a program for generating 2 threads, one for printing even numbers and the
other for printing odd numbers.
4) Write a Java program that implement multithreading among 3 threads. use
sleep() and join() methods and show appropriate output.
5) Write a Java program that show multithreading between three threads. Set
different priority to each thread and show output.
3. Write a Java code that converts int to Integer, converts Integer to String, converts
String to int, converts int to String, converts String to Integer converts Integer to int.
4.Write a Java code that converts float to Float converts Float to String converts
String to float converts float to String converts String to Float converts Float to
float.
11 TITLE: JDBC
1) Create a database table to store the records of employee in a company. Use
getConnection function to connect the database. The statement object uses
executeUpdate function to create a table.
2) Create a database of employee of company in mysql and then use java program
to access the database for inserting information of employees in database. The
SQL statement can be used to view the details of the data of employees in the
database.
12 TITLE: JSP/Servlet
1) Write a Servlet page to display current date of the server.
3. Introduction to Java IDEs: Popular Integrated Development Environments (IDEs) for Java
include Eclipse, IntelliJ IDEA, and NetBeans, which provide tools for coding, debugging, and
project management.
Expected Output:
Hello, World!
---
2. Write a Program to Print Fibonacci Series Using a Java Loop (Up to 10 Numbers)
Expected Output:
Fibonacci Series up to 10 terms:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
---
3. Write a Program to Find the Largest of 3 Numbers
import java.util.Scanner;
public class LargestOfThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter third number: ");
int num3 = scanner.nextInt();
int largest = num1;
if (num2 > largest) {
largest = num2;
}
if (num3 > largest) {
largest = num3;
}
System.out.println("The largest number is: " + largest);
}
}
Expected Output:
---
4. Write a Program to Find the Sum of All Integers Greater Than 40 and Less Than 250 That Are
Divisible by 5
public class SumDivisibleByFive {
public static void main(String[] args) {
int sum = 0;
System.out.println("The sum of all integers greater than 40 and less than 250 that are divisible
by 5 is: " + sum);
}
}
Expected Output:
The sum of all integers greater than 40 and less than 250 that are divisible by 5 is: 10385
---
Basic Java Programming
1. Write a program to input a number of a month (1 - 12) and print its equivalent name of the
month.( e.g 1 to Jan, 2 to Feb. 12 to Dec.) Hint-use switch case
2. Write a program to add two number using command line arguments.
3. Write a program to implement a command line calculator.
4. Write a program that takes student’s info from user(through Scanner class) and display on
output screen. Use appropriate mutator and accessor. setInfo(),getInfo()
Here are Java programs for the tasks you specified, including the use of switch statements,
command line arguments, and the Scanner class for user input. Each program is explained step-by-
step.
try {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int sum = num1 + num2;
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
} catch (NumberFormatException e) {
System.out.println("Please enter valid integers.");
}
}
}
Expected Output:
The sum of 5 and 10 is: 15
---
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error: Division by zero.");
return;
}
break;
default:
System.out.println("Invalid operator. Use +, -, *, or /.");
return;
}
---
4. Program to Take Student's Info and Display It Using Mutator and Accessor Methods
import java.util.Scanner;
class Student {
private String name;
private int age;
// Mutator method
public void setInfo(String name, int age) {
this.name = name;
this.age = age;
}
// Accessor method
public String getInfo() {
return "Name: " + name + ", Age: " + age;
}
}
student.setInfo(name, age);
System.out.println("Student Info: " + student.getInfo());
}
}
Expected Output:
Enter student's name: John Doe
Enter student's age: 20
Student Info: Name: John Doe, Age: 20
---
Class, Objects and Methods
1. Write a JAVA program to implement class mechanism. – Create a class, methods and
invoke them inside main method.
2. Write a JAVA program to implement compile time polymorphism.
3. Write a JAVA program to implement type promotion in method overloading.
// Set details
myDog.setDetails("Buddy", 3);
// Display details
myDog.displayDetails();
}
}
Expected Output
Dog's Name: Buddy
Dog's Age: 3 years
---
Expected Output:
Sum of 5 and 10: 15
Sum of 5, 10 and 15: 30
Sum of 5.5 and 10.5: 16.0
---
Expected Output:
Sum of integers: 15
Sum of doubles: 16.0
Sum of int and double: 15.5
---
TITLE Inheritance
1. Write a Java program to show that private member of a super class cannot be accessed
from derived classes.
2. Write a program in Java to create a Player class. Inherit the classes Cricket Player,
Football _Player and Hockey Player from Player class.
3. Write a class Worker and derive classes DailyWorker and SalariedWorker from it. Every
worker has a name and a salary rate. Write method ComPay (int hours) to compute the week pay
of every worker. A Daily Worker is paid on the basis of the number of days he/she works. The
Salaried Worker gets paid the wage for 40 hours a week no matter what the actual hours are. Test
this program to calculate the pay of workers. You are expected to use the concept of polymorphism
to write this program.
4. Design a class employee of an organization. An employee has a name, empid, and salary.
Write the default constructor, a constructor with parameters (name, empid, and salary) and
methods to return name and salary. Also write a method increaseSalary that raises the employee’s
salary by a certain user specified percentage. Derive a subclass Manager from employee. Supply a
test program that uses theses classes and methods.
Here are Java programs that demonstrate the concepts of inheritance, including private member
access, class hierarchies, polymorphism, and constructors.
## 1. Java Program to Show That Private Members of a Superclass Cannot Be Accessed from
Derived Classes
---
## 2. Java Program to Create a Player Class and Inherit CricketPlayer, FootballPlayer, and
HockeyPlayer Classes
Player(String name) {
this.name = name;
}
void display() {
System.out.println("Player Name: " + name);
}
}
void display() {
System.out.println("Cricket Player: " + name);
}
}
void display() {
System.out.println("Football Player: " + name);
}
}
void display() {
System.out.println("Hockey Player: " + name);
}
}
cricketPlayer.display();
footballPlayer.display();
hockeyPlayer.display();
}
}
Expected Output:
Cricket Player: Sachin Tendulkar
Football Player: Lionel Messi
Hockey Player: Wayne Gretzky
---
@Override
double computePay(int days) {
return days * salaryRate;
}
}
@Override
double computePay(int hours) {
return salaryRate * 40; // Fixed pay for 40 hours
}
}
---
4. Java Program to Design an Employee Class and a Manager Subclass
class Employee {
private String name;
private int empId;
private double salary;
// Default constructor
public Employee() {
this.name = "Unknown";
this.empId = 0;
this.salary = 0.0;
}
// Parameterized constructor
public Employee(String name, int empId, double salary) {
this.name = name;
this.empId = empId;
this.salary = salary;
}
public String getName() {
return name;
}
---
Interface
1. Write a program to create interface named test. In this interface the member function is
square. Implement this interface in arithmetic class. Create one new class called ToTestInt. In this
class use the object of arithmetic class.
2. Write a program to create interface A, in this interface we have two method meth1 and
meth2. Implements this interface in another class named MyClass.
3. Implement Multiple and multilevel Inheritance using Interface.
4. Write a program to create an Interface having two methods division and modules. Create a
class, which overrides these methods.
1. Java Program to Create an Interface and Implement It
interface Test {
int square(int num);
}
class Arithmetic implements Test {
@Override
public int square(int num) {
return num * num;
}
}
---
2. Java Program to Create an Interface with Multiple Methods
interface A {
void meth1();
void meth2();
}
---
3. Java Program to Implement Multiple and Multilevel Inheritance Using Interfaces
interface First {
default void display1() {
System.out.println("First interface");
}
}
interface Second {
default void display2() {
System.out.println("Second interface");
}
}
@Override
public void display2() {
System.out.println("Overriding display2() from Second interface");
}
@Override
public void display3() {
System.out.println("Overriding display3() from Third interface");
}
}
---
4. Java Program to Create an Interface with Division and Modulus Methods
interface Operations {
int division(int num1, int num2);
int modulus(int num1, int num2);
}
@Override
public int modulus(int num1, int num2) {
return num1 % num2;
}
}
---
Package
1. Write a Java program to implement the concept of importing classes from user defined
package and created packages.
2. Write a program to make a package Balance. This has an Account class with
Display_Balance method. Import Balance package in another program to access Display_Balance
method of Account class.
3. Write a java program that creates a package calculation. Add following classes in it:
a) Addition
b) Subtraction
c) Division
d) Multiplication
Write another Test class, import and use the above package.
---
2. Java Program to Create a Package Balance with an Account Class
Step 1: Create the Balance Package
// File: Balance/Account.java
package Balance;
// File: calculation/Subtraction.java
package calculation;
---
TITLE: Exceptions
1) Write a program in Java to display the names and roll numbers of students. Initialize
respective array variables for 10 students. Handle ArrayIndexOutOfBoundsExeption, so that any
such problem doesn’t cause illegal termination of program.
2) Write a Java program to enable the user to handle any chance of divide by zero exception.
3) Create an exception class, which throws an exception if operand is nonnumeric in
calculating modules. (Use command line arguments).
1. Java Program to Display Student Names and Roll Numbers with Exception Handling
import java.util.Scanner;
public class StudentDetails {
public static void main(String[] args) {
String[] names = new String[10];
int[] rollNumbers = new int[10];
Student Details:
Student 1: Name = John, Roll Number = 101
...
Student 10: Name = Alice, Roll Number = 110
---
2. Java Program to Handle Divide by Zero Exception
import java.util.Scanner;
public class DivideByZeroExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter numerator: ");
int numerator = scanner.nextInt();
System.out.print("Enter denominator: ");
int denominator = scanner.nextInt();
try {
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
}
}
Expected Output:
Enter numerator: 10
Enter denominator: 0
Error: Division by zero is not allowed.
---
try {
int num1 = Integer.parseInt(args);
int num2 = Integer.parseInt(args);
int result = num1 % num2;
System.out.println("Result of modulus: " + result);
} catch (NumberFormatException e) {
System.out.println("Error: Non-numeric operand provided.");
} catch (NonNumericException e) {
System.out.println(e.getMessage());
}
}
}
Expected Output:
Result of modulus: 1
Expected Output:
Error: Non-numeric operand provided.
---
4. Java Program to Throw Exceptions for Employee Details
class NameException extends Exception {
public NameException(String message) {
super(message);
}
}
class Employee {
private String name;
private int age;
@Override
public String toString() {
return "Employee Name: " + name + ", Age: " + age;
}
}
try {
Employee emp = new Employee("Alice", 55); // This will throw AgeException
System.out.println(emp);
} catch (NameException | AgeException e) {
System.out.println(e.getMessage());
}
try {
Employee emp = new Employee("Bob", 40); // This will succeed
System.out.println(emp);
} catch (NameException | AgeException e) {
System.out.println(e.getMessage());
}
}
}
Expected Output
Error: Employee name cannot contain numbers.
Error: Employee age cannot be greater than 50.
Employee Name: Bob, Age: 40
---
TITLE: Threads
1) Write a program to implement the concept of threading by extending Thread Class and
Runnable interface.
2) Write a program to implement the concept of threading by implementing Runnable
interface.
3) Write a program for generating 2 threads, one for printing even numbers and the other for
printing odd numbers.
4) Write a Java program that implement multithreading among 3 threads. use sleep() and
join() methods and show appropriate output.
5) Write a Java program that show multithreading between three threads. Set different
priority to each thread and show output.
1. Program to Implement Threading by Extending the Thread Class and Implementing the
Runnable Interface
class MyThread extends Thread {
public void run() {
System.out.println("Thread using Thread class is running.");
}
}
thread1.start();
thread2.start();
}
}
Expected Output
Thread using Thread class is running.
Thread using Runnable interface is running.
---
2. Program to Implement Threading by Implementing the Runnable Interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running using Runnable interface.");
}
}
3. Program to Generate Two Threads for Printing Even and Odd Numbers
class EvenThread extends Thread {
public void run() {
for (int i = 0; i <= 10; i += 2) {
System.out.println("Even: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
}
evenThread.start();
oddThread.start();
}
}
Expected Output:
Even: 0
Odd: 1
Even: 2
Odd: 3
---
thread1.start();
try {
thread1.join(); // Wait for thread1 to finish
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
thread2.start();
thread3.start();
}
}
Thread-0 is running.
Thread-0 has finished.
Thread-1 is running.
Thread-1 has finished.
Thread-2 is running.
Thread-2 has finished.
---
5. Java Program to Show Multithreading with Different Priorities
class PriorityThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + " with priority " +
Thread.currentThread().getPriority() + " is running.");
}
}
thread1.setName("Thread 1");
thread2.setName("Thread 2");
thread3.setName("Thread 3");
thread1.setPriority(Thread.MIN_PRIORITY); // 1
thread2.setPriority(Thread.NORM_PRIORITY); // 5
thread3.setPriority(Thread.MAX_PRIORITY); // 10
thread1.start();
thread2.start();
thread3.start();
}
}
Expected Output:
Thread 1 with priority 1 is running.
Thread 2 with priority 5 is running.
Thread 3 with priority 10 is running.
---
3. Write a Java code that converts int to Integer, converts Integer to String, converts String to int,
converts int to String, converts String to Integer converts Integer to int.
4.Write a Java code that converts float to Float converts Float to String converts String to float
converts float to String converts String to Float converts Float to float.
// String toUpperCase()
System.out.println("Uppercase: " + str1.toUpperCase()); // "HELLO"
// int hashCode()
System.out.println("Hash Code: " + str.hashCode());
// String trim()
String trimmed = str.trim();
System.out.println("Trimmed String: '" + trimmed + "'");
// String intern()
String interned = trimmed.intern();
System.out.println("Interned String: '" + interned + "'");
// int length()
System.out.println("Length: " + trimmed.length());
Expected Output:
Hash Code: 1732587
Trimmed String: 'Hello World!'
Interned String: 'Hello World!'
Length: 12
Replaced String: Hell0 W0rld!
Substring (0, 5): Hello
---
3. Java Code for Integer and String Conversions
public class IntegerStringConversion {
public static void main(String[] args) {
// Convert int to Integer
int intValue = 42;
Integer integerValue = Integer.valueOf(intValue);
System.out.println("int to Integer: " + integerValue);
Expected Output:
int to Integer: 42
Integer to String: 42
String to int: 100
int to String: 42
String to Integer: 100
Integer to int: 100
---
2) Create a database of employee of company in mysql and then use java program to access
the database for inserting information of employees in database. The SQL statement can be used to
view the details of the data of employees in the database.
Expected Output:
Table created successfully!
---
if (rowsInserted > 0) {
System.out.println("Employee information inserted successfully!");
} else {
System.out.println("Failed to insert employee information.");
}
---
TITLE: JSP/Servlet
1) Write a Servlet page to display current date of the server.
2) Write a JSP page that display the student information.
*CurrentDateServlet.java*
java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/currentDate")
public class CurrentDateServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Set response content type
response.setContentType("text/html");
1. Make sure you have a web server like Apache Tomcat set up.
2. Place the CurrentDateServlet.java file in the appropriate package directory (e.g.,
src/com/example).
3. Compile the servlet and package it into a WAR file or deploy it directly in the WEB-INF/classes
directory of your web application.
http://localhost:8080/your-web-app/currentDate
Expected Output
Current Date and Time:
Wed Mar 15 12:34:56 UTC 2023
---
2. JSP Page to Display Student Information
Step 1: Create the JSP Page
*studentInfo.jsp*
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Student Information</title>
</head>
<body>
<h1>Student Information</h1>
<%
// Sample student data
String name = "John Doe";
int rollNumber = 12345;
String course = "Computer Science";
double gpa = 3.8;
http://localhost:8080/your-web-app/studentInfo.jsp
Expected Output:
Student Information
Name: John Doe
Roll Number: 12345
Course: Computer Science
GPA: 3.8
---