Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Friday, November 30, 2012

Strings in Java

Differences between creating String as new() and literal assigning?
Described as code, the question transforms in this:
String a = "abc";
String c = new String("abc");


Just a note, which is basic for all comments below – String in Java is immutable.
When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

Lets look some functionality differences:

Thursday, November 29, 2012

Immutable objects

Immutable objects
Immutable objects are objects whose state cannot change after construction. Examples of immutable objects from the JDK include String and Integer. (String methods, such as String.replace do not change the instance, but create new Strings)

Requirements for immutable classes:
•    ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private;
•    make fields private and final;
•    force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setter methods
•    do not provide any methods which can change the state of the object in any way;