Question 331
public class Account
{
private String owner;
private int balance;
public Account(String o)
{
owner = o;
balance = 0;
}
public int getBalanceLen()
{
return ("" + balance).length();
}
public int getOwnerLen()
{
return owner.length();
}
}
Consider the following code segment.
Account a = new Account(null);
System.out.println(a.getBalanceLen());
System.out.println(a.getOwnerLen());
What is the result of executing the code segment?Main Solution
Solution:
Answer: A. getBalanceLen concatenates "" with the primitive balance, producing "0", whose length is 1 — the first line prints 1. The second call invokes owner.length() on a null reference, which throws NullPointerException at runtime. Concatenation of null never throws (Java produces "null"), but method invocation through a null reference always does.
Answer: Correct: A
Answer images

