OCP Stage 2 Problem 1.20 – Explanation

Given the code fragment:

String str = "Powers of 2";
int a = 8, b = 256;
StringBuilder sb = new StringBuilder(str);

sb.append(a);           // n1
sb.append(b);           // n2
sb.append(a > b);       // n3
sb.append(a < b);       // n4
sb.insert(a, "" + a);   // n5
sb.insert(b, "" + b);   // n6

Which line will throw a runtime exception?

A. n1
B. n2
C. n3
D. n4
E. n5
F. n6

 

The correct answer is F.

 

The StringBuilder class’s append() method might throw an exception only when we specify an index as one of the method’s arguments, like in:

sb.append(new char[]{‘a’,’b’,’c’}, 0, 10);

In the above example, we are attempting to append a part of the char array, which sits between indices 0 and 10, but the array itself is just three element long. This LOC will obviously throw an AIOOBE.

Our Problem does not specify indices in options A through D, which automatically makes them RTE-free:

  • option A appends the string representation of 8,
  • then option B does the same for 256, so now the sb object contains “Powers of 28256”,
  • then options C and D append false followed by true.

On the other hand, options E and F are featuring the insert() method, which uses at least one index by definition; after all, it does need to know where to insert something, right? This makes line n5 and n6 prime suspects for throwing an SIOOBE.

By comparing two indices – that is, 8 and 256 – we immediately realize that whatever the sb objects contains by now is way too short to accept anything for its (256-1)th position.

 

Takeaway:
The StringBuilder‘s append() is overloaded for all imaginable types. The StringBuilder#insert() method might throw a run-time exception if its index is negative or overshoots sb.length()-1.

 

Objective:
Java Class Design

Sub-Objective:
Create and use singleton classes and immutable classes

Leave Comment

Your email address will not be published.