AP Computer Science A · Topic 5.2
Constructors Practice
Part of Writing Classes.
Practice questions
19
Sample questions
5 of 19 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
public class Counter { private int count; public Counter() { count = 0; } public void inc() { count++; } public int getCount() { return count; } } // ... Counter c = new Counter(); c.inc(); c.inc(); c.inc(); System.out.println(c.getCount());What is printed?
- Acheck_circle
3
- B
0
- C
1
- D
Compile-time error
Why
The default constructor sets count to 0; inc() is called three times, so count becomes 3.
- A
Sample 2difficulty 2/5
public class Foo { public void Foo() { System.out.println("ctor?"); } } // ... Foo f = new Foo();What happens?
- Acheck_circle
Nothing is printed; Java's default constructor was used
- B
Run-time error
- C
Compile-time error
- D
ctor? is printed
Why
Foo here is a regular method (it has return type void), not a constructor; the implicit default constructor runs and produces no output.
- A
Sample 3difficulty 2/5
public class Greeter { private String greeting; public Greeter() { greeting = "Hello"; } public Greeter(String g) { greeting = g; } public String say() { return greeting; } } // ... Greeter g = new Greeter("Hola"); System.out.println(g.say());What is printed?
- Acheck_circle
Hola
- B
Hello
- C
null
- D
Compile-time error
Why
The String-parameter constructor sets greeting to "Hola".
- A
Sample 4difficulty 2/5
public class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } } // ... Point p = new Point(4, 7); System.out.println(p.getX() + "," + p.getY());What is printed?
- A
Compile-time error
- B
7,4
- C
0,0
- Dcheck_circle
4,7
Why
The constructor uses this.x = x and this.y = y to assign instance variables, so getX returns 4 and getY returns 7.
- A
Sample 5difficulty 2/5
public class Item { private String name; private double price; public Item() { name = "?"; price = 0.0; } public Item(String n, double p) { name = n; price = p; } public String getName() { return name; } } // ... Item i = new Item(); System.out.println(i.getName());What is printed?
- A
0.0
- B
null
- Ccheck_circle
?
- D
Compile-time error
Why
The no-argument constructor sets name to "?" and price to 0.0.
- A