What will the following code print?
public class Main{ public static void stringMain (String s){ s.replace ('h ', 's'); } //from w w w. j a v a 2 s. c o m public static void stringBuilderMain (StringBuilder s){ s.append ("o"); } public static void main (String [] args){ String s = "hell"; StringBuilder sb = new StringBuilder ("well"); stringMain (s); stringBuilderMain (sb); System.out.println (s + sb); } }
Select 1 option
A. sellwello B. hellwello C. hellwell D. sellwell E. None of these.
Correct Option is : B
A String is immutable while a StringBuilder is not.
So in stringMain()
, "hell".replace('h ', 's') will produce a new String "sell" but will not affect the original String that was passed to the method.
However, the append()
method of StringBuilder appends to the original String object. So, "well" becomes wello
.