Object showing instead of String when received through a stream

Hopefully I don't need to flood this post with my code, but if needed, please ask. Also, I only used getPassword().toString() for testing purposes, and I don't use it in any of my applications.

Client-Side: Grab password from JPasswordField passfield, send it as a String through ObjectOutputStream out

Server-Side: Receive String through ObjectInputStream in, print it to console

Easy enough, but the problem I'm having is that instead of the String showing, it prints an object ([C@6af3a631) The way I'm sending and receiving objects is pretty simple:

Client:

out.writeObject(passfield.getPassword().toString())

Server:

Object data;

while((data = in.readObject) != null) {
    if(data instanceof String) {
        System.out.println(data);
    }
}

If I send "hey" instead of passfield.getPassword().toString()), the String prints out just fine. I have been getting pretty familiar with ObjectOutputStream, and I've never encountered this problem, so I'm guessing it might have to do with the JPasswordField

This is a small step towards helping me understand bigger problem (packet containing password is sent just fine, packet is received just fine, but the password var comes in as null).

Jon Skeet
people
quotationmark

You're calling toString() on a char[]. That doesn't do what you think it does - it will return something like "[C@6af3a631" because arrays don't override toString(). You end up with the default implementation of toString() from Object:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object.

You can use:

// Eek - security problem!
out.writeObject(new String(passfield.getPassword());

... but that would leave a string hanging around in memory, which can't then be cleared. It's also transmitting the password in plaintext, which is awful unless this stream is secured in some other way.

I suspect you can just use:

out.writeObject(passfield.getPassword());

which will transmit the char[] as an object, and you'll get the same char[] out at the other end. It doesn't solve the "transmitting a password" problem though - and you'll still need to clear the char[] afterwards to avoid the password being accessible in memory.

people

See more on this question at Stackoverflow