Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Practical

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 60

Exp No

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.

3) Create an exception class, which throws an exception if operand is nonnumeric


in calculating modules. (Use command line arguments).

4) Write a java program to throw an exception for an employee details.


 If an employee name is a number, a name exception must be thrown.
 If an employee age is greater than 50, an age exception must be thrown.
 Or else an object must be created for the entered employee details

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.

10 TITLE: Strings Handling and Wrapper Class


1. Write Java program using the following string methods:
 String concat(String str)
 boolean equals(Object anObject)
 boolean equalsIgnoreCase(String anotherString)
 String toUpperCase()
 char charAt(int index)
 int compareTo(String anotherString)

2. Write Java program using the following string methods:


 int hashCode()
 String trim()
 String intern()
 int length()
 String replace(char oldChar, char newChar)
 String substring(int beginIndex, int endIndex)

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.

2) Write a JSP page that display the student information.


Introduction to Java Environment
1. Installation of JDK*: Download the Java Development Kit (JDK) from the official Oracle
website and run the installer, following the prompts to complete the installation[4][5].

2. Setting the Path Variable*:


- Temporary: Open Command Prompt and use set PATH=%PATH%;C:\Program Files\Java\
jdk\bin (adjust the path as necessary).
- Permanent: Go to Control Panel > System > Advanced System Settings > Environment
Variables. Edit the "Path" variable to include the JDK path.

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.

Basic Java Programming


Here's a guide to writing and executing basic Java programs, along with examples for each of your
requests.

1. Write and Execute My First Java Program


1. Create a Java File: Open your IDE or a text editor and create a new file named HelloWorld.java.

2. Write the Code:


java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
3. Compile the Program: Open a command prompt or terminal, navigate to the directory where
your file is saved, and run:
bash
javac HelloWorld.java

4. Execute the Program: After compilation, run the program using:


bash
java HelloWorld

Expected Output:

Hello, World!

---

2. Write a Program to Print Fibonacci Series Using a Java Loop (Up to 10 Numbers)

public class Fibonacci {


public static void main(String[] args) {
int n = 10, firstTerm = 0, secondTerm = 1;

System.out.println("Fibonacci Series up to " + n + " terms:");

for (int i = 1; i <= n; ++i) {


System.out.print(firstTerm + ", ");
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}

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:

Enter first number: 10


Enter second number: 20
Enter third number: 15
The largest number is: 20

---

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;

for (int i = 41; i < 250; i++) {


if (i % 5 == 0) {
sum += i;
}
}

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.

1. Program to Input a Month Number and Print Its Equivalent Name


import java.util.Scanner;
public class MonthName {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a month number (1-12): ");
int month = scanner.nextInt();
String monthName;
switch (month) {
case 1: monthName = "January"; break;
case 2: monthName = "February"; break;
case 3: monthName = "March"; break;
case 4: monthName = "April"; break;
case 5: monthName = "May"; break;
case 6: monthName = "June"; break;
case 7: monthName = "July"; break;
case 8: monthName = "August"; break;
case 9: monthName = "September"; break;
case 10: monthName = "October"; break;
case 11: monthName = "November"; break;
case 12: monthName = "December"; break;
default: monthName = "Invalid month number!";
}
System.out.println("The month is: " + monthName);
}
}
Expected Output:
Enter a month number (1-12): 3
The month is: March
---

2. Program to Add Two Numbers Using Command Line Arguments


public class AddTwoNumbers {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide two numbers as command line arguments.");
return;
}

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

---

3. Program to Implement a Command Line Calculator


public class CommandLineCalculator {
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: java CommandLineCalculator <num1> <operator> <num2>");
return;
}

double num1 = Double.parseDouble(args[0]);


String operator = args[1];
double num2 = Double.parseDouble(args[2]);
double result;

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;
}

System.out.println("Result: " + result);


}
}
Expected Output
Result: 15.0

---

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;
}
}

public class StudentInfo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student student = new Student();

System.out.print("Enter student's name: ");


String name = scanner.nextLine();
System.out.print("Enter student's age: ");
int age = scanner.nextInt();

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.

1. Java Program to Implement Class Mechanism


class Dog {
// Attributes
String name;
int age;

// Method to set dog details


void setDetails(String name, int age) {
this.name = name;
this.age = age;
}

// Method to display dog details


void displayDetails() {
System.out.println("Dog's Name: " + name);
System.out.println("Dog's Age: " + age + " years");
}
}

public class ClassMechanism {


public static void main(String[] args) {
// Create an object of Dog class
Dog myDog = new Dog();

// Set details
myDog.setDetails("Buddy", 3);

// Display details
myDog.displayDetails();
}
}
Expected Output
Dog's Name: Buddy
Dog's Age: 3 years

---

2. Java Program to Implement Compile-Time Polymorphism


class MathOperations {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two double values
double add(double a, double b) {
return a + b;
}
}
public class CompileTimePolymorphism {
public static void main(String[] args) {
MathOperations math = new MathOperations();

// Calling the add method with different parameters


System.out.println("Sum of 5 and 10: " + math.add(5, 10)); // Calls int add(int, int)
System.out.println("Sum of 5, 10 and 15: " + math.add(5, 10, 15)); // Calls int add(int, int,
int)
System.out.println("Sum of 5.5 and 10.5: " + math.add(5.5, 10.5)); // Calls double
add(double, double)
}
}

Expected Output:
Sum of 5 and 10: 15
Sum of 5, 10 and 15: 30
Sum of 5.5 and 10.5: 16.0
---

3. Java Program to Implement Type Promotion in Method Overloading


class TypePromotion {
// Method to add two integers
void add(int a, int b) {
System.out.println("Sum of integers: " + (a + b));
}
// Method to add two double values
void add(double a, double b) {
System.out.println("Sum of doubles: " + (a + b));
}
// Method to add an integer and a double
void add(int a, double b) {
System.out.println("Sum of int and double: " + (a + b));
}
}

public class TypePromotionExample {


public static void main(String[] args) {
TypePromotion tp = new TypePromotion();

// Calling the add method with different types


tp.add(5, 10); // Calls add(int, int)
tp.add(5.5, 10.5); // Calls add(double, double)
tp.add(5, 10.5); // Calls add(int, double)
}
}

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

### Code Example


java
class SuperClass {
private int privateVariable = 10;

public int getPrivateVariable() {


return privateVariable;
}
}

class SubClass extends SuperClass {


void display() {
// Cannot access privateVariable directly
// System.out.println(privateVariable); // This would cause an error
System.out.println("Accessing private variable through getter: " + getPrivateVariable());
}
}
public class InheritanceExample1 {
public static void main(String[] args) {
SubClass obj = new SubClass();
obj.display();
}
}

### Expected Output

Accessing private variable through getter: 10

---

## 2. Java Program to Create a Player Class and Inherit CricketPlayer, FootballPlayer, and
HockeyPlayer Classes

### Code Example


java
class Player {
String name;

Player(String name) {
this.name = name;
}

void display() {
System.out.println("Player Name: " + name);
}
}

class CricketPlayer extends Player {


CricketPlayer(String name) {
super(name);
}

void display() {
System.out.println("Cricket Player: " + name);
}
}

class FootballPlayer extends Player {


FootballPlayer(String name) {
super(name);
}

void display() {
System.out.println("Football Player: " + name);
}
}

class HockeyPlayer extends Player {


HockeyPlayer(String name) {
super(name);
}

void display() {
System.out.println("Hockey Player: " + name);
}
}

public class InheritanceExample2 {


public static void main(String[] args) {
Player cricketPlayer = new CricketPlayer("Sachin Tendulkar");
Player footballPlayer = new FootballPlayer("Lionel Messi");
Player hockeyPlayer = new HockeyPlayer("Wayne Gretzky");

cricketPlayer.display();
footballPlayer.display();
hockeyPlayer.display();
}
}
Expected Output:
Cricket Player: Sachin Tendulkar
Football Player: Lionel Messi
Hockey Player: Wayne Gretzky

---

3. Java Program to Implement Worker Classes with Polymorphism


abstract class Worker {
String name;
double salaryRate;

Worker(String name, double salaryRate) {


this.name = name;
this.salaryRate = salaryRate;
}
abstract double computePay(int hours);
}

class DailyWorker extends Worker {


DailyWorker(String name, double salaryRate) {
super(name, salaryRate);
}

@Override
double computePay(int days) {
return days * salaryRate;
}
}

class SalariedWorker extends Worker {


SalariedWorker(String name, double salaryRate) {
super(name, salaryRate);
}

@Override
double computePay(int hours) {
return salaryRate * 40; // Fixed pay for 40 hours
}
}

public class InheritanceExample3 {


public static void main(String[] args) {
Worker dailyWorker = new DailyWorker("Alice", 100.0);
Worker salariedWorker = new SalariedWorker("Bob", 1500.0);
System.out.println("Daily Worker Pay for 5 days: " + dailyWorker.computePay(5));
System.out.println("Salaried Worker Pay for 40 hours: " + salariedWorker.computePay(40));
}
}
Expected Output:
Daily Worker Pay for 5 days: 500.0
Salaried Worker Pay for 40 hours: 1500.0

---
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;
}

public double getSalary() {


return salary;
}

public void increaseSalary(double percentage) {


salary += salary * (percentage / 100);
}
}

class Manager extends Employee {


private String department;

public Manager(String name, int empId, double salary, String department) {


super(name, empId, salary);
this.department = department;
}

public void displayInfo() {


System.out.println("Manager Name: " + getName());
System.out.println("Employee ID: " + empId);
System.out.println("Salary: " + getSalary());
System.out.println("Department: " + department);
}
}
public class InheritanceExample4 {
public static void main(String[] args) {
Manager manager = new Manager("John Doe", 101, 75000, "Sales");
manager.displayInfo();

// Increase salary by 10%


manager.increaseSalary(10);
System.out.println("New Salary after increase: " + manager.getSalary());
}
}
Expected Output:
Manager Name: John Doe
Employee ID: 101
Salary: 75000.0
Department: Sales
New Salary after increase: 82500.0

---
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;
}
}

public class ToTestInt {


public static void main(String[] args) {
Arithmetic obj = new Arithmetic();
int result = obj.square(5);
System.out.println("The square of 5 is: " + result);
}
}
Expected Output:
The square of 5 is: 25

---
2. Java Program to Create an Interface with Multiple Methods
interface A {
void meth1();
void meth2();
}

class MyClass implements A {


@Override
public void meth1() {
System.out.println("Implementing meth1()");
}
@Override
public void meth2() {
System.out.println("Implementing meth2()");
}
}

public class InterfaceExample2 {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.meth1();
obj.meth2();
}
}
Expected Output:
Implementing meth1()
Implementing 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");
}
}

interface Third extends First, Second {


default void display3() {
System.out.println("Third interface");
}
}

class MyClass implements Third {


@Override
public void display1() {
System.out.println("Overriding display1() from First 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");
}
}

public class InterfaceExample3 {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display1();
obj.display2();
obj.display3();
}
}
Expected Output:
Overriding display1() from First interface
Overriding display2() from Second interface
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);
}

class MyClass implements Operations {


@Override
public int division(int num1, int num2) {
return num1 / num2;
}

@Override
public int modulus(int num1, int num2) {
return num1 % num2;
}
}

public class InterfaceExample4 {


public static void main(String[] args) {
MyClass obj = new MyClass();
int result1 = obj.division(20, 4);
int result2 = obj.modulus(20, 4);
System.out.println("Division: " + result1);
System.out.println("Modulus: " + result2);
}
}
Expected Output:
Division: 5
Modulus: 0

---
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.

1. Java Program to Implement Importing Classes from a User-Defined Package

Step 1: Create a Package


1. Create a directory structure for your package. For example, create a directory named
mypackage.

2. Inside mypackage, create a Java file named MyClass.java.


// File: mypackage/MyClass.java
package mypackage;

public class MyClass {


public void display() {
System.out.println("Hello from MyClass in mypackage!");
}
}
Step 2: Create a Main Class to Use the Package

3. Create another Java file named TestPackage.java in the parent directory.


// File: TestPackage.java
import mypackage.MyClass;

public class TestPackage {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
Step 3: Compile and Run the Program
Expected Output:
Hello from MyClass in mypackage!

---
2. Java Program to Create a Package Balance with an Account Class
Step 1: Create the Balance Package

1. Create a directory named Balance.

2. Inside Balance, create a Java file named Account.java.

// File: Balance/Account.java
package Balance;

public class Account {


private double balance;

public Account(double balance) {


this.balance = balance;
}

public void displayBalance() {


System.out.println("Current Balance: $" + balance);
}
}
Step 2: Create a Main Class to Use the Balance Package

3. Create another Java file named TestBalance.java in the parent directory.


// File: TestBalance.java
import Balance.Account;

public class TestBalance {


public static void main(String[] args) {
Account myAccount = new Account(500.0);
myAccount.displayBalance();
}
}
Step 3: Compile and Run the Program
Expected Output:
Current Balance: $500.0
---

3. Java Program to Create a Package Calculation with Various Classes

Step 1: Create the Calculation Package

1. Create a directory named calculation.

2. Inside calculation, create the following Java files:


// File: calculation/Addition.java
package calculation;

public class Addition {


public int add(int a, int b) {
return a + b;
}
}

// File: calculation/Subtraction.java
package calculation;

public class Subtraction {


public int subtract(int a, int b) {
return a - b;
}
}
// File: calculation/Multiplication.java
package calculation;
public class Multiplication {
public int multiply(int a, int b) {
return a * b;
}
}
// File: calculation/Division.java
package calculation;

public class Division {


public double divide(int a, int b) {
if (b != 0) {
return (double) a / b;
} else {
throw new ArithmeticException("Division by zero is not allowed.");
}
}
}
Step 2: Create a Test Class to Use the Calculation Package

3. Create another Java file named TestCalculation.java in the parent directory.


// File: TestCalculation.java
import calculation.Addition;
import calculation.Subtraction;
import calculation.Multiplication;
import calculation.Division;
public class TestCalculation {
public static void main(String[] args) {
Addition add = new Addition();
Subtraction sub = new Subtraction();
Multiplication mul = new Multiplication();
Division div = new Division();

System.out.println("Addition: " + add.add(10, 5));


System.out.println("Subtraction: " + sub.subtract(10, 5));
System.out.println("Multiplication: " + mul.multiply(10, 5));
System.out.println("Division: " + div.divide(10, 5));
}
}

Step 3: Compile and Run the Program


Expected Output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0

---
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).

4) Write a java program to throw an exception for an employee details.


• If an employee name is a number, a name exception must be thrown.
• If an employee age is greater than 50, an age exception must be thrown.
• Or else an object must be created for the entered employee details

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];

Scanner scanner = new Scanner(System.in);

// Input student names and roll numbers


for (int i = 0; i < 10; i++) {
try {
System.out.print("Enter name for student " + (i + 1) + ": ");
names[i] = scanner.nextLine();
System.out.print("Enter roll number for student " + (i + 1) + ": ");
rollNumbers[i] = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: You can only enter details for 10 students.");
break;
}
}
// Display student details
System.out.println("\nStudent Details:");
for (int i = 0; i < names.length; i++) {
try {
System.out.println("Student " + (i + 1) + ": Name = " + names[i] + ", Roll Number = " +
rollNumbers[i]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("No more students to display.");
break;
}
}
}
}
Expected Output:
Enter name for student 1: John
Enter roll number for student 1: 101
...
Enter name for student 10: Alice
Enter roll number for student 10: 110

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.

---

3. Custom Exception Class for Non-Numeric Operand in Command Line Arguments


class NonNumericException extends Exception {
public NonNumericException(String message) {
super(message);
}
}

public class ModulusCalculator {


public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide two numeric operands.");
return;
}

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 AgeException extends Exception {


public AgeException(String message) {
super(message);
}
}

class Employee {
private String name;
private int age;

public Employee(String name, int age) throws NameException, AgeException {


if (name.matches(".\\d.")) {
throw new NameException("Error: Employee name cannot contain numbers.");
}
if (age > 50) {
throw new AgeException("Error: Employee age cannot be greater than 50.");
}
this.name = name;
this.age = age;
}

@Override
public String toString() {
return "Employee Name: " + name + ", Age: " + age;
}
}

public class EmployeeDetails {


public static void main(String[] args) {
try {
Employee emp = new Employee("John123", 30); // This will throw NameException
System.out.println(emp);
} catch (NameException | AgeException e) {
System.out.println(e.getMessage());
}

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.");
}
}

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread using Runnable interface is running.");
}
}

public class ThreadExample {


public static void main(String[] args) {
MyThread thread1 = new MyThread();
Thread thread2 = new Thread(new MyRunnable());

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.");
}
}

public class RunnableExample {


public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
Expected Output
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());
}
}
}
}

class OddThread extends Thread {


public void run() {
for (int i = 1; i <= 10; i += 2) {
System.out.println("Odd: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
}
public class EvenOddThreadExample {
public static void main(String[] args) {
EvenThread evenThread = new EvenThread();
OddThread oddThread = new OddThread();

evenThread.start();
oddThread.start();
}
}
Expected Output:
Even: 0
Odd: 1
Even: 2
Odd: 3

---

4. Java Program to Implement Multithreading with Sleep() and Join() Methods


class MyThread extends Thread {
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " is running.");
Thread.sleep(1000); // Sleep for 1 second
System.out.println(Thread.currentThread().getName() + " has finished.");
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
public class MultithreadingExample {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
MyThread thread3 = new MyThread();

thread1.start();
try {
thread1.join(); // Wait for thread1 to finish
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}

thread2.start();
thread3.start();
}
}

### Expected Output

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.");
}
}

public class ThreadPriorityExample {


public static void main(String[] args) {
PriorityThread thread1 = new PriorityThread();
PriorityThread thread2 = new PriorityThread();
PriorityThread thread3 = new PriorityThread();

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.
---

TITLE: Strings Handling and Wrapper Class


1. Write Java program using the following string methods:
• String concat(String str)
• boolean equals(Object anObject)
• boolean equalsIgnoreCase(String anotherString)
• String toUpperCase()
• char charAt(int index)
• int compareTo(String anotherString)

2. Write Java program using the following string methods:


• int hashCode()
• String trim()
• String intern()
• int length()
• String replace(char oldChar, char newChar)
• String substring(int beginIndex, int endIndex)

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.

1. Java Program Using Various String Methods


public class StringMethodsExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
// String concat(String str)
String concatenated = str1.concat(" ").concat(str2);
System.out.println("Concatenated String: " + concatenated);

// boolean equals(Object anObject)


System.out.println("Equals: " + str1.equals("Hello")); // true

// boolean equalsIgnoreCase(String anotherString)


System.out.println("Equals Ignore Case: " + str1.equalsIgnoreCase("hello")); // true

// String toUpperCase()
System.out.println("Uppercase: " + str1.toUpperCase()); // "HELLO"

// char charAt(int index)


System.out.println("Character at index 1: " + str1.charAt(1)); // 'e'

// int compareTo(String anotherString)


System.out.println("Compare To: " + str1.compareTo(str2)); // negative value because
"Hello" < "World"
}
}
Expected Output:
Concatenated String: Hello World
Equals: true
Equals Ignore Case: true
Uppercase: HELLO
Character at index 1: e
Compare To: -15
---

2. Java Program Using Additional String Methods

public class StringMethodsExample2 {


public static void main(String[] args) {
String str = " Hello World! ";

// 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());

// String replace(char oldChar, char newChar)


String replaced = trimmed.replace('o', '0');
System.out.println("Replaced String: " + replaced);

// String substring(int beginIndex, int endIndex)


String substring = trimmed.substring(0, 5);
System.out.println("Substring (0, 5): " + substring);
}
}

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);

// Convert Integer to String


String stringValueFromInteger = integerValue.toString();
System.out.println("Integer to String: " + stringValueFromInteger);

// Convert String to int


String stringValue = "100";
int intValueFromString = Integer.parseInt(stringValue);
System.out.println("String to int: " + intValueFromString);
// Convert int to String
String stringValueFromInt = String.valueOf(intValue);
System.out.println("int to String: " + stringValueFromInt);

// Convert String to Integer


Integer integerValueFromString = Integer.valueOf(stringValue);
System.out.println("String to Integer: " + integerValueFromString);

// Convert Integer to int


int intValueFromInteger = integerValueFromString.intValue();
System.out.println("Integer to int: " + intValueFromInteger);
}
}

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

---

4. Java Code for Float and String Conversions


public class FloatStringConversion {
public static void main(String[] args) {
// Convert float to Float
float floatValue = 3.14f;
Float floatObject = Float.valueOf(floatValue);
System.out.println("float to Float: " + floatObject);

// Convert Float to String


String stringFromFloat = floatObject.toString();
System.out.println("Float to String: " + stringFromFloat);

// Convert String to float


String floatString = "2.71";
float floatValueFromString = Float.parseFloat(floatString);
System.out.println("String to float: " + floatValueFromString);

// Convert float to String


String stringFromPrimitiveFloat = String.valueOf(floatValue);
System.out.println("float to String: " + stringFromPrimitiveFloat);

// Convert String to Float


Float floatObjectFromString = Float.valueOf(floatString);
System.out.println("String to Float: " + floatObjectFromString);

// Convert Float to float


float floatValueFromObject = floatObjectFromString.floatValue();
System.out.println("Float to float: " + floatValueFromObject);
}
}
Expected Output:
float to Float: 3.14
Float to String: 3.14
String to float: 2.71
float to String: 3.14
String to Float: 2.71
Float to float: 2.71
---
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.

1. Java Program to Create a Database Table Using JDBC


import java.sql.*;
public class CreateTableExample {
public static void main(String[] args) {
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Get the connection to the database


Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/company", "username", "password");

// Create a statement object


Statement statement = connection.createStatement();

// SQL statement to create the table


String sql = "CREATE TABLE Employees (" +
"id INT AUTO_INCREMENT PRIMARY KEY," +
"name VARCHAR(50) NOT NULL," +
"department VARCHAR(50)," +
"salary DOUBLE)";

// Execute the SQL statement


statement.executeUpdate(sql);

System.out.println("Table created successfully!");

// Close the connection


connection.close();
} catch (ClassNotFoundException e) {
System.out.println("MySQL JDBC driver not found.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("SQL exception occurred.");
e.printStackTrace();
}
}
}

Expected Output:
Table created successfully!

---

2. Java Program to Insert Employee Information into the Database


import java.sql.*;
public class InsertEmployeeExample {
public static void main(String[] args) {
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Get the connection to the database


Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/company", "username", "password");

// Create a statement object


Statement statement = connection.createStatement();

// SQL statement to insert employee information


String sql = "INSERT INTO Employees (name, department, salary) " +
"VALUES ('John Doe', 'IT', 5000.0)";

// Execute the SQL statement


int rowsInserted = statement.executeUpdate(sql);

if (rowsInserted > 0) {
System.out.println("Employee information inserted successfully!");
} else {
System.out.println("Failed to insert employee information.");
}

// SQL statement to retrieve employee information


sql = "SELECT * FROM Employees";

// Execute the SQL statement


ResultSet resultSet = statement.executeQuery(sql);
// Display the employee information
System.out.println("Employee Details:");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String department = resultSet.getString("department");
double salary = resultSet.getDouble("salary");
System.out.println("ID: " + id + ", Name: " + name + ", Department: " + department + ",
Salary: " + salary);
}
// Close the connection
connection.close();
} catch (ClassNotFoundException e) {
System.out.println("MySQL JDBC driver not found.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("SQL exception occurred.");
e.printStackTrace();
}
}
}
Expected Output:
Employee information inserted successfully!
Employee Details:
ID: 1, Name: John Doe, Department: IT, Salary: 5000.0

---
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.

1. Servlet to Display Current Date of the Server

Step 1: Create the Servlet

*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");

// Get the current date


Date currentDate = new Date();

// Get the PrintWriter to write the response


PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Current Date and Time:</h1>");
out.println("<p>" + currentDate.toString() + "</p>");
out.println("</body></html>");
}
}

Step 2: Configure the Web Application

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.

Step 3: Access the Servlet

- Start your server and access the servlet by navigating to:

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;

// Display student information


%>
<p>Name: <%= name %></p>
<p>Roll Number: <%= rollNumber %></p>
<p>Course: <%= course %></p>
<p>GPA: <%= gpa %></p>
</body>
</html>

Step 2: Deploy the JSP Page


1. Place the studentInfo.jsp file in the root directory of your web application or in the WEB-INF
directory if you want to restrict direct access.
2. Make sure your web server (like Apache Tomcat) is running.

Step 3: Access the JSP Page

- Open your web browser and navigate to:

http://localhost:8080/your-web-app/studentInfo.jsp

Expected Output:
Student Information
Name: John Doe
Roll Number: 12345
Course: Computer Science
GPA: 3.8

---

You might also like