Chapter 4.1: Objects and Classes
Multiple Choice · Object-Oriented Programming
Question 1: Class and Object
Which statement is true about two objects created from the same class with new?
A: A class is a blueprint; every object carries its own copy of the instance fields. The method code exists only once, and this decides which object's data it works with (C is wrong). Sharing fields applies only to static fields (B).
Multiple Choice · Constructors
Question 2: Names and Default Values
Does the program compile? If it does, what does it print?
public class Example2 { private static int $; public static void main(String[] args) { String value_1 = "1"; System.out.print($); System.out.print(value_1); } }
B: $ is a valid name (letters, digits, _ and $; it cannot start with a digit). Fields get default values: a static int field is 0. The two print calls write side by side without a line break: 01. Local variables, on the other hand, get no default value; they cannot be read before being given one.
Output Question · Constructors
Question 3: A Box with Three Constructors
In main, new Box(); System.out.println(); new Box(1); System.out.println(); is run. What does the program print?
class Box { int width; Box() { this(2); System.out.print("A" + width); } Box(int width) { this(width, width * 3); System.out.print("B" + width); } Box(int width, int height) { this.width = width + height; System.out.print("C" + this.width); } }
Show answer
C8B2A8 C4B1
Box()first callsthis(2), which callsthis(2, 6): width = 2 + 6 = 8 →C8.- As the chain unwinds, each constructor runs the rest of its own body:
B2(the parameterwidth= 2), thenA8(the fieldwidth= 8). new Box(1):this(1, 3)→C4, thenB1. The no-argument constructor never runs.
Multiple Choice · Constructors
Question 4: A Constructor Written with void
What happens when Book b = new Book("Java"); is written in main?
class Book { String title; public void Book(String title) { this.title = title; } }
C: A constructor has no return type, not even void. Since this class has no constructor at all, the compiler adds only the no-argument default constructor; no suitable constructor is found for new Book("Java"): constructor Book in class Book cannot be applied to given types.
Step-by-Step Trace · Constructors
Question 5: A Constructor Chain with this(...)
Two objects are created. In which constructor, and in what order, do the fields get their values? What does the program print?
new allocates the object on the heap; the fields get default values: color = null, coats = 0. The no-argument constructor starts.
this("white") calls the other constructor for the same object: a new frame opens, and in both, this points to #1.
this.color is the object's field, and the color on the right is the parameter: the field becomes "white".
The constructor with a parameter sets coats to 1 and finishes; its frame closes.
The no-argument constructor continues where it left off: coats = 2. The last write wins; the value 1 was overwritten.
Both constructors are done; the reference, which is the value of the new expression, is assigned to e.
The second object is built directly with TrColor(String): "blue" and 1. This time the no-argument constructor never runs.
The output: white 2 and blue 1. Each object carries its own fields.
public class TrColor { private String color; private int coats; public TrColor() { this("white"); coats = 2; } public TrColor(String color) { this.color = color; coats = 1; } public static void main(String[] args) { TrColor e = new TrColor(); TrColor f = new TrColor("blue"); System.out.println(e.color + " " + e.coats); System.out.println(f.color + " " + f.coats); } }
Output Question · Constructors
Question 6: A Chain of Three Constructors
Three overloaded constructors call each other with this(...). What does the program print?
class Counter { int value; String name; Counter() { this(10); name = "first"; } Counter(int v) { value = v; } Counter(String n, int v) { this(v * 2); name = n; } } // in main: Counter c1 = new Counter(); Counter c2 = new Counter(5); Counter c3 = new Counter("x", 4); System.out.println(c1.value + " " + c1.name); System.out.println(c2.value + " " + c2.name); System.out.println(c3.value + " " + c3.name);
Show answer
10 first 5 null 8 x
new Counter(): firstthis(10)sets value = 10, then name = "first".new Counter(5): only value is assigned; since name is never assigned, the String field has its default value, null.new Counter("x", 4):this(8)→ value = 8, then name = "x".this(...)must be on the first line of the constructor.
Output Question · Fields
Question 7: Initialization Order
main is: System.out.print("M"); new B(); new B(); System.out.println();. What does the program print?
class B { static { System.out.print("S"); } int x = show("F"); { System.out.print("I"); } B() { System.out.print("C"); } static int show(String s) { System.out.print(s); return 1; } }
Show answer
MSFICFIC
mainfirst printsM; classBis loaded at the firstnew B()and thestaticblock runs once:S.- For every object the order is: field initial values and instance initializer blocks in the order they are written (
F,I), then the constructor body (C). - For the second object the
staticblock does not run again:FIC.
Multiple Choice · Methods
Question 8: A Missing return
Which statement is true about this method?
static int sign(int x) { if (x > 0) return 1; else if (x < 0) return -1; }
C: Every path of a method that returns int must end with return. When x == 0, both conditions are false and the end of the method is reached; the compiler sees this and does not run the program at all. The fix: add return 0; at the end.
Spot the Bug · static Members
Question 9: An Instance Member from a static Context
Does the program compile? If not, which lines give which error? Suggest two different fixes.
public class Tally { int count = 0; void increment() { count++; } public static void main(String[] args) { increment(); System.out.println(count); } }
Show answer
It does not compile; two errors:
error: non-static method increment() cannot be referenced from a static context error: non-static variable count cannot be referenced (same ending)
main is static: it has no object and no this; instance members need an object.
- Create an object:
Tally t = new Tally(); t.increment(); System.out.println(t.count);→1 - Make the members static:
static int countandstatic void increment()→1. Now all objects share the counter.
Step-by-Step Trace · static Members
Question 10: A static Ticket Counter
Each ticket takes a number from the shared counter. What does the line a.lastId = 500; change? What does the program print?
When the class is loaded, the static field is created once: lastId = 100. There are no objects yet.
The first object: id is 0 at first. The constructor increments the shared counter: 101.
id = lastId: the current value is copied into the object's own field.
The constructor finishes; a points to the first ticket.
The same steps for the second object: the counter is 102, #2.id = 102. #1.id does not change.
a.lastId is written through an object, but the field is static: the compiler treats it as Ticket.lastId = 500. There is no lastId inside the object.
The third ticket continues from 500: the counter is 501, #3.id = 501.
The output: 101 102 501 and 501 501. b.lastId reads the same single field too.
class Ticket { static int lastId = 100; int id; Ticket() { lastId++; id = lastId; } } public class TrTicket { public static void main(String[] args) { Ticket a = new Ticket(); Ticket b = new Ticket(); a.lastId = 500; Ticket c = new Ticket(); System.out.println(a.id + " " + b.id + " " + c.id); System.out.println(Ticket.lastId + " " + b.lastId); } }
Multiple Choice · References and this
Question 11: Which i?
What does the program print? (Each number on a separate line.)
public class Example5 { private static int i = 1; public static void main(String[] args) { System.out.println(i); int i = 2; Example5 example = new Example5(); System.out.println(i); example.show(); } public static void show() { System.out.println(i); } }
D: At the first println there is no local i yet; the static field is read: 1. After the local i = 2 is declared, it shadows the field in main: 2. In the frame of show there is no local i, and main's local is not visible: 1. A local variable with the same name as a field is legal (C is wrong).
Output Question · References and this
Question 12: An Alias
These lines run in main. What does the program print? How many Box objects are created?
class Box { int width; Box(int width) { this.width = width; } void grow(int amount) { width += amount; } } // in main: Box a = new Box(4); Box b = a; b.grow(3); a = new Box(1); a.grow(2); System.out.println(a.width + " " + b.width); System.out.println(a == b);
Show answer
3 7 false
b = adoes not copy the object, it copies the reference: both variables point to the same object.b.grow(3)makes that object go from 4 to 7.a = new Box(1)only bindsato the second object; the first object lives on throughb.a.grow(2)→ 3.- Two objects were created;
aandbnow point to different objects:false.
Step-by-Step Trace · References and this
Question 13: Pass by Value
The method takes a reference and an int. Which of the four assignments inside the method show up in main? What does the program print?
A Point object is created; n holds only its reference.
n.x = 1 writes into the object, and s = 1 into the primitive variable on the stack.
Java always passes by value: p is a copy of the reference (it points to the same object), and k is a copy of the number.
p.x = 5 changes the shared object; this change will be visible through n too.
k = 7 changes only the copy; s in main stays 1.
p = new Point() turns the copied reference toward a new object; n still points to #1.
9 is written into the new object; #1 is not affected.
The method ends and its frame is removed; no reference to #2 is left (it is up to the garbage collector). The output: 5 1.
class Point { int x; } public class TrPassing { static void move(Point p, int k) { p.x = 5; k = 7; p = new Point(); p.x = 9; } public static void main(String[] args) { Point n = new Point(); n.x = 1; int s = 1; move(n, s); System.out.println(n.x + " " + s); } }
Output Question · Comparing Objects
Question 14: == or equals?
The Money class does not override equals. What does the program print?
class Money { int tl; Money(int tl) { this.tl = tl; } } // in main: String a = "ab"; String b = new String("ab"); Money p = new Money(5); Money q = new Money(5); Money r = p; System.out.println(a == b); System.out.println(a.equals(b)); System.out.println(p.equals(q)); System.out.println(p.equals(r)); System.out.println(p.tl == q.tl);
Show answer
false true false true true
new String("ab")is a separate object:==compares references →false;String.equalscompares content →true.- Since
equalsis not written inMoney, the version fromObjectruns, and it behaves like==:p.equals(q)→false,p.equals(r)→true(the same object). p.tl == q.tlcompares twoints →true.
Multiple Choice · Wrapper Classes
Question 15: The Integer Cache
What does the program print on the first line?
Integer a = 100, b = 100;
Integer c = 200, d = 200;
System.out.println((a == b) + " " + (c == d));
System.out.println(c.equals(d));
int e = 200;
System.out.println(c == e);B: Integer a = 100 uses Integer.valueOf in autoboxing; values between −128 and 127 come from the cache as the same object: a == b → true. For 200 two separate objects are created: false. For content, c.equals(d) is used (true); in a comparison with an int such as c == e, the box is unboxed and the result is true.
Output Question · Records and enum
Question 16: enum Values
What does the program print? What would happen if Season.valueOf("Winter") were called?
enum Season { SPRING, SUMMER, AUTUMN, WINTER } // in main: Season m = Season.valueOf("AUTUMN"); Season[] t = Season.values(); System.out.println(m.ordinal() + " " + t.length); System.out.println(m == Season.AUTUMN); System.out.println(t[1]); for (Season x : t) { if (x.ordinal() % 2 == 1) System.out.print(x + " "); } System.out.println();
Show answer
2 4 true SUMMER SUMMER WINTER
ordinal()starts at 0:AUTUMN→ 2;values()returns an array of four elements.- Every enum value is a single object; comparing with
==is safe. - The ones with an odd ordinal: 1 (
SUMMER) and 3 (WINTER). valueOflooks for the name exactly (including case): for"Winter",IllegalArgumentException: No enum constant Season.Winterat run time.
Output Question · Inner Classes
Question 17: Three x's
The member inner class Inner accesses a private field of the outer class. What does the program print?
public class Outer { private int x = 10; class Inner { int x = 20; void show(int x) { System.out.println(x + " " + this.x + " " + Outer.this.x); } } static int x() { return 5; } public static void main(String[] args) { Outer o = new Outer(); Outer.Inner i = o.new Inner(); i.show(30); o.x = 15; i.show(x()); } }
Show answer
30 20 10 5 20 15
- A plain
xis the nearest declaration: the parameter.this.xis the field of the inner object, andOuter.this.xis the field of the outer object it is bound to. o.new Inner(): a member inner class object is created bound to an outer object; aftero.x = 15, the inner object sees the same outer object.- In the second call the argument is the 5 returned by the
staticmethodx().
Multiple Choice · Class Types and Design
Question 18: Singleton
The only object of the class Settings, whose constructor is private, is obtained with getInstance(). What does the program print?
class Settings { private static final Settings ONLY = new Settings(); private int language = 1; private Settings() { } static Settings getInstance() { return ONLY; } void setLanguage(int l) { language = l; } int getLanguage() { return language; } } // in main: Settings a = Settings.getInstance(); Settings b = Settings.getInstance(); a.setLanguage(2); System.out.println(b.getLanguage() + " " + (a == b));
C: getInstance() returns the same static final object on every call; a and b are two references to the same object. a.setLanguage(2) changes the shared object: b.getLanguage() → 2, a == b → true. Writing new Settings() from another class does not compile: Settings() has private access in Settings.