0% found this document useful (0 votes)
6 views52 pages

2 Java Record Program Single Side Print

The document outlines the Java Programming Lab course at Nehru Institute of Technology, detailing various experiments and their objectives. It includes instructions for writing and executing Java programs, implementing control structures, arrays, and classes. Each experiment concludes with a result statement confirming successful implementation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views52 pages

2 Java Record Program Single Side Print

The document outlines the Java Programming Lab course at Nehru Institute of Technology, detailing various experiments and their objectives. It includes instructions for writing and executing Java programs, implementing control structures, arrays, and classes. Each experiment concludes with a result statement confirming successful implementation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Nehru Institute of Technology

(Autonomous)
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC with Section 2(f), Accredited by NAAC with A+, NBA Accredited

U23CS312 - JAVA PROGRAMMING LAB

Certified that this is the bonafide record of work done by …..…………..……………………..

in the………………………………………………………………………………laboratory of

this institution, as prescribed by the Autonomous Regulation …………………..for

the………………… Semester B.E/[Link]., during the academic year …………………..

Faculty in-charge: HOD:

Date: Date:

Register No :

Submitted for the (……………………………………………………..) B.E/[Link].,

Examination Practical conducted on………………………………………………..

Internal Examiner External Examiner


Nehru Institute of Technology
(Autonomous)
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC with Section 2(f), Accredited by NAAC with A+, NBA Accredited

INDEX
Pg
[Link]. DATE EXPERIMENT NAME MARK SIGN
No.

BRANCHING AND LOOPING STATEMENTS

ARRAYI IMPLEMENTATION

INHERITANCE
Nehru Institute of Technology
(Autonomous)
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC with Section 2(f), Accredited by NAAC with A+, NBA Accredited

FILE OPERATIONS

NETWORKING USING SOCKETS

Average

Observation Record Total


(50) (25) (75)

Signature
U23CS312-Java Lab

Exp No:

Writing and executing Java programs in Eclipse


Date:

AIM:
To study and understand how to write and execute Java programs using Eclipse.
Step 1: Open Eclipse and click File > New > Java Project

1
U23CS312-Java Lab

Step 2: Provide the Project Name and click on the Finish button.

2
U23CS312-Java Lab

Step 3: In the Package Explorer (left-hand side of the window) select the project which
you have created.

Step 4: Right-click on the src folder, select New > Class from the submenu. Provide
the Class name and click on Finish button.

Step 5: Write the program and save it.

3
U23CS312-Java Lab

Step 6: Now, press Ctrl+F11 or click on the Run menu and select Run or click on Run
button.

Step 7: Output

RESULT:

Thus, writing and executing Java program in Eclipse has been studied successfully.

4
U23CS312-Java Lab

Exp No:

Java Program to implement if and if-else


Date:

AIM:
To write a Java program to implement exception handling

ALGORITHM:
STEP 1: Start
STEP 2: Create a BufferedReader object to read input from the user.
STEP 3: Prompt the user to enter a number.
STEP 4: Read the input as a string using [Link]().
STEP 5: Convert the string input to an integer using [Link](input).
STEP 6: Check if the number is divisible by 2 (i.e., number % 2 == 0).
STEP 7: If the number is divisible by 2, print that the number is even.
STEP 8: Otherwise, print that the number is odd.
STEP 9: Handle possible IOException by printing an error message if input reading fails.
STEP 10: Handle NumberFormatException by printing an error message if the input is not
a valid integer.
STEP 11: Stop

PROGRAM:

import [Link];
import [Link];
import [Link];
public class OddEvenCheckerIOStream {
public static void main(String[] args) {
// Create BufferedReader object to read input from InputStream
BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));
try {
// Prompt the user to enter a number

5
U23CS312-Java Lab

[Link]("Enter a number: ");


String input = [Link](); // Reading the input as a string
int number = [Link](input); // Converting the string input to an integer
// Check if the number is even or odd
if (number % 2 == 0) {
[Link](number + " is an even number.");
} else {
[Link](number + " is an odd number.");
}
} catch (IOException e) {
[Link]("An error occurred while reading input.");
[Link]();
} catch (NumberFormatException e) {
[Link]("Invalid input. Please enter a valid integer.");
}
}
}

RESULT:

Thus, if-else statement in Java was implemented successfully

6
U23CS312-Java Lab

Exp No:
Java Program to implement for loop
Date:

AIM:
To write, a Java program to implement for loop

ALGORITHM:
STEP 1: Start
STEP 2: Create a Scanner object to read user input.
STEP 3: Prompt the user to enter a number (n).
STEP 4: Read the input number using [Link]().
STEP 5: Print the message "Numbers from 1 to n:".
STEP 6: Initialize a for loop with the loop variable i starting at 1, and continue looping
until i is less than or equal to n.
STEP 7: Inside the loop, print the current value of i.
STEP 8: Increment i by 1 after each iteration.
STEP 9: After the loop finishes, close the Scanner object to release resources.
STEP 10: Stop

PROGRAM:

import [Link];
public class ForLoopExample {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner([Link]);
// Prompt the user to enter a number
[Link]("Enter a number: ");
int n = [Link]();

// Example of a for loop: Print numbers from 1 to n


[Link]("Numbers from 1 to " + n + ":");

7
U23CS312-Java Lab

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


[Link](i);
}
// Close the scanner
[Link]();
}
}

RESULT:
Thus, for loop in Java was implemented successfully

8
U23CS312-Java Lab

Exp No:
Java Program to implement while loop
Date:

AIM:
To write a Java program to implement while loop

ALGORITHM:
STEP 1: Start
STEP 2: Create a Scanner object to read user input.
STEP 3: Prompt the user to enter a number (n).
STEP 4: Read the input number using [Link]().
STEP 5: Initialize a counter variable i to 1.
STEP 6: Print the message "Numbers from 1 to n:".
STEP 7: Start a while loop that continues as long as i is less than or equal to n.
STEP 8: Inside the loop, print the current value of i.
STEP 9: Increment i by 1 after each iteration.
STEP 10: When the loop ends, close the Scanner object to release resources.
STEP 11: Stop

PROGRAM:

import [Link];
public class WhileLoopExample {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner([Link]);
// Prompt the user to enter a number
[Link]("Enter a number: ");
int n = [Link]();
// Initialize the counter
int i = 1;

9
U23CS312-Java Lab

// Example of a while loop: Print numbers from 1 to n


[Link]("Numbers from 1 to " + n + ":");
while (i <= n) {
[Link](i);
i++; // Increment the counter
}
// Close the scanner
[Link]();
}
}

RESULT:
Thus, while loop in Java was implemented successfully

10
U23CS312-Java Lab

Exp No:
Java Program to implement simple array
Date:

AIM:
To write a Java program to implement simple array

ALGORITHM:

STEP 1: Start
STEP 2: Create a Scanner to read input.
STEP 3: Ask the user for the number of elements in the array.
STEP 4: Read the size of the array from the user.
STEP 5: Declare an array to hold the numbers.
STEP 6: Use a loop to get each element from the user and store it in the array.
STEP 7: Use a loop to print all the elements in the array.
STEP 8: Close the Scanner.
STEP 9: Stop

PROGRAM:

import [Link];
public class SimpleArrayExample {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner([Link]);
// Prompt the user to enter the size of the array
[Link]("Enter the number of elements in the array: ");
int size = [Link]();
// Declare an array to store the user input
int[] numbers = new int[size];
// Loop to get input from the user

11
U23CS312-Java Lab

[Link]("Enter " + size + " elements:");


for (int i = 0; i < size; i++) {
[Link]("Element " + (i + 1) + ": ");
numbers[i] = [Link]();
}
// Display the elements entered by the user
[Link]("The elements in the array are:");
for (int i = 0; i < size; i++) {
[Link]("Element " + (i + 1) + ": " + numbers[i]);
}
// Close the scanner
[Link]();
}
}

RESULT:
Thus, simple array in Java was implemented successfully

12
U23CS312-Java Lab

Exp No:
Java Program to implement 2-Dimensional array
Date:

AIM:
To write a Java program to implement 2-Dimensional array

ALGORITHM:
STEP 1: Start
STEP 2: Create a Scanner to read user input.
STEP 3: Ask the user for the number of rows and columns of the first matrix.
STEP 4: Ask the user for the number of rows and columns of the second matrix.
STEP 5: Check if matrix multiplication is possible (i.e., the number of columns of the first
matrix must equal the number of rows of the second matrix).

• If not: Print an error message and stop.


STEP 6: Declare two matrices (matrix1 and matrix2) and a result matrix.
STEP 7: Use loops to get the elements of the first matrix from the user.
STEP 8: Use loops to get the elements of the second matrix from the user.
STEP 9: Perform matrix multiplication using nested loops:

• Multiply elements and store the result in the result matrix.


STEP 10: Display the result matrix.
STEP 11: Close the Scanner.
STEP 12: Stop

PROGRAM:

import [Link];
public class MatrixMultiplication {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner([Link]);
// Get the dimensions of the first matrix

13
U23CS312-Java Lab

[Link]("Enter the number of rows for the first matrix: ");


int rows1 = [Link]();
[Link]("Enter the number of columns for the first matrix: ");
int cols1 = [Link]();
// Get the dimensions of the second matrix
[Link]("Enter the number of rows for the second matrix: ");
int rows2 = [Link]();
[Link]("Enter the number of columns for the second matrix: ");
int cols2 = [Link]();
// Check if matrix multiplication is possible
if (cols1 != rows2) {
[Link]("Matrix multiplication is not possible. Columns of the first
matrix must equal the rows of the second matrix.");
return;
}
// Declare the matrices
int[][] matrix1 = new int[rows1][cols1];
int[][] matrix2 = new int[rows2][cols2];
int[][] result = new int[rows1][cols2]; // Resultant matrix will have rows1 x cols2
dimensions
// Get input for the first matrix
[Link]("Enter the elements of the first matrix:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
[Link]("Element [" + i + "][" + j + "]: ");
matrix1[i][j] = [Link]();
}
}
// Get input for the second matrix
[Link]("Enter the elements of the second matrix:");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
[Link]("Element [" + i + "][" + j + "]: ");

14
U23CS312-Java Lab

matrix2[i][j] = [Link]();
}
}
// Perform matrix multiplication
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) { // cols1 is equal to rows2
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
// Display the result of the matrix multiplication
[Link]("The resulting matrix after multiplication is:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
[Link](result[i][j] + "\t");
}
[Link]();
}
// Close the scanner
[Link]();
}
}

RESULT:
Thus, 2-Dimentional array in Java was implemented successfully

15
U23CS312-Java Lab

Exp No:
Simple program to implement classes and objects
Date:

AIM:
To write a simple Java program to implement classes and objects

ALGORITHM:

STEP 1: Start
STEP 2: Define a Student class with instance variables name, age, and grade.
STEP 3: Define a method inputDetails to:

• Get student details (name, age, and grade) from the user.
STEP 4: Define a method displayDetails to:

• Display the student's name, age, and grade.


STEP 5: In the main method:

• Create a Student object (student1).

• Call inputDetails to input the student's details.

• Call displayDetails to display the student's details.

STEP 6: Stop

PROGRAM:

import [Link];

// Define a class "Student"

class Student {

// Declare instance variables

String name;

int age;

double grade;

16
U23CS312-Java Lab

// Method to input student details

void inputDetails() {

Scanner scanner = new Scanner([Link]);

// Get input from the user

[Link]("Enter student's name: ");

name = [Link]();

[Link]("Enter student's age: ");

age = [Link]();

[Link]("Enter student's grade: ");

grade = [Link]();

// Method to display student details

void displayDetails() {

[Link]("\nStudent Details:");

[Link]("Name: " + name);

[Link]("Age: " + age);

[Link]("Grade: " + grade);

// Main class to run the program

public class Main {

public static void main(String[] args) {

// Create an object of the "Student" class

Student student1 = new Student();

// Call the method to input details

17
U23CS312-Java Lab

[Link]();

// Call the method to display the student's details

[Link]();

RESULT:
Thus, classes and objects in Java was implemented successfully

18
U23CS312-Java Lab

Exp No:

Java program that implements single inheritance


Date:

AIM:
To write a Java program to implement single inheritance

ALGORITHM:
STEP 1: Start
STEP 2: Define a Person class with the following:
• Instance variables: name, age.
• Method inputDetails:
o Get name and age from the user.
• Method displayDetails:
o Display name and age.
STEP 3: Define a Student class that inherits from Person:
• Instance variable: major.
• Method inputStudentDetails:
o Call inputDetails from Person to get name and age.
o Get major from the user.
• Method displayStudentDetails:
o Call displayDetails from Person to display name and age.
o Display major.
STEP 4: In the main method:
• Create a Student object (student).
• Call inputStudentDetails to input student details.
• Call displayStudentDetails to display the student's details.

STEP 5: Stop

19
U23CS312-Java Lab

PROGRAM:

import [Link];
// Base class
class Person {
String name;
int age;
// Method to input person details
void inputDetails() {
Scanner scanner = new Scanner([Link]);
[Link]("Enter name: ");
name = [Link]();
[Link]("Enter age: ");
age = [Link]();
}
// Method to display person details
void displayDetails() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
// Derived class
class Student extends Person {
String major;
// Method to input student details
void inputStudentDetails() {
Scanner scanner = new Scanner([Link]);
// Call the inputDetails method from the Person class
inputDetails();
[Link]("Enter major: ");
major = [Link]();
}
// Method to display student details
void displayStudentDetails() {

20
U23CS312-Java Lab

// Call the displayDetails method from the Person class


displayDetails();
[Link]("Major: " + major);
}
}
// Main class to run the program
public class Main {
public static void main(String[] args) {
// Create an object of the Student class
Student student = new Student();

// Input details for the student


[Link]();

// Display student details


[Link]("\nStudent Details:");
[Link]();

RESULT:
Thus, Java program to implement single inheritance was completed successfully

21
U23CS312-Java Lab

Exp No:
Java program that implements Multilevel inheritance
Date:

AIM:

To write a Java program to implement Multilevel inheritance

ALGORITHM:

STEP 1: Start
STEP 2: Create a Person class with:

• Variables: name, age.

• Method inputDetails: Get name and age.

• Method displayDetails: Display name and age.

STEP 3: Create a Student class that extends Person with:

• Variable: major.

• Method inputStudentDetails: Get major (calls inputDetails from Person).

• Method displayStudentDetails: Display name, age, and major (calls displayDetails


from Person).

STEP 4: Create a Graduate class that extends Student with:

• Method inputGraduateDetails: Get thesisTopic (calls inputStudentDetails from


Student).

• Method displayGraduateDetails: Display name, age, major, and thesisTopic (calls


displayStudentDetails from Student).

STEP 5: In the main method:

• Create a Graduate object (graduate). And Input and display graduate details.

STEP 6: Stop

22
U23CS312-Java Lab

PROGRAM:

import [Link];
// Base class
class Person {
String name;
int age;
// Method to input person details
void inputDetails() {
Scanner scanner = new Scanner([Link]);
[Link]("Enter name: ");
name = [Link]();
[Link]("Enter age: ");
age = [Link]();
}
// Method to display person details
void displayDetails() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
// Derived class
class Student extends Person {
String major;
// Method to input student details
void inputStudentDetails() {
// Call the inputDetails method from the Person class
inputDetails();
Scanner scanner = new Scanner([Link]);
[Link]("Enter major: ");
major = [Link]();
}
// Method to display student details
void displayStudentDetails() {

23
U23CS312-Java Lab

// Call the displayDetails method from the Person class


displayDetails();
[Link]("Major: " + major);
}
}
// Further derived class
class Graduate extends Student {
String thesisTopic;
// Method to input graduate details
void inputGraduateDetails() {
// Call the inputStudentDetails method from the Student class
inputStudentDetails();
Scanner scanner = new Scanner([Link]);
[Link]("Enter thesis topic: ");
thesisTopic = [Link]();
}
// Method to display graduate details
void displayGraduateDetails() {
// Call the displayStudentDetails method from the Student class
displayStudentDetails();
[Link]("Thesis Topic: " + thesisTopic);
}
}

// Main class to run the program


public class Main {
public static void main(String[] args) {
// Create an object of the Graduate class
Graduate graduate = new Graduate();
// Input details for the graduate
[Link]();
// Display graduate details
[Link]("\nGraduate Details:");

24
U23CS312-Java Lab

[Link]();
}
}

RESULT:
Thus, Multi-level Inheritance in Java was implemented successfully

25
U23CS312-Java Lab

Exp No:
Java program that implements Hierarchical inheritance
Date:

AIM:
To write a Java program to implement Hierarchical Inheritance

ALGORITHM:
STEP 1: Start
STEP 2: Create a Person class with:

• Variables: name, age.

• Method inputDetails: Get name and age.

• Method displayDetails: Display name and age.

STEP 3: Create a Student class that extends Person with:

• Variable: major.

• Method inputStudentDetails: Get major (calls inputDetails from Person).

• Method displayStudentDetails: Display name, age, and major (calls displayDetails


from Person).

STEP 4: Create a Teacher class that extends Person with:

• Variable: subject.

• Method inputTeacherDetails: Get subject (calls inputDetails from Person).

• Method displayTeacherDetails: Display name, age, and subject (calls displayDetails


from Person).

STEP 5: In the main method:

• Create a separate object for Student and Teacher input their details.

• Display student & teacher details.

STEP 6: Stop

26
U23CS312-Java Lab

PROGRAM:

import [Link];
// Base class
class Person {
String name;
int age;
// Method to input person details
void inputDetails() {
Scanner scanner = new Scanner([Link]);
[Link]("Enter name: ");
name = [Link]();
[Link]("Enter age: ");
age = [Link]();
}
// Method to display person details
void displayDetails() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
// Derived class for students
class Student extends Person {
String major;
// Method to input student details
void inputStudentDetails() {
inputDetails(); // Call the inputDetails method from Person
Scanner scanner = new Scanner([Link]);
[Link]("Enter major: ");
major = [Link]();
}
// Method to display student details
void displayStudentDetails() {
displayDetails(); // Call the displayDetails method from Person

27
U23CS312-Java Lab

[Link]("Major: " + major);


}
}
// Derived class for teachers
class Teacher extends Person {
String subject;
// Method to input teacher details
void inputTeacherDetails() {
inputDetails(); // Call the inputDetails method from Person
Scanner scanner = new Scanner([Link]);
[Link]("Enter subject: ");
subject = [Link]();
}
// Method to display teacher details
void displayTeacherDetails() {
displayDetails(); // Call the displayDetails method from Person
[Link]("Subject: " + subject);
}
}
// Main class to run the program
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Create an object of the Student class
Student student = new Student();
[Link]("Enter details for the student:");
[Link]();
// Create an object of the Teacher class
Teacher teacher = new Teacher();
[Link]("\nEnter details for the teacher:");
[Link]();
// Display student details
[Link]("\nStudent Details:");

28
U23CS312-Java Lab

[Link]();
// Display teacher details
[Link]("\nTeacher Details:");
[Link]();
}
}

RESULT:
Thus, Hierarchical Inheritance in Java was implemented successfully

29
U23CS312-Java Lab

Exp No:
Java program that implements Multiple inheritance using
Date: interface

AIM:
To write a Java program to implement Multiple Inheritance using interface

ALGORITHM:
STEP 1: Start
STEP 2: Define a Student interface with:
• Method inputStudentDetails: To get student details (name, age, major).
• Method displayStudentDetails: To display student details.
STEP 3: Define an Employee interface with:
• Method inputEmployeeDetails: To get employee details (company, stipend).
• Method displayEmployeeDetails: To display employee details.
STEP 4: Create an Intern class that implements both Student and Employee interfaces with:
• Variables: name, age, major, company, stipend.
• Method inputStudentDetails: Get student details.
• Method displayStudentDetails: Display student details.
• Method inputEmployeeDetails: Get employee details (company, stipend).
• Method displayEmployeeDetails: Display employee details.
STEP 5: In the main method:
• Create an Intern object.
• Call inputStudentDetails to input student details.
• Call inputEmployeeDetails to input employee details.
• Call displayStudentDetails to display student details.
• Call displayEmployeeDetails to display employee details.
STEP 6: Stop

30
U23CS312-Java Lab

PROGRAM:

import [Link];
// Interface for Student
interface Student {
void inputStudentDetails();
void displayStudentDetails();
}
// Interface for Employee
interface Employee {
void inputEmployeeDetails();
void displayEmployeeDetails();
}
// Class that implements both interfaces
class Intern implements Student, Employee {
String name;
int age;
String major;
String company;
double stipend;
// Method to input student details
@Override
public void inputStudentDetails() {
Scanner scanner = new Scanner([Link]);
[Link]("Enter student name: ");
name = [Link]();
[Link]("Enter student age: ");
age = [Link]();
[Link](); // Consume newline
[Link]("Enter major: ");
major = [Link]();
}
// Method to display student details
@Override

31
U23CS312-Java Lab

public void displayStudentDetails() {


[Link]("Student Name: " + name);
[Link]("Age: " + age);
[Link]("Major: " + major);
}
// Method to input employee details
@Override
public void inputEmployeeDetails() {
Scanner scanner = new Scanner([Link]);
[Link]("Enter company name: ");
company = [Link]();
[Link]("Enter stipend: ");
stipend = [Link]();
}
// Method to display employee details
@Override
public void displayEmployeeDetails() {
[Link]("Company Name: " + company);
[Link]("Stipend: $" + stipend);
}
}
// Main class to run the program
public class Main {
public static void main(String[] args) {
Intern intern = new Intern();
// Input details for the intern
[Link]("Enter details for the intern (as Student):");
[Link]();
[Link]("\nEnter details for the intern (as Employee):");
[Link]();
// Display details
[Link]("\nIntern Details:");
[Link]();

32
U23CS312-Java Lab

[Link]();
}
}

RESULT:
Thus, Multiple Inheritance using interface was successfully implemented

33
U23CS312-Java Lab

Exp No:
Java program that implements method overloading
Date:

AIM:
To write a Java program to implement method overloading

ALGORITHM:
STEP 1: Start
STEP 2: Define a calculateArea method for the rectangle:

• Input: length, breadth (both integers).

• Calculate and print the area of the rectangle: length * breadth.

STEP 3: Define a calculateArea method for the circle:

• Input: radius (double).

• Calculate and print the area of the circle: π * radius².

STEP 4: In the main method:

• Prompt the user to choose either rectangle (1) or circle (2).

• If choice is 1 (rectangle):

o Input length and breadth.

o Call calculateArea for rectangle.

• If choice is 2 (circle):

o Input radius.

o Call calculateArea for circle.

• If the choice is invalid, print "Invalid choice!".

STEP 5: Stop

34
U23CS312-Java Lab

PROGRAM:

import [Link];
public class MethodOverloadingExample {
public static void calculateArea(int length, int breadth) {
int area = length * breadth;
[Link]("Area of rectangle: " + area);
}
public static void calculateArea(double radius) {
double area = [Link] * radius * radius;
[Link]("Area of circle: " + area);
}
public static void main(String[] args) {
Scanner
scanner = new Scanner([Link]);
[Link]("Enter 1 for rectangle or 2 for circle:");
int choice = [Link]();
if (choice == 1) {
[Link]("Enter length: ");
int length = [Link]();
[Link]("Enter breadth: ");
int breadth = [Link]();
calculateArea(length, breadth);
} else if (choice == 2) {
[Link]("Enter radius: ");
double radius = [Link]();
calculateArea(radius);
} else {
[Link]("Invalid choice!");
}
[Link]();

RESULT:
Thus, Method overloading in Java was implemented successfully

35
U23CS312-Java Lab

Exp No:
Java program to handle exceptions
Date:

AIM:
To write a Java program to handle exceptions
ALGORITHM:
STEP 1: Start
STEP 2: Create a Scanner object to take user input.
STEP 3: Use a try block to:

• Prompt the user to input two integers (num1 and num2).

• Attempt to divide num1 by num2 and display the result.

STEP 4: Use catch blocks to handle exceptions:

• InputMismatchException: If the user enters a non-integer value, display an error


message: "Invalid input. Please enter an integer."

• ArithmeticException: If division by zero occurs, display an error message: "Division


by zero is not allowed."

STEP 5: Use a finally block:

• Print "End of exception handling demo."

• Close the scanner.


STEP 6: Stop

PROGRAM:
import [Link];
import [Link];
public class ExceptionHandlingExample {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
try {
// Taking user input for two integers

36
U23CS312-Java Lab

[Link]("Enter the first number: ");


int num1 = [Link]();

[Link]("Enter the second number: ");


int num2 = [Link]();

// Attempting division, may throw ArithmeticException


int result = num1 / num2;
[Link]("Result of division: " + result);

} catch (InputMismatchException e) {
// Handling case where the user enters a non-integer value
[Link]("Error: Invalid input. Please enter an integer.");
} catch (ArithmeticException e) {
// Handling division by zero
[Link]("Error: Division by zero is not allowed.");
} finally {
// This block will always execute
[Link]("End of exception handling demo.");
[Link]();
}
}
}

RESULT:
Thus, Program to handle exceptions was implemented successfully

37
U23CS312-Java Lab

Exp No:
Java program to implement multithreading
Date:

AIM:
To write a Java program to implement multithreading

ALGORITHM:
STEP 1: Start
STEP 2: Create a Scanner object to take user input.
STEP 3: Ask the user for the number of threads (numThreads).
STEP 4: Create an array threads of size numThreads.
STEP 5: For each thread (from 0 to numThreads - 1):

• Create a new Thread that:

o Prints "Thread X started" (where X is the thread number).

o Sleeps for 1 second (simulating some work).

o Prints "Thread X finished". STEP6: Start each thread by calling [Link]().

STEP 7: Wait for each thread to finish by calling [Link]().

STEP 8: After all threads have finished, print "All threads have finished."
STEP 9: Close the scanner.
STEP 10: Stop

PROGRAM:

import [Link];
public class MultithreadingExample {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of threads: ");
int numThreads = [Link]();
Thread[] threads = new Thread[numThreads];
for (int i = 0; i < numThreads; i++) {
int threadNumber = i; // Capturing the correct index in a final variable

38
U23CS312-Java Lab

threads[i] = new Thread(() -> {


[Link]("Thread " + threadNumber + " started.");
try {
[Link](1000); // Simulate some work
} catch (InterruptedException e) {
[Link]();
}
[Link]("Thread " + threadNumber + " finished.");
}
);
}
for (Thread thread : threads) {
[Link]();
}
for (Thread thread : threads) {
try {
[Link]();
} catch (InterruptedException e) {
[Link]();
}
}
[Link]();
[Link]("All threads have finished.");
}
}

RESULT:
Thus, Multi-threading in Java was implemented successfully

39
U23CS312-Java Lab

Exp No:
Java program to perform basic file reading from and
Date: writing to text files

AIM:
To write a Java program to perform basic file reading from and write to text file
ALGORITHM:
STEP 1: Start
STEP 2: Define the file name ([Link]) and content to write
STEP 3: Write content to the file:

• Use a FileWriter to open the file and write the content.

• If writing is successful, print "Content written to file successfully."

• If an error occurs during writing, catch IOException and print an error message.

STEP 4: Read content from the file:

• Use a FileReader to open the file and read each character one by one.

• Print each character until the end of the file (-1).

• If an error occurs during reading, catch IOException and print an error message.

STEP 5: Stop

PROGRAM:

import [Link];
import [Link];
import [Link];

public class BasicFileReadWrite {


public static void main(String[] args) {
String fileName = "[Link]";
String contentToWrite = "This is a sample text written to the file.\nJava File IO is
interesting!";

40
U23CS312-Java Lab

// Writing to the file


try (FileWriter writer = new FileWriter(fileName)) {
[Link](contentToWrite);
[Link]("Content written to file successfully.");
} catch (IOException e) {
[Link]("An error occurred during writing.");
[Link]();
}

// Reading from the file


try (FileReader reader = new FileReader(fileName)) {
int character;
[Link]("Reading content from file:");
while ((character = [Link]()) != -1) {
[Link]((char) character);
}
[Link]();
} catch (IOException e) {
[Link]("An error occurred during reading.");
[Link]();
}
}
}

RESULT:
Thus, Program to perform basic file reading and writing was implemented successfully

41
U23CS312-Java Lab

Exp No:
Java program to perform reading from and writing to
binary files
Date:

AIM:
To write a Java program to perform reading and writing binary files

ALGORITHM:

STEP 1: Start
STEP 2: Define the file name ([Link]) and data to write
STEP 3: Write data to a binary file:

• Use FileOutputStream to open the file and write the byte array to it.

• If writing is successful, print "Data written to binary file successfully."

• If an error occurs during writing, catch IOException and print an error message.
STEP 4: Read data from the binary file:

• Use FileInputStream to open the file and read one byte at a time.

• Convert each byte to a character and print it for readability.

• Continue reading until the end of the file (-1 is returned).


• If an error occurs during reading, catch IOException and print an error message.
STEP 5: Stop

PROGRAM:

import [Link];
import [Link];
import [Link];

public class BinaryFileReadWrite {


public static void main(String[] args) {
String fileName = "[Link]";

42
U23CS312-Java Lab

byte[] dataToWrite = { 65, 66, 67, 68, 69 }; // Corresponds to ASCII values of A, B, C,


D, E

// Writing to a binary file


try (FileOutputStream fos = new FileOutputStream(fileName)) {
[Link](dataToWrite);
[Link]("Data written to binary file successfully.");
} catch (IOException e) {
[Link]("An error occurred during writing.");
[Link]();
}

// Reading from a binary file


try (FileInputStream fis = new FileInputStream(fileName)) {
int byteData;
[Link]("Reading data from binary file:");
while ((byteData = [Link]()) != -1) {
[Link]((char) byteData + " "); // Convert byte to char for readability
}
[Link]();
} catch (IOException e) {
[Link]("An error occurred during reading.");
[Link]();
}
}
}

RESULT:
Thus, Java program to read and write Binary files was implemented successfully

43
U23CS312-Java Lab

Exp No:
Java program to demonstrate basic networking using
Date: TCP sockets

AIM:
To write a Java program to demonstrate basic networking using TCP sockets

ALGORITHM:
[Link] (Server Side):
STEP 1: Start
STEP 2: Initialize the server to listen on a specified port (e.g., 6789).
STEP 3: Wait for a client to connect using [Link]().
STEP 4: Once the client connects, create input and output streams to communicate with the
client:

• Use InputStream and BufferedReader to receive data from the client.


• Use OutputStream and PrintWriter to send data to the client.
STEP 5: Read the message sent by the client using the input stream and print it on the
server.
STEP 6: Send a response ("Hello from server!") back to the client.
STEP 7: Close the socket connection.
STEP 8: Stop
[Link] (Client Side):
STEP 1: Start
STEP 2: Create a connection to the server using the server's hostname (localhost) and port
number (e.g., 6789).
STEP 3: Create input and output streams to communicate with the server:
• Use OutputStream and PrintWriter to send data to the server.

• Use InputStream and BufferedReader to read the server's response.


STEP 4: Send a message to the server (e.g., "Hello from client!").
STEP 5: Wait and read the server's response.
STEP 6: Print the response from the server.
STEP 7: Close the connection to the server.
STEP 8: Stop

44
U23CS312-Java Lab

PROGRAM:

TCPServer,java:

import [Link].*;
import [Link].*;

public class TCPServer {


public static void main(String[] args) {
int port = 6789;
try (ServerSocket serverSocket = new ServerSocket(port)) {
[Link]("Server is listening on port " + port);
Socket socket = [Link](); // Accept client connection
[Link]("Client connected");

// Setup input and output streams


InputStream input = [Link]();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));

OutputStream output = [Link]();


PrintWriter writer = new PrintWriter(output, true);

// Read message from client


String message = [Link]();
[Link]("Received from client: " + message);

// Send response to client


[Link]("Hello from server!");

[Link](); // Close the connection


} catch (IOException ex) {
[Link]("Server exception: " + [Link]());
[Link]();
}
}
}

[Link]:

import [Link].*;
import [Link].*;

public class TCPClient {

45
U23CS312-Java Lab

public static void main(String[] args) {


String hostname = "localhost";
int port = 6789;

try (Socket socket = new Socket(hostname, port)) {


OutputStream output = [Link]();
PrintWriter writer = new PrintWriter(output, true);

InputStream input = [Link]();


BufferedReader reader = new BufferedReader(new InputStreamReader(input));

// Send message to server


[Link]("Hello from client!");

// Read response from server


String response = [Link]();
[Link]("Server response: " + response);

} catch (UnknownHostException ex) {


[Link]("Server not found: " + [Link]());
} catch (IOException ex) {
[Link]("I/O error: " + [Link]());
}
}
}

RESULT:
Thus, Program to demonstrate basic networking using TCP sockets was completed
successfully

46
U23CS312-Java Lab

Exp No:
Java program to demonstrate basic
networking using UDP sockets
Date:

AIM:
To write a Java program to demonstrate basic networking using UDP sockets
ALGORITHM:
[Link] (Server Side):
STEP 1: Start
STEP 2: Create a DatagramSocket to listen for incoming client messages on a specific port
(e.g., 9876).
STEP 3: Set up a buffer to receive incoming data from the client.
STEP 4: Wait for a packet (message) from the client using [Link]().
STEP 5: Read the data from the packet and convert it into a string.
STEP 6: Prepare a response message ("Hello from UDP Server!") and convert it into bytes.
STEP 7: Send the response message back to the client using [Link]().
STEP 8: Close the socket connection.
STEP 9: Stop

[Link] (Client Side):


STEP 1: Start
STEP 2: Create a DatagramSocket to communicate with the server.
STEP 3: Prepare the message to send to the server.
STEP 4: Convert the message into a byte array and send it to the server using
[Link]().
STEP 5: Set up a buffer to receive the server's response.
STEP 6: Wait for the response using [Link]().
STEP 7: Read the server's response and convert it into a string.
STEP 8: Print the response.
STEP 9: Close the socket connection.
STEP 10: Stop

47
U23CS312-Java Lab

PROGRAM:

[Link]:

import [Link];
import [Link];
import [Link];

public class UDPServer {


public static void main(String[] args) {
int port = 9876;
try (DatagramSocket serverSocket = new DatagramSocket(port)) {
[Link]("UDP Server is listening on port " + port);

// Buffer to receive incoming data


byte[] receiveBuffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,
[Link]);

// Receive packet from client


[Link](receivePacket);
String receivedMessage = new String([Link](), 0,
[Link]());
[Link]("Received from client: " + receivedMessage);

// Prepare response
String responseMessage = "Hello from UDP Server!";
byte[] sendBuffer = [Link]();

// Send response back to client


InetAddress clientAddress = [Link]();
int clientPort = [Link]();
DatagramPacket sendPacket = new DatagramPacket(sendBuffer, [Link],
clientAddress, clientPort);
[Link](sendPacket);

[Link]("Response sent to client.");


} catch (Exception e) {
[Link]("Server error: " + [Link]());
[Link]();
}
}
}

48
U23CS312-Java Lab

[Link]:

import [Link];
import [Link];
import [Link];

public class UDPClient {


public static void main(String[] args) {
String serverHostname = "localhost";
int port = 9876;

try (DatagramSocket clientSocket = new DatagramSocket()) {


// Prepare message to send
String message = "Hello from UDP Client!";
byte[] sendBuffer = [Link]();
InetAddress serverAddress = [Link](serverHostname);

// Send packet to server


DatagramPacket sendPacket = new DatagramPacket(sendBuffer, [Link],
serverAddress, port);
[Link](sendPacket);
[Link]("Message sent to server.");

// Buffer to receive response


byte[] receiveBuffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,
[Link]);

// Receive response from server


[Link](receivePacket);
String receivedMessage = new String([Link](), 0,
[Link]());
[Link]("Response from server: " + receivedMessage);

} catch (Exception e) {
[Link]("Client error: " + [Link]());
[Link]();
}
}
}

RESULT:
Thus, Program to demonstrate basic networking using UDP sockets was completed
successfully

49

You might also like