Posted on

Java feature/bug

1.

public static void main(String[] args) {
        System.out.println(Byte.valueOf((byte) 48)   == Byte.valueOf((byte) 48));
        System.out.println(Byte.valueOf((byte) 248)  == Byte.valueOf((byte) 248));
        System.out.println(Integer.valueOf(48)       == Integer.valueOf(48));
        System.out.println(Integer.valueOf(248)      == Integer.valueOf(248));
    }

Answer

true
true
true
false

2.

class TrickyClass {
    { value = 10; }
    private int value = 20;
    { value = 30;}
    public int getValue() { return value; }
    public static void main(String[] args) {
       System.out.println(new TrickyClass().getValue());
    }
}

Answer

 30;

3.

class Base {
   public Base() {
       System.out.println(getName());
   }
   protected String getName() { return "Base";}
}

class Derived extends Base {
   private String name = "Derived";
   @Override
   protected String getName() { return this.name;}
   public static void main(String[] args) {
       new Derived();
   }
}

Answer

null

4.

public class User implements Serializable {

    public final String name;

    public User(String name) { this.name = name; }

    private Object readResolve() { return new User("Darth Vader"); }


    public static void main(String[] args) throws Exception {
        User user = new User("Anakin Skywalker");

        // Serialize user
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        new ObjectOutputStream(outputStream).writeObject(user);

        // Deserialize user
        ByteArrayInputStream inputStreamStream = new ByteArrayInputStream(outputStream.toByteArray());
        User readUser = (User) new ObjectInputStream(inputStreamStream).readObject();

        System.out.println(readUser.name);
    }
}

Answer

Darth Vader

 

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.