Thursday, September 19

String concatenation trimming ,String immutability ,java String and memory management

String concatenation trimming ,String immutability ,java String and memory management





String s="hello";

This created an oject in memory

Object = "hello"    Reference =s

s+="World "

This creates a new object in memory

Object ="hellow world "  reference =s

Now in total , there are two objects in memory

 Object ="hellow world"  reference =s
Object = "hello"    Reference = none (no reference of "hello" object available)


s.trim();

What happens here?

A new object is created.

So now there are three objects memory

"hello"
"hello world "
"hello world"

and only "hello world " has a reference to it.






Strings are immutable objects. So once created can't be modified . On modification Java creates another String instance in memory. String pool maintains all string values at single place and If same oject is created multiple times java does not create multiple objects in memory but add reference to existing object. Thus an String can have multiple references in Java.










No comments:

Post a Comment