Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Record Java Programming

The document contains a series of programming exercises in Java, including flowcharts, algorithms, and code implementations. Each exercise covers different concepts such as printing strings, calculating sums, reading user input, generating Fibonacci series, finding multiples of numbers, checking for palindromes, managing student names in a vector, and illustrating thread control methods. The results of each exercise confirm successful output for the respective tasks.

Uploaded by

cyberdomesoc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Record Java Programming

The document contains a series of programming exercises in Java, including flowcharts, algorithms, and code implementations. Each exercise covers different concepts such as printing strings, calculating sums, reading user input, generating Fibonacci series, finding multiples of numbers, checking for palindromes, managing student names in a vector, and illustrating thread control methods. The results of each exercise confirm successful output for the respective tasks.

Uploaded by

cyberdomesoc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

FLOWCHART

Start

Define message = “Hello, World!”

Print messsage

End

OutPut
Hello, World!
Expt. No. 01 Page No.: 02

Write a Program to Print a String on the Screen

public class PrintString {


public static void main(String[] args) {
// Define the string to be printed
String message = "Hello, World!";

// Print the string to the screen


System.out.println(message);
}
}

Algorithm:

1. Start: Begin the program execution.


2. Define String: Declare a string variable named message and assign it the value
"Hello, World!".
3. Print String: Output the value of the message variable to the screen using
System.out.println.
4. End: Terminate the program.

Result
Output printed successfully
FLOWCHART

Start

n=5

sum=0

i=1

No

i <= n

Yes

sum = sum + i

i=i+1

Print sum

End

OutPut
The sum of the first 5 consecutive positive integers is: 15
Expt. No. 02 Page No.: 03

Write a Java Program to calculate the sum of the first n consecutive positive
integers

public class SumOfConsecutiveIntegers {

public static void main(String[] args) {

int n = 5; // Change this to the desired number of integers

int sum = 0;

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

sum += i;

System.out.println("The sum of the first " + n + " consecutive positive integers is: " + sum);

Algorithm:

1. Start: Begin the program execution.


2. Initialize n: Set n to the desired number of consecutive integers.
3. Initialize sum: Set sum to 0.
4. Initialize loop counter i: Set i to 1.
5. Loop: Repeat steps 6 to 8 until i is greater than n. 6. Add i to sum: Add the value of
i to sum. 7. Increment i: Increment the value of i by 1.
6. End Loop: Exit the loop when i is greater than n.
7. Print sum: Output the calculated sum.
8. End: Terminate the program.

Result
Output printed successfully
FLOWCHART

Start

Create Scanner object

Prompt: "Enter first integer:"

Read first integer into num1

Prompt: "Enter second integer:"

Read second integer into num2

Sum = num1+num2

Display: "The sum of num1 and num2 is: Sum"

Close Scanner

End

OUTPUT
Enter the first integer: 8
Enter the second integer: 15
The sum of 8 and 15 is: 23

Expt. No. 03 Page No.: 04

Write a Program to read 2 Integer numbers from the keyboard and display
their sum on the screen
import java.util.Scanner;
public class SumOfTwoIntegers {
public static void main(String[] args) {
// Create a Scanner object to read input from the keyboard
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the first integer
System.out.print("Enter the first integer: ");
int num1 = scanner.nextInt();
// Prompt the user to enter the second integer
System.out.print("Enter the second integer: ");
int num2 = scanner.nextInt();
// Calculate the sum of the two integers
int sum = num1 + num2;
// Display the sum
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);

// Close the scanner to prevent resource leaks


scanner.close();
}
}
Page No.: 05

Algorithm:

1. Start: Begin the program.


2. Create Scanner Object: Initialize a Scanner object to read input from the keyboard.
3. Prompt for First Integer: Display a message asking the user to enter the first integer.
4. Read First Integer: Read the first integer from the keyboard and store it in num1.
5. Prompt for Second Integer: Display a message asking the user to enter the second
integer.
6. Read Second Integer: Read the second integer from the keyboard and store it in
num2.
7. Calculate Sum: Compute the sum of num1 and num2.
8. Display Sum: Print the sum to the screen.
9. Close Scanner: Close the Scanner object to prevent resource leaks.
10. End: Terminate the program.

Result
Output printed successfully
Flowchart

Start

Initialize prev=0,
curr=1
i=1

No
i <= 10? End

Yes

next = prev + curr

Print current (curr)

Update prev, curr


prev = curr
curr = next
i++

OutPut

First 10 terms of Fibonacci series:

0 1 1 2 3 5 8 13 21 34
Expt. No. 04 Page No.: 06

Write a program to display first ten terms of fibonacci series

public class FibonacciSeries {


public static void main(String[] args) {
int n = 10; // Number of terms to display
int firstTerm = 0;
int secondTerm = 1;
System.out.println("First " + n + " terms of Fibonacci series:");
for (int i = 1; i <= n; i++) {
System.out.print(firstTerm + " ");
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}

Algorithm:

1. Start: Begin the program.


2. Initialize Variables: Set n to 10 (for the number of terms). Initialize firstTerm to 0
and secondTerm to 1.
3. Print Header: Print "First 10 terms of Fibonacci series:".
4. Loop through Terms:
o For each term from 1 to n:
 Print the firstTerm.
 Compute the next term as the sum of firstTerm and secondTerm.
 Update firstTerm to be secondTerm.
 Update secondTerm to be the newly computed next term.
5. End: Terminate the program.
Result
Output printed successfully

FLOWCHART

Start

i = 100

if

i <= 200

Stop

Yes

if

i % 9 == 0

Yes

Print i

i=i+1

OUTPUT
Multiples of 9 between 100 and 200:
108
117
126
135
144
153
162
171
180
189
198

Expt. No. 05 Page No.: 07

Write a program to find and print the multiples of 9 between 100 and 200
using for loop

public class MultiplesOfNine {

public static void main(String[] args) {

// Print a message indicating the task

System.out.println("Multiples of 9 between 100 and 200:");

// Loop through numbers from 100 to 200

for (int i = 100; i <= 200; i++) {

// Check if the current number is a multiple of 9

if (i % 9 == 0) {

// Print the number if it is a multiple of 9

System.out.println(i);

Algorithm:

1. Start: Begin the program.


2. Initialize Loop: Start a for loop with i ranging from 100 to 200.
3. Check Multiples of 9: In each iteration, check if i is a multiple of 9 (i % 9 == 0).
4. Print Multiples: If i is a multiple of 9, print the value of i.
5. Continue Loop: Continue the loop until i exceeds 200.
6. End: Terminate the program.
Result
Output printed successfully

FLOWCHART
Start

Input originalNumber

Initialize reversedNumber = 0
Initialize tempNumber = originalNumber

While tempNumber != 0
lastDigit = tempNumber % 10
reversedNumber = reversedNum * 10 + lastDigit
tempNumber = tempNumber / 10

originalNumber == reversedNumber? No

Print "originalNumber is not a


palindrome"

Stop

Print "originalNumber is a palindrome"

Stop

OUTPUTS
1. 2.
Enter a number: 121 Enter a number: 123
121 is a palindrome. 123 is not a palindrome.
Expt. No. 06 Page No.: 08

Write to check whether the number is palindrome or not

import java.util.Scanner;

public class PalindromeChecker {


public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a number


System.out.print("Enter a number: ");
int originalNumber = scanner.nextInt();

// Store the original number for comparison later


int reversedNumber = 0;
int tempNumber = originalNumber;

// Reverse the digits of the number


while (tempNumber != 0) {
int lastDigit = tempNumber % 10;
reversedNumber = reversedNumber * 10 + lastDigit;
tempNumber /= 10;
}

// Check if the original number is equal to the reversed number


if (originalNumber == reversedNumber) {
System.out.println(originalNumber + " is a palindrome.");
} else {
System.out.println(originalNumber + " is not a palindrome.");
}

// Close the scanner


scanner.close();
}
}

Algorithm:

1. Start: Begin the program.


2. Input: Read an integer number from the user.
3. Initialize: Set reversedNumber to 0 and tempNumber to the input number
(originalNumber).
4. Reverse Number:
o While tempNumber is not 0:
Page No.: 09

 Extract the last digit using tempNumber % 10.


 Add the last digit to reversedNumber after shifting its current digits to the
left by multiplying it by 10.
 Remove the last digit from tempNumber using integer division by 10.
5. Check Palindrome: Compare originalNumber and reversedNumber.
o If they are equal, the number is a palindrome.
o If they are not equal, the number is not a palindrome.
6. Output Result: Display whether the number is a palindrome or not.
7. End: Terminate the program.

Result
Output printed successfully
FLOWCHART

Start

Create Vector studentNames

Add names: "Alice", "Bob",


"Charlie", "David", "Eve"

YES
studentNames.size() > 2

Remove the
name at the
third position (index 2)

Add name "Frank" at end of the list

Stop

OUTPUT

Final list of student names:


Alice
Bob
David
Eve
Frank
Expt. No. 07 Page No.: 10

Write a Program to create a list of names of 5 students in a class and store in


a vector. In addition to perform the following operations in the list:
1. Add a name at the end of the list
2. Delete a name at the third position in the list
3. Display the final contents of the list

import java.util.Vector;

public class StudentNames {


public static void main(String[] args) {
// Create a Vector to store the names of students
Vector<String> studentNames = new Vector<>();

// Add initial names to the Vector


studentNames.add("Alice");
studentNames.add("Bob");
studentNames.add("Charlie");
studentNames.add("David");
studentNames.add("Eve");

// Add a name at the end of the list


studentNames.add("Frank");

// Delete the name at the third position (index 2)


if (studentNames.size() > 2) {
studentNames.remove(2);
}

// Display the final contents of the list


System.out.println("Final list of student names:");
for (String name : studentNames) {
System.out.println(name);
}
}
}

Algorithm:
1. Start: Begin the program.
2. Create Vector: Initialize a Vector named studentNames to store student names.
3. Add Initial Names: Add the names "Alice", "Bob", "Charlie", "David", and "Eve" to the
Vector.
4. Add a Name: Add "Frank" at the end of the Vector.
Page No.: 11

5. Delete a Name: Remove the name at the third position (index 2) from the Vector.
6. Display Contents: Print the contents of the Vector.
7. End: Terminate the program.

Result
Output printed successfully
FLOWCHART

Start

Define class MyThread extending Thread


Implement run() method
- Loop from 1 to 10
- Print the current value of i
- Sleep for 1000ms
- Catch InterruptedException

Define class ThreadDemo


- main() method
- Create an instance of MyThread
- Start the thread
- Sleep for 3000ms
- Call suspend() on thread
- Print "Thread suspended"
- Sleep for 3000ms
- Call resume() on thread
- Print "Thread resumed"
- Sleep for 3000ms
- Call stop() on thread
- Print "Thread stopped"
- Catch InterruptedException

Stop

OutPut

1
2
3
Thread suspended
Thread resumed
4
5
Thread stopped

Expt. No. 08 Page No.: 12

Write a Program to illustrate the use of stop() and suspend() methods

class MyThread extends Thread {


public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class ThreadDemo {


public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();

try {
Thread.sleep(3000);
thread.suspend();
System.out.println("Thread suspended");
Thread.sleep(3000);
thread.resume();
System.out.println("Thread resumed");
Thread.sleep(3000);
thread.stop();
System.out.println("Thread stopped");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Page No.: 13

Algorithm

1. Start: Begin the program execution.


2. Define MyThread Class:
o Step 2.1: Extend the Thread class.
o Step 2.2: Override the run() method:
 Step 2.2.1: Initialize a loop counter i to 1.
 Step 2.2.2: Loop while i is less than or equal to 10:
 Step 2.2.2.1: Print the value of i.
 Step 2.2.2.2: Increment i by 1.
 Step 2.2.2.3: Put the thread to sleep for 1000 milliseconds (1
second).
 Step 2.2.2.4: Catch and handle any InterruptedException.

3. Define ThreadDemo Class:


o Step 3.1: In the main() method:

 Step 3.1.1: Create an instance of MyThread named thread.


 Step 3.1.2: Start the thread, which initiates the run() method in
MyThread.
 Step 3.1.3: Put the main thread to sleep for 3000 milliseconds (3
seconds) to allow MyThread to run.
 Step 3.1.4: Call thread.suspend():
 Step 3.1.4.1: Suspend the execution of the thread.
 Step 3.1.4.2: Print "Thread suspended" to the console.

 Step 3.1.5: Put the main thread to sleep for another 3000 milliseconds
(3 seconds).
 Step 3.1.6: Call thread.resume():
 Step 3.1.6.1: Resume the execution of the thread.
 Step 3.1.6.2: Print "Thread resumed" to the console.

 Step 3.1.7: Put the main thread to sleep for another 3000 milliseconds
(3 seconds).
 Step 3.1.8: Call thread.stop():
 Step 3.1.8.1: Stop the execution of the thread.
 Step 3.1.8.2: Print "Thread stopped" to the console.

 Step 3.1.9: Catch and handle any InterruptedException during the


sleep periods.
4. End: Terminate the program.

Result
Output Printed Successfully

FLOWCHART

Start

Create instance of
ExceptionHandlingDemo

Try block
Call divideNumbers(10, 0)

No
Denominator == 0?
Print Result

Yes
throw ArithmeticException

Catch block
Handle ArithmeticException

Finally block
Print Message

Try block
Call checkAge(15)
Age < 18?

Print "Access granted

throw IllegalArgumentException

Catch block Handle IllegalArgumentException

Stop
Expt. No. 09 Page No.: 14

Write a program illustrating the use of exception handling by using try, catch,
finally, throw, and throws blocks

public class ExceptionHandlingDemo {

public static void main(String[] args) {


ExceptionHandlingDemo demo = new ExceptionHandlingDemo();
try {
demo.divideNumbers(10, 0); // This will throw an exception
} catch (ArithmeticException e) {
System.out.println("Caught an ArithmeticException: " + e.getMessage());
} finally {
System.out.println("Execution in finally block.");
}

try {
demo.checkAge(15); // This will throw an exception
} catch (IllegalArgumentException e) {
System.out.println("Caught an IllegalArgumentException: " + e.getMessage());
}
}

public void divideNumbers(int numerator, int denominator) throws ArithmeticException {


if (denominator == 0) {
throw new ArithmeticException("Denominator cannot be zero.");
}
System.out.println("Result: " + (numerator / denominator));
}

public void checkAge(int age) throws IllegalArgumentException {


if (age < 18) {
throw new IllegalArgumentException("Age must be at least 18.");
}
System.out.println("Access granted.");
}
}

OUTPUT

Caught an ArithmeticException: Denominator cannot be zero.

Execution in finally block.

Caught an IllegalArgumentException: Age must be at least 18.


Page No.: 15

Algorithm

1. Start: Initialize the program.


2. Main Method:
o Create an instance of ExceptionHandlingDemo.
o Try-Catch-Finally Block for divideNumbers method:
 Try: Call divideNumbers(10, 0).
 Catch: Handle ArithmeticException and print the message.
 Finally: Print a message indicating execution in the finally block.
o Try-Catch Block for checkAge method:
 Try: Call checkAge(15).
 Catch: Handle IllegalArgumentException and print the message.
3. divideNumbers Method:
o Check if the denominator is zero.
o If true, throw an ArithmeticException.
o Else, print the division result.
4. checkAge Method:
o Check if age is less than 18.
o If true, throw an IllegalArgumentException.
o Else, print "Access granted."
5. End: Terminate the program.

Result
Output Printed Successfully
FLOWCHART

Start

Define string text


"Hello, ByteArrayInputStream!"

Convert text to byte array


byte[] buffer = text.getBytes()

Create ByteArrayInputStream
ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer)

Read byte from inputStream


int data = inputStream.read()

While data != -1
Print character (char) data
Read next byte

Close inputStream
inputStream.close()

Stop
OUTPUT

Hello, ByteArrayInputStream!

Expt. No. 10 Page No.: 16

Write a program to illustrate the use ByteArrayInputStream method.

import java.io.ByteArrayInputStream;
import java.io.IOException;

public class ByteArrayInputStreamDemo {

public static void main(String[] args) {


String text = "Hello, ByteArrayInputStream!";
byte[] buffer = text.getBytes();

ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);

int data;
while ((data = inputStream.read()) != -1) {
char character = (char) data;
System.out.print(character);
}

try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Algorithm

1. Start: Initialize the program.


2. Define Input String: Create a string text containing the message.
3. Convert String to Byte Array: Convert text to a byte array buffer using getBytes().
4. Create ByteArrayInputStream: Create an instance of ByteArrayInputStream using
buffer.
5. Read from Stream:
o Initialize a variable data to store byte data.
o While Loop: Read from the stream using read(), which returns -1 at the end of the
stream.
o Convert the read byte data to a character and print it.
6. Close Stream: Close the ByteArrayInputStream.
7. End: Terminate the program.

Result
Output printed successfully.

You might also like