Write a program to demonstrate chaining of streams (BufferedReader on top of InputStreamReader on top of System.in)
To demonstrate stream chaining in Java by combining InputStreamReader and BufferedReader to read user input efficiently from System.in.
- Create a
BufferedReaderobject by chainingSystem.in → InputStreamReader → BufferedReader. - Read a line of text from the user and store it as the name.
- Read the next line, convert it into an integer, and store it as the age.
- Display the collected user details (name and age) on the screen.
- Use a try–with–resources block to automatically close the reader and catch any
IOException.
/*
Program to implement a conditional statement using Java
Developed by: Harshada P K
RegisterNumber: 212224060097
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ChainingStreamsExample {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String name=br.readLine();
int age=Integer.parseInt(br.readLine());
System.out.println("--- User Details ---");
System.out.println("Name: "+name);
System.out.println("Age: "+age);
// Chaining: System.in -> InputStreamReader -> BufferedReader
//Write your code here
}
}
The program successfully reads multiple lines of user input using chained input streams and prints the user details. It demonstrates effective use of BufferedReader wrapped around InputStreamReader for fast and efficient input handling.
Write a Java program to serialize a collection of objects (like ArrayList) into a file.
To write a Java program that serializes a list of Student objects into a file and later deserializes them back, demonstrating Java’s object serialization mechanism using ObjectOutputStream and ObjectInputStream.
- Collect Student Data
Readnfrom the user, then read each student’sid,name, andmarks, creatingStudentobjects and storing them in a list. - Serialize the Student List
UseObjectOutputStreamwrapped aroundFileOutputStreamto write the entireList<Student>object into a file (students.dat). - Deserialize the Student List
UseObjectInputStreamwrapped aroundFileInputStreamto read the serialized list back into a new list ofStudentobjects. - Handle Exceptions
Use try–with–resources to automatically close streams and catchIOExceptionandClassNotFoundExceptionfor safe file operations. - Display Results
After deserialization, print eachStudentobject using its overriddentoString()method.
/*
Program to implement a conditional statement using Java
Developed by: Harshada P K
RegisterNumber: 212224060097
*/
import java.io.*;
import java.util.*;
// Student class must implement Serializable
class Student implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private double marks;
public Student(int id, String name, double marks) {
this.id = id;
this.name = name;
this.marks = marks;
}
@Override
public String toString() {
return "Student{id=" + id + ", name='" + name + "', marks=" + marks + "}";
}
}
public class StudentSerializationUserInput {
// Serialize list of students
public static void serializeStudents(List<Student> students, String fileName) {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName))) {
oos.writeObject(students);
System.out.println("Students serialized successfully into: " + fileName);
} catch (IOException e) {
System.out.println("Error during serialization: " + e.getMessage());
}
}
// Deserialize list of students
@SuppressWarnings("unchecked")
public static List<Student> deserializeStudents(String fileName) {
List<Student> students = null;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName))) {
students = (List<Student>) ois.readObject();
System.out.println("Students deserialized successfully from: " + fileName);
} catch (IOException | ClassNotFoundException e) {
System.out.println("Error during deserialization: " + e.getMessage());
}
return students;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Student> students = new ArrayList<>();
int n = scanner.nextInt();
scanner.nextLine(); // consume newline
for (int i = 0; i < n; i++) {
int id = scanner.nextInt();
scanner.nextLine(); // consume newline
String name = scanner.nextLine();
double marks = scanner.nextDouble();
scanner.nextLine(); // consume newline
students.add(new Student(id, name, marks));
}
String fileName = "students.dat";
// Serialize
serializeStudents(students, fileName);
// Deserialize
List<Student> deserializedStudents = deserializeStudents(fileName);
// Display deserialized data
if (deserializedStudents != null) {
System.out.println("\nDeserialized Students:");
for (Student s : deserializedStudents) {
System.out.println(s);
}
}
scanner.close();
}
}
The program successfully serializes a list of dynamically entered student objects into a file and retrieves them back through deserialization, verifying Java’s object persistence mechanism.
Ask the user for name, age, and email address. Write the collected data into a file called userdata.txt in a structured format.
To write user information (name, age, email) into a text file using FileWriter and then read the same content using BufferedReader, demonstrating basic file handling in Java.
- Read User Input
Accept name, age, and email from the user usingScanner. - Write Data to File
Create aFileWriterobject, write formatted user information into the fileuserdata.txt, and close the writer. - Read Data from File
Create aBufferedReaderwrapped aroundFileReaderto open the same file. - Print File Content
Read each line usingreadLine()inside a loop and print it to the console. - Handle Exceptions
Use atry–catchblock to manage errors related to file operations or invalid user input.
/*
Program to implement a conditional statement using Java
Developed by: Harshada P K
RegisterNumber: 212224060097
*/
import java.io.FileWriter;
import java.util.*;
public class main
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
try
{
String name=input.nextLine();
int age=input.nextInt();
input.nextLine();
String email=input.nextLine();
FileWriter f=new FileWriter("userdata.txt");
f.close();
System.out.println("User Information");
System.out.println("================");
System.out.println("Name : "+name);
System.out.println("Age : "+age);
System.out.println("Email : "+email);
}
catch(Exception e)
{
System.out.println();
}
}
}
The program successfully stores user details into a text file and reads them back line by line, displaying the stored content in the console.
Write a java program for determine the priority and name of the current thread.
Note : Read the threadname from the User
To create and execute a thread using the Runnable interface, set its name from user input, and display thread properties such as priority and name.
- Create a class
Athat implementsRunnableand override therun()method to print the current thread. - In the
mainmethod, create an object of classA. - Read a thread name from user input using
Scanner. - Create a new
Threadobject by passing theRunnableobject and the thread name. - Display the thread’s priority and name, then start the thread by calling
t.start().
/*
Program to implement a conditional statement using Java
Developed by: Harshada P K
RegisterNumber: 212224060097
*/
import java.util.*;
public class main
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
String name=input.nextLine();
Thread t=new Thread();
t.setName(name);
System.out.println("Priority of Thread: "+t.getPriority());
System.out.println("Name of Thread: "+t.getName());
System.out.println(t);
}
}
The program successfully creates a thread with a user-given name, prints its priority and name, and displays the thread details when executed.
Synchronize deposit method in a BankAccount class, simulate deposits from multiple threads.
Input:
3 100 200 300
Output:
Final Balance: 600
To simulate multiple concurrent deposits into a shared bank account using threads, ensuring thread-safety by synchronizing the deposit method.
- Create a
BankAccountclass with abalancevariable and a synchronizeddeposit(int amount)method. - Create a
DepositTaskclass extendingThread, storing a reference toBankAccountand the deposit amount, and calldeposit()insiderun(). - In
main, readn(number of deposits), then read each deposit amount and create/start a thread for each. - Use
join()on all threads to ensure all deposits are completed. - Print the final bank balance using
getBalance().
/*
Program to implement a conditional statement using Java
Developed by: Harshada P K
RegisterNumber: 212224060097
*/
import java.util.Scanner;
class BankAccount {
int balance = 0;
synchronized void deposit(int amount) {
balance = balance + amount;
}
}
class MyThread extends Thread {
BankAccount acc;
int amt;
MyThread(BankAccount acc, int amt) {
this.acc = acc;
this.amt = amt;
}
public void run() {
acc.deposit(amt);
}
}
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
BankAccount acc = new BankAccount();
MyThread[] t = new MyThread[n];
for (int i = 0; i < n; i++) {
int amount = sc.nextInt();
t[i] = new MyThread(acc, amount);
t[i].start();
}
for (int i = 0; i < n; i++) {
t[i].join();
}
System.out.println("Final Balance: " + acc.balance);
}
}
The program safely performs concurrent deposits using synchronized access and prints the correct final balance.