Skip to content

HARSHADA-PK/Oops-Module5

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

Oops-Module5

Ex.No:5(A) INPUT STREAM READER

QUESTION:

Write a program to demonstrate chaining of streams (BufferedReader on top of InputStreamReader on top of System.in)

AIM:

To demonstrate stream chaining in Java by combining InputStreamReader and BufferedReader to read user input efficiently from System.in.

ALGORITHM :

  1. Create a BufferedReader object by chaining System.in → InputStreamReader → BufferedReader.
  2. Read a line of text from the user and store it as the name.
  3. Read the next line, convert it into an integer, and store it as the age.
  4. Display the collected user details (name and age) on the screen.
  5. Use a try–with–resources block to automatically close the reader and catch any IOException.

PROGRAM:

/*
Program to implement a conditional statement using Java
Developed by: Harshada P K
RegisterNumber:  212224060097
*/

SOURCE CODE:

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

OUTPUT:

image

RESULT:

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.

Ex.No:5(B) SERIALIZATION AND DESERIALIZATION

QUESTION:

Write a Java program to serialize a collection of objects (like ArrayList) into a file.

AIM:

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.

ALGORITHM:

  1. Collect Student Data
    Read n from the user, then read each student’s id, name, and marks, creating Student objects and storing them in a list.
  2. Serialize the Student List
    Use ObjectOutputStream wrapped around FileOutputStream to write the entire List<Student> object into a file (students.dat).
  3. Deserialize the Student List
    Use ObjectInputStream wrapped around FileInputStream to read the serialized list back into a new list of Student objects.
  4. Handle Exceptions
    Use try–with–resources to automatically close streams and catch IOException and ClassNotFoundException for safe file operations.
  5. Display Results
    After deserialization, print each Student object using its overridden toString() method.

PROGRAM:

/*
Program to implement a conditional statement using Java
Developed by: Harshada P K
RegisterNumber:  212224060097
*/

SOURCE CODE:

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

OUTPUT:

image

RESULT:

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.

Ex.No:5(C) FILE HANDLING USING JAVA

QUESTION:

Ask the user for name, age, and email address. Write the collected data into a file called userdata.txt in a structured format.

AIM:

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.

ALGORITHM :

  1. Read User Input
    Accept name, age, and email from the user using Scanner.
  2. Write Data to File
    Create a FileWriter object, write formatted user information into the file userdata.txt, and close the writer.
  3. Read Data from File
    Create a BufferedReader wrapped around FileReader to open the same file.
  4. Print File Content
    Read each line using readLine() inside a loop and print it to the console.
  5. Handle Exceptions
    Use a try–catch block to manage errors related to file operations or invalid user input.

PROGRAM:

/*
Program to implement a conditional statement using Java
Developed by: Harshada P K
RegisterNumber:  212224060097
*/

SOURCE CODE:

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

OUTPUT:

image

RESULT:

The program successfully stores user details into a text file and reads them back line by line, displaying the stored content in the console.

Ex.No:5(D) THREAD PRIORITY

QUESTION:

Write a java program for determine the priority and name of the current thread.

Note : Read the threadname from the User

AIM:

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.

ALGORITHM :

  1. Create a class A that implements Runnable and override the run() method to print the current thread.
  2. In the main method, create an object of class A.
  3. Read a thread name from user input using Scanner.
  4. Create a new Thread object by passing the Runnable object and the thread name.
  5. Display the thread’s priority and name, then start the thread by calling t.start().

PROGRAM:

/*
Program to implement a conditional statement using Java
Developed by: Harshada P K
RegisterNumber:  212224060097
*/

SOURCE CODE:

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

OUTPUT:

image

RESULT:

The program successfully creates a thread with a user-given name, prints its priority and name, and displays the thread details when executed.

Ex.No:5(E) MULTITHREADING - SYNCHRONIZATION

QUESTION:

Synchronize deposit method in a BankAccount class, simulate deposits from multiple threads.

Input:

3 100 200 300

Output:

Final Balance: 600

AIM:

To simulate multiple concurrent deposits into a shared bank account using threads, ensuring thread-safety by synchronizing the deposit method.

ALGORITHM :

  1. Create a BankAccount class with a balance variable and a synchronized deposit(int amount) method.
  2. Create a DepositTask class extending Thread, storing a reference to BankAccount and the deposit amount, and call deposit() inside run().
  3. In main, read n (number of deposits), then read each deposit amount and create/start a thread for each.
  4. Use join() on all threads to ensure all deposits are completed.
  5. Print the final bank balance using getBalance().

PROGRAM:

/*
Program to implement a conditional statement using Java
Developed by: Harshada P K
RegisterNumber:  212224060097
*/

SOURCE CODE:

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

OUTPUT:

image

RESULT:

The program safely performs concurrent deposits using synchronized access and prints the correct final balance.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors