0% found this document useful (0 votes)
3 views21 pages

Java Lab Programs

Uploaded by

sasikala
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views21 pages

Java Lab Programs

Uploaded by

sasikala
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

EX 1 PRIME NUMBERS

AIM :
To write a Java program that prompts the user for an integer and then prints out all the prime
numbers up to that Integer

ALGORITHM

STEP 1: Start

STEP 2: Input the number n

STEP 3: For each number i from 2 to n, do:

Set a flag isPrime to true


For each number j from 2 to i - 1, do:
If i % j == 0, set isPrime to false and break
If isPrime is true, print i

STEP 4: End

SOURCE CODE

import [Link];

public class SimplePrimeNumbers {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter a number: ");
int n = [Link]();

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


boolean prime = true;

for (int j = 2; j < i; j++) {


if (i % j == 0) {
prime = false;
break;
}
}
if (prime) {
[Link](i + " ");
}
}
[Link]();
}
}

OUTPUT

RESULT:
Thus the program was compiled and executed successfully
EX 2. CELSIUS TO FAHRENHEIT

AIM :
To write a program to read the temperature in Celsius and convert into Fahrenheit.

ALGORITHM

STEP 1: Start
STEP 2: Create a Scanner object to take user input.
STEP 3: Prompt the user to enter the temperature in Celsius.
STEP 4: Read the input and store it in a variable celsius.
STEP 5: Convert the temperature using the formula:

Fahrenheit=(Celsius×95)+32\text{Fahrenheit} = (\text{Celsius} \times \frac{9}{5}) +


32Fahrenheit=(Celsius×59)+32

STEP 6: Display the temperature in Fahrenheit.


STEP 7: Close the Scanner.
STEP 8: End.

SOURCE CODE:
import [Link];
public class TemperatureConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Read temperature in Celsius from user


[Link]("Enter temperature in Celsius: ");
double celsius = [Link]();

// Convert Celsius to Fahrenheit


double fahrenheit = (celsius * 9/5) + 32;

// Display the result


[Link]("%.2f°C is equal to %.2f°F\n", celsius, fahrenheit);

[Link]();
}
}

RESULT:
Thus the program was compiled and executed successfully
EX 3 THE LARGEST NUMBER
AIM:
To write a program to read 2 integers and find the largest number using conditional
operator
ALGORITHM

STEP 1: Start
STEP 2: Create a Scanner object to take user input.
STEP 3: Prompt the user to enter the first integer (num1).
STEP 4: Read and store the value in num1.
STEP 5: Prompt the user to enter the second integer (num2).
STEP 6: Read and store the value in num2.
STEP 7: Use the conditional (ternary) operator to determine the largest number:

largest=(num1>num2)?num1:num2

STEP 8: Print the largest number.


STEP 9: Close the Scanner.
STEP 10: End.

SOURCE CODE:

import [Link];
public class LargestNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Read two integers from user
[Link]("Enter first number: ");
int num1 = [Link]();
[Link]("Enter second number: ");
int num2 = [Link]();
// Find the largest number using conditional operator
int largest = (num1 > num2) ? num1 : num2;
// Display the result
[Link]("The largest number is: " + largest);
[Link]();
}}
RESULT:
Thus the program was compiled and executed successfully
EX 4 FACTORIAL NUMBER

AIM
To write a program to read an integer and find the factorial of a number.

ALGORITHM

STEP 1: Start
STEP 2: Declare an integer variable num (e.g., num = 5).
STEP 3: Initialize a variable factorial = 1 to store the result.
STEP 4: Use a for loop that runs from i = 1 to num:

Multiply factorial by i in each iteration (factorial *= i).

STEP 5: Print the value of factorial.


STEP 6: End

SOURCE CODE

public class FactorialCalculator {


public static void main(String[] args) {
int num = 5; // Example number
long factorial = 1;

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


factorial *= i;
}

[Link]("Factorial of " + num + " is: " + factorial);


}
}
RESULT:
Thus the program was compiled and executed successfully
EX 5 VECTOR CLASS AND ITS METHODS
AIM:
To write a program to implement Vector class and its methods.

ALGORITHM

STEP 1: Start
STEP 2: Create a Vector of integers.
STEP 3: ADD ELEMENTS (10, 20, 30) TO THE VECTOR.
STEP 4: Print the Vector.
STEP 5: Remove an element at index 1.
STEP 6: Print the updated Vector.
STEP 7: End.

SOURCE CODE

import [Link];

public class VectorExample {


public static void main(String[] args) {
Vector<Integer> numbers = new Vector<>();
[Link](10);
[Link](20);
[Link](30);

[Link]("Vector: " + numbers);


[Link](1);
[Link]("After removal: " + numbers);
}
}
RESULT:
Thus the program was compiled and executed successfully
Ex 6 PALINDROME
AIM
To write a program to read a string and check whether it is palindrome or not

ALGORITHM

STEP 1: Start
STEP 2: Define a string (str = "madam") as an example.
STEP 3: Reverse the string using StringBuilder.
STEP 4: Compare the original string with the reversed string:

If both are equal, print "Palindrome".


Otherwise, print "Not a palindrome".

STEP 5: End.

SOURCE CODE

public class PalindromeChecker {


public static void main(String[] args) {
String str = "madam"; // Example string

String reversed = new StringBuilder(str).reverse().toString();

if ([Link](reversed)) {
[Link](str + " is a palindrome.");
} else {
[Link](str + " is not a palindrome.");
}
}
}
RESULT:
Thus the program was compiled and executed successfully
EX 7 CLASS AND OBJECTS
AIM :
To Write a program to create a class with following data members register number,. Name,
Marks in 3 subjects and member functions parameterised constructor – to assign values to
members,method to find total mark method to display register number, name, total mark
Create 3 objects from the above class and use the members

ALGOITHM

STEP 1: Start
STEP 2: Define a Student class with the following data members:

 regNumber (integer)
 name (string)
 mark1, mark2, mark3 (integers)

STEP 3: Create a parameterized constructor to initialize these data members.


STEP 4: Define a method displayDetails() to:

Calculate the total marks (mark1 + mark2 + mark3)

Print Register Number, Name, and Total Marks

STEP 5: In the main method:

Create two student objects using the constructor.

Call displayDetails() for each student.

STEP 6: End.
SOURCE CODE

class Student {
private int regNumber;
private String name;
private int mark1, mark2, mark3;

public Student(int regNumber, String name, int mark1, int mark2, int mark3) {
[Link] = regNumber;
[Link] = name;
this.mark1 = mark1;
this.mark2 = mark2;
this.mark3 = mark3;
}
public void displayDetails() {
[Link](regNumber + " - " + name + " - Total: " + (mark1 + mark2 +
mark3));
}
public static void main(String[] args) {
Student s1 = new Student(101, "Alice", 85, 90, 80);
Student s2 = new Student(102, "Bob", 75, 88, 95);
[Link]();
[Link]();
}
}
RESULT:
Thus the program was compiled and executed successfully
EX 8 MULTILEVEL INHERITANCE

AIM
To Write a program to implement multilevel inheritance.

ALGORITHM

STEP 1: Start

STEP 2: Define a base class Person with:

Data member: name


Constructor to initialize name

STEP 3: Create a derived class Student (inherits from Person) with:

Data member: studentId


Constructor to initialize name (from Person) and studentId

STEP 4: Create another derived class GraduateStudent (inherits from Student) with:

Data member: specialization


Constructor to initialize name, studentId, and specialization

STEP 5: Define a method displayInfo() in GraduateStudent to print all details.

STEP 6: In the main method:

Create an object of GraduateStudent with sample data.


Call displayInfo() to display details.

STEP 7: End.

SOURCE CODE
class Person {
String name;

Person(String name) {
[Link] = name;
}
}

class Student extends Person {


int id;

Student(String name, int id) {


super(name);
[Link] = id;
}
}

class GraduateStudent extends Student {


String specialization;

GraduateStudent(String name, int id, String specialization) {


super(name, id);
[Link] = specialization;
}

void displayInfo() {
[Link](name + " - " + id + " - " + specialization);
}

public static void main(String[] args) {


GraduateStudent student = new GraduateStudent("Alice", 101, "CS");
[Link]();
}
}

RESULT:
Thus the program was compiled and executed successfully
EX 9 THREAD IMPLEMENTATION

AIM
Write a program that creates three threads. First thread displays “Good Morning”
everyone second, the second thread displays “Hello” every two seconds and the third
thread displays “Welcome” every three seconds.

Algorithm

Step 1: Start

Step 2: Define a class MessageThread that extends Thread:

Data members:
message (stores the message to be printed)
interval (stores the time interval in milliseconds)
Constructor: Initializes message and interval
run() method:
Loop 5 times:
Print message
Sleep for interval milliseconds

Step 3: In the main method:

Create three threads with different messages and time intervals:


"Good Morning" (1 second)
"Hello" (2 seconds)
"Welcome" (3 seconds)
Start all three threads

Step 4: End

Source Code
class MessageThread extends Thread {
private String message;
private int interval;

public MessageThread(String message, int interval) {


[Link] = message;
[Link] = interval;
}

public void run() {


try {
for (int i = 0; i < 5; i++) {
[Link](message);
[Link](interval);
}
} catch (InterruptedException e) {
[Link]("Thread interrupted: " + message);
}
}
}

public class MultiThreadingDemo {


public static void main(String[] args) {
new MessageThread("Good Morning", 1000).start();
new MessageThread("Hello", 2000).start();
new MessageThread("Welcome", 3000).start();
}
}
RESULT:
Thus the program was compiled and executed successfully
EX10 STRING OPERATIONS USING STRING CLASS

AIM:
Write a program to perform the following string operations using String class:
String Concatenation,Search a substring,To extract substring from given string

ALGORITHM

Step 1: Start

Step 2: Perform String Concatenation

 Define two strings, str1 = "Hello" and str2 = "World"


 Concatenate them using + operator and store the result

Step 3: Search for a Substring

 Define a string mainStr = "Java programming is fun"


 Search for the substring "programming" using indexOf() method
 Print the index where the substring is found

Step 4: Extract a Substring

 Define a string extractStr = "Welcome to Java"


 Extract a substring from index 8 to 12 using substring() method
 Print the extracted substring

Step 5: End

Source Code
public class StringOperations {
public static void main(String[] args) {
// String Concatenation
String result = "Hello" + " World";
[Link]("Concatenated String: " + result);

// Search a Substring
String mainStr = "Java programming is fun";
[Link]("Substring found at index: " + [Link]("programming"));

// Extract Substring
[Link]("Extracted Substring: " + "Welcome to Java".substring(8, 12));
}
}

RESULT:
Thus the program was compiled and executed successfully

You might also like