Menu
Question Index
...

What will be the output of the following program?

import java.io.*;
public class SaveSecrets {

    public static void main(String[] args) {
        User user = new User("My User Name", "My Password");
        try {
            ObjectOutput out = new ObjectOutputStream(new FileOutputStream("secrets.txt"));
            user.writeExternal(out);
            out.close();
            ObjectInput in = new ObjectInputStream(new FileInputStream("secrets.txt"));
            user.readExternal(in);
            in.close();
        } catch (Exception e) {    }
        System.out.println(user);
    }
}

class User implements Externalizable {
    private String userName;
    private transient String password;
    public User(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        String line = in.readUTF();
        userName = line.split("~")[0];
        password = line.split("~")[0];
    }
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeUTF(userName + "~" + password);
    }
    public String toString() {
        return userName + " " + password;
    }
}


My User Name My Password
My User Name null
null My Password
Some other output not shown here
Compilation Error

Doubts

Problems

Topic: Java ObjectInputStream

Read this topic
Take test on this topic

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App