Thursday, February 10, 2011

Strings Are Immutable

C# has a System.String class which is analogous to the java.lang.String class. Both classes are immutable meaning that the values of the strings cannot be changed once the strings have been created. In both instances methods that appear to modify the actual content of a string actually create a new string to return, leaving the original string unchanged. Thus the following C# and Java code does not modify the string in either case
C# Code
String csString = "Apple Jack";
csString.ToLower(); /* Does not modify string, instead returns lower case copy of string */

Java Code
String jString = "Grapes";
jString.toLowerCase(); /* Does not modify string, instead returns lower case copy of string */
To create a string-like object that allows modification in C# it is advisable to use the System.Text.StringBuilder class whereas in Java one would use the java.lang.StringBuffer class.

NOTE: In C#, the string class can either be written as string or String.

No comments:

Post a Comment