Wednesday, September 24, 2014

JAVA: Be careful with String class - General

 

1. JAVA only puts primitive and reference variable onto Stack while all objects, including String, is created and stays on the Heap, subject to GC

http://programmers.stackexchange.com/questions/65281/stack-and-heap-memory-in-java/65289#65289

 

2. String literal value assignment such as

String str1 = “abcd”;

and String variable assignment such as

String str2 = str1

will create these new String objects (which are reference objects) and both str1 and str2 will point to the same object with value “abcd” in the JVM’s internal String Pool

 

3. String Value Object itself, not the reference that points to it, is IMMUTABLE (i.e.the String Class itself is ‘final’), meaning the whenever you try to

String str = someOpToModify(str);

What happens is that another String Value Object is created on the String Pool and this ‘str’ String Reference Object is not changed to point at this new String Value Object rather than the old String Value Object that contains the old value before modification.

http://stackoverflow.com/questions/8798403/string-is-immutable-what-exactly-is-the-meaning/17942294#17942294

 

4. Only way to make sure a new Object of String is created in the String Pool is to call: String str3 = new String(“abcd”);

5. Why to make the String immutable?

http://stackoverflow.com/questions/2068804/why-is-string-final-in-java/2069014#2069014

  1. Security: the system can hand out sensitive bits of read-only information without worrying that they will be altered
  2. Performance: immutable data is very useful in making things thread-safe.

 

 

All and all, be very careful with String in JAVA, especially when it comes to performance and if you have a lot of long Strings to load into the memory:

http://www.javamex.com/tutorials/memory/string_saving_memory.shtml

1 comment:

  1. Arguably the most exciting technology currently on the .NET Framework, .NET Core is an open-source general-purpose development platform that Microsoft and the wider .NET community maintain. If you are a freelance net full stack developer, you can get more relevant projects on Eiliana.com, where top clients regularly post IT development projects.

    ReplyDelete