Sec 4: String Handling
Last updated
Last updated
The simple meaning of immutable is unmodifiable or unchangeable. Once string object has been created, its value can't be changed.
Because java uses the concept of string literal. Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.
There are two ways to create the string object, by string literal and by new keyword. 1) String Literal
2) By new keyword
Only one object.
To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).
Two objects, one in string constant pool and other in non-pool(heap).
String is an immutable object. StringBuffer is a mutable object.
StringBuffer is synchronized whereas StringBuilder is not synchronized. StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isn’t thread safe).
We can also create immutable class by creating final class that have final data members
The toString() method returns the string representation of any object. If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.