Consider the following Java class without a constructor. What will be the output when creating an object and printing its value?
public class Box { int size; public static void main(String[] args) { Box b = new Box(); System.out.println(b.size); } }
Think about default values for uninitialized int fields in Java.
In Java, if no constructor is defined, a default constructor is provided. The int field 'size' is initialized to 0 by default, so printing it outputs 0.
What will happen when you try to compile and run this Java code?
public class Box { int size; public Box(int size) { this.size = size; } public static void main(String[] args) { Box b = new Box(); System.out.println(b.size); } }
Check if the constructor call matches any defined constructor.
When a constructor with parameters is defined, Java does not provide a default no-argument constructor. Trying to call 'new Box()' causes a compilation error.
Which of the following best explains why constructors are needed in Java?
Think about what happens when you create a new object and want it to start with certain values.
Constructors let you set initial values for an object's fields when you create it, ensuring the object starts in a valid state.
What will this Java program print?
public class Box { int size; public Box() { this.size = 10; } public Box(int size) { this.size = size; } public static void main(String[] args) { Box b1 = new Box(); Box b2 = new Box(20); System.out.println(b1.size + "," + b2.size); } }
Look at which constructor is called for each object.
The first object uses the no-argument constructor setting size to 10. The second uses the parameterized constructor setting size to 20. So output is '10,20'.
Why do constructors help make Java programs safer and less error-prone?
Think about what happens if an object is used without setting its fields.
Constructors guarantee that objects start with valid data, preventing bugs from uninitialized fields.