I was wondering if the following simple method is sufficient to show that StringBuilder's toString() and substring() will not return an interned string, while String's same methods will?
Code: Select all
void checkInterned (){
String s = "checks";
StringBuilder sb = new StringBuilder("checksb");
if (sb.substring(0) == sb.substring(0))
System.out.println("StringBuilder's substring returns interned string");
if (sb.toString() == sb.toString())
System.out.println("StringBuilder's toString returns interned string");
if (s.substring(0) == s.substring(0))
System.out.println("String's substring returns interned string");
if (s.toString() == s.toString())
System.out.println("String's toString returns interned string");
}
Code: Select all
//Excercise 5
String changeStringBuilder (StringBuilder sb){
try{
return sb.replace(0, sb.length()-4, "X").toString();
}catch(IndexOutOfBoundsException e){
return "Input must contain at least 4 characters.";
}
}
- please find the different calls from TestClass' main(). Is that sufficient variation to make sure the method can cover all basis?
- as for
since the incoming array and its components are Strings, I don't see what would be the point of all the extra back and forth conversions code that would be needed in order to make use of StringBuilder. The only possible advantage I see in using StringBuilder here, is if there is concern for saving heap memory space with so many Strings being created. If that is the point, then I would change the parameter from String[] to StringBuilder[] to save a lot of extra conversion coding as well. Yes, No?Is this a good place to make use of a StringBuilder?
Code: Select all
//the method
String stringArray (String[] sa){
String sf = "";
for (String s : sa)
sf += s;
return sf;
}
//the calls from TestClass's main()
String[] stra1 = new String[]{"1", null, "hello", "", "null", null, " ", "W"};
System.out.println("\n"+ss.stringArray(stra1));
String[] stra2 = new String[]{null, null};
System.out.println(ss.stringArray(stra2));
String[] stra3 = new String[]{""};
System.out.println(ss.stringArray(stra3));
String[] stra4 = new String[]{"", null, "", null};
System.out.println(ss.stringArray(stra4));