String is a immutable object, where StringBuffer is a mutable object in java. Still you'll be able to change string using '+' operator. But every time you add some thing to string object using '+', a new string object is created, So, more memory is need to hold those new objects. If you just use concat method of string object, it'll not concatenate the new string as shown in below example.
String abc = "Hello ";
abc.concat("changed");
System.out.println(abc);
Most of the people think that output of the above example is 'Hello changed' (with out single quotes). That's correct, but new object has been created with value 'Hello changed' (Without single quotes) and the previous value is recommended for garbage collection.
String abc = "Hello ";
abc += "changed";
System.out.println(abc);
Output of the above code is 'Hello changed' (without single quotes). But, a new string object is created to hold the string "Hello changed".
If you use StringBuffer instead of String in the above two examples you'll save memory(example 2) and you'll get the output what you intended for (example 1) as shown in the below example
StringBuffer abc = new StringBuffer("Hello ");
abc.append("changed");
System.out.println(abc);
Output: Hello changed
String abc = "Hello ";
abc.concat("changed");
System.out.println(abc);
Most of the people think that output of the above example is 'Hello changed' (with out single quotes). That's correct, but new object has been created with value 'Hello changed' (Without single quotes) and the previous value is recommended for garbage collection.
String abc = "Hello ";
abc += "changed";
System.out.println(abc);
Output of the above code is 'Hello changed' (without single quotes). But, a new string object is created to hold the string "Hello changed".
If you use StringBuffer instead of String in the above two examples you'll save memory(example 2) and you'll get the output what you intended for (example 1) as shown in the below example
StringBuffer abc = new StringBuffer("Hello ");
abc.append("changed");
System.out.println(abc);
Output: Hello changed
No comments:
Post a Comment