Skip to content

Instantly share code, notes, and snippets.

@reynir
Forked from tonymorris/EggsToast.java
Created August 29, 2016 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reynir/f8c341eaf7a49722b1388bf0fccb7806 to your computer and use it in GitHub Desktop.
Save reynir/f8c341eaf7a49722b1388bf0fccb7806 to your computer and use it in GitHub Desktop.
What is the output of this program?
// What is the output of this program?
// a) x = 2
// b) x = 3
// c) compile-error
// d) runtime exception
// e) something else _____
abstract class Eggs {
abstract void m();
Eggs() {
m();
}
}
class Toast extends Eggs {
private int x = 2;
Toast() {
m();
x = 3;
m();
}
public void m() {
System.out.println("x = " + x);
try {
throw new Throwable();
} catch (Throwable t) {
t.printStackTrace();
}
}
public static void main(String[] args) {
new Toast();
}
}
@reynir
Copy link
Author

reynir commented Aug 29, 2016

The output for reference

$ java Toast 
x = 0
java.lang.Throwable
    at Toast.m(EggsToast.java:27)
    at Eggs.<init>(EggsToast.java:11)
    at Toast.<init>(EggsToast.java:18)
    at Toast.main(EggsToast.java:34)
x = 2
java.lang.Throwable
    at Toast.m(EggsToast.java:27)
    at Toast.<init>(EggsToast.java:19)
    at Toast.main(EggsToast.java:34)
x = 3
java.lang.Throwable
    at Toast.m(EggsToast.java:27)
    at Toast.<init>(EggsToast.java:21)
    at Toast.main(EggsToast.java:34)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment