Sunday, 9 February 2014
C# Java String Immutable means
String is immutable.
What exactly is the meaning?
immutable string in java
immutable string in c#
immutable string in java with example
immutable string class in java
|immutable string in java|
String is immutable means that you cannot change the object itself, but you can change the reference of course. When you called a = "ty", you are actually changing the reference of a to a new object created by the String literal "ty". Changing an object means to use its methods to change one of its fields, for example:
Foo x = new Foo("the field");
x.setField("a new field");
System.out.println(x.getField()); // prints "a new field"
While in an immutable class (declared as final, to prevent modification via inheritance), for example String, you cannot change the current String but you can return a new String, i.e:
String s = "some text";
System.out.println(s); // still printing "some text"
String a = s.substring(0,4);
System.out.println(a); // prints "some"
Immutable Objects (Java , C#)
In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created. In some cases, an object is considered immutable even if some internally-used attributes change but the object's state appears to be unchanging from an external point of view. For example, an object that uses memoization to cache the results of expensive computations could still be considered an immutable object.
Some very familiar examples of Object Oriented Languages are : C#, Java
and Functional Programming Languages : Haskell
Immutable objects are often useful because they are inherently thread-safe. Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects