Constructors
Computer Science · Java
Question 1 of 10
0What number does this Java code print? public class Main { public static void main(String[] args) { Robot b = new Robot(6); System.out.println(b.size); } } class Robot { int size; Robot(int s) { size = s * 3; } }
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Constructors explained
A constructor is a special method that runs when an object is created with new, and it sets up the object's starting state. It has the same name as its class and no return type, not even void.
If a class has no constructor, Java provides a default one that takes no arguments and sets fields to their default values, such as 0 for an int and null for an object. Once you write any constructor, that default is no longer provided unless you write it yourself. A class can have several constructors with different parameters. Inside a constructor, this.title refers to the field, which lets a parameter share its name with the field. If a constructor writes only title = title;, the field keeps its default value.
class Book {
String title;
int pages;
Book(String title, int pages) {
this.title = title;
this.pages = pages;
}
}
Book b = new Book("Notes", 120);
Worked example
Trace the code above.
- new Book("Notes", 120) matches the two-parameter constructor.
- this.title = title stores "Notes" in the title field.
- this.pages = pages stores 120 in the pages field.
- b.pages now returns 120. If the constructor had written only pages = pages, b.pages would stay 0.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What number does this Java code print?
public class Main { public static void main(String[] args) { Widget b = new Widget(4); System.out.println(b.size); } }
class Widget { int size;
Widget(int s) { size = s * 3; } }
Medium
What number does this Java code print?
public class Main { public static void main(String[] args) { System.out.println(new Widget().size); } }
class Widget { int size;
Widget() { this(4); size = size + 4; }
Widget(int s) { size = s * 4; } }
Hard
What number does this Java code print?
public class Main { public static void main(String[] args) { System.out.println(new Box().size); } }
class Box { int base = 3; int size;
Box(int s) { size = base + s; }
Box() { this(2); size = size * 4; } }