Challenge - 5 Problems
Java Default Values Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of uninitialized instance variables
What is the output of this Java program?
Java
public class Test { int number; boolean flag; String text; public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.number + "," + obj.flag + "," + obj.text); } }
Attempts:
2 left
💡 Hint
Instance variables have default values if not initialized.
✗ Incorrect
In Java, instance variables of type int default to 0, boolean to false, and object references like String to null.
❓ Predict Output
intermediate2:00remaining
Default values of local variables
What happens when you try to compile and run this Java code?
Java
public class Test { public static void main(String[] args) { int x; System.out.println(x); } }
Attempts:
2 left
💡 Hint
Local variables must be initialized before use.
✗ Incorrect
Local variables in Java do not have default values and must be explicitly initialized before use, otherwise compilation fails.
❓ Predict Output
advanced2:00remaining
Default values in arrays
What is the output of this Java program?
Java
public class Test { public static void main(String[] args) { boolean[] flags = new boolean[3]; System.out.println(flags[1]); } }
Attempts:
2 left
💡 Hint
Array elements have default values based on their type.
✗ Incorrect
Boolean array elements default to false in Java.
❓ Predict Output
advanced2:00remaining
Default values of object fields in inheritance
What is the output of this Java program?
Java
class Parent { int value; } class Child extends Parent { boolean flag; } public class Test { public static void main(String[] args) { Child c = new Child(); System.out.println(c.value + "," + c.flag); } }
Attempts:
2 left
💡 Hint
Inherited fields also get default values.
✗ Incorrect
Both inherited int and boolean fields get default values 0 and false respectively.
🧠 Conceptual
expert2:00remaining
Default values of static variables
Consider this Java class with static variables. What is the value of staticVar after the program runs?
Java
public class Test { static int staticVar; public static void main(String[] args) { System.out.println(staticVar); } }
Attempts:
2 left
💡 Hint
Static variables also get default values if not initialized.
✗ Incorrect
Static variables of primitive types get default values like instance variables. int defaults to 0.