Consider the following Java classes and main method. What will be printed when the program runs?
class Engine { int power; Engine(int power) { this.power = power; } int getPower() { return power; } } class Car { Engine engine; Car(Engine engine) { this.engine = engine; } int totalPower() { return engine.getPower() + 50; } } public class Main { public static void main(String[] args) { Engine e = new Engine(100); Car c = new Car(e); System.out.println(c.totalPower()); } }
Look at how Car uses the Engine object to calculate total power.
The Engine object has power 100. The Car adds 50 to this power in totalPower(). So the output is 150.
Given these classes, what will be printed?
class Wallet { private int money; Wallet(int money) { this.money = money; } void spend(int amount) { money -= amount; } int getMoney() { return money; } } class Person { Wallet wallet; Person(Wallet wallet) { this.wallet = wallet; } void buySomething(int price) { wallet.spend(price); } } public class Main { public static void main(String[] args) { Wallet w = new Wallet(200); Person p = new Person(w); p.buySomething(70); System.out.println(w.getMoney()); } }
Think about how the Person uses the Wallet to spend money.
The wallet starts with 200. The person spends 70, so 200 - 70 = 130 remains.
Examine the code below. What error will occur when running it?
class Book { String title; Book(String title) { this.title = title; } } class Library { Book book; Library() { // book not initialized } void printTitle() { System.out.println(book.title); } } public class Main { public static void main(String[] args) { Library lib = new Library(); lib.printTitle(); } }
Think about what happens if you try to access a field of an object that was never set.
The book field is never assigned an object, so it is null. Accessing book.title causes a NullPointerException.
Look at these code snippets. Which one will NOT compile?
Check if the object a is initialized before calling its method.
Option A declares a but does not initialize it. Calling a.foo() causes a compile error because a might not have been initialized.
Analyze the code below. How many objects are created and what is printed?
class Node { int value; Node next; Node(int value) { this.value = value; } void setNext(Node next) { this.next = next; } int sum() { if (next == null) return value; return value + next.sum(); } } public class Main { public static void main(String[] args) { Node n1 = new Node(1); Node n2 = new Node(2); Node n3 = new Node(3); n1.setNext(n2); n2.setNext(n3); System.out.println(n1.sum()); } }
Count each new Node(...) call and understand the recursive sum method.
Three Node objects are created (n1, n2, n3). The sum method adds 1 + 2 + 3 = 6.