Posted on Leave a comment

Java feature/bug

1.

[code language=”java”]
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));
}
[/code]

Answer

[code language=”java”]
true
true
true
false
[/code]

2.

[code language=”java”]
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());
}
}
[/code]

Answer
[code]
30;
[/code]

3.
[code language=”java”]
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();
}
}
[/code]

Answer

[code language=”java”]
null
[/code]

4.

[code language=”java”]
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);
}
}
[/code]

Answer

[code language=”java”]
Darth Vader
[/code]

 

Leave a Reply

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