string is immutable in java you cant change a


 

String is immutable in java: you can't change a string object but can replace it by creating a new object instance. Creating a new instance is rather expensive.

 

//Non efficient version using immutable String

 

String out = "Some text"

 

Int cou = 80;

for(int i =0; i

output += i;

}

return out;

 

The above code would build 79 new String objects, of which 78 would be thrown away

immediately. Creating new objects is not efficient.

 

StringBuffer is mutable in java: use StringBuilder or StringBuffer when you want to change the contents. StringBuilder was started in Java 5 and it is identical in all function respects to StringBuffer except that it is not synchronized, which gives it slightly faster at the cost of not being thread-safe.

 

// efficient version of using mutable StringBuffer

StringBuffer out = new StringBuffer(110);// set an stating size of 110

out.append(" text");

for(int i =0; i

out.append(i);

}

return out.toString();

 

The above code builds only two new objects, the final String and the StringBuffer that is given. StringBuffer expands as needed, which is costly however, so it could be better to initialize the StringBuffer with the needed size from the start as shown.

 

Request for Solution File

Ask an Expert for Answer!!
JAVA Programming: string is immutable in java you cant change a
Reference No:- TGS0157363

Expected delivery within 24 Hours