Showing posts with label String. Show all posts
Showing posts with label String. Show all posts

Monday, 23 January 2017

What is an Immutable Class ? How to create Immutable class ? What are the advantage of Immutability ? Why is it important in multi-threading context ? Can you write a Custom immutable class ? What are semantics for writing an Immutable Class in java ?

In this article we will discuss  about following  topic
è What is an Immutable Class ?
è How to create Immutable class ?
è Write a Custom immutable class ?
è What are the advantage of  Immutability ?
è Why is it important in multi-threading context ?
è What are semantics for writing an Immutable Class in java ?

What is an Immutable Class ?
As per Oracle docs , An Immutable class is a class if its state of object  cannot change after it is constructed. It means any modification of  Immutable object will be another immutable object.  Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe.All wrapper classes in java.lang are immutable  String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger.

Read this article :

Why is String immutable?


Example of  Immutable class:
·         java.lang.String
·         The wrapper classes for the primitive types: java.lang.Integer, java.lang.Byte, java.lang.Character, java.lang.Short, java.lang.Boolean, java.lang.Long, java.lang.Double, java.lang.Float
·         java.lang.StackTraceElement (used in building exception stacktraces)
·         Most enum classes are immutable, but this in fact depends on the concrete case. (Don't implement mutable enums, this will screw you up somewhen.) I think that at least all enum classes in the standard API are in fact immutable.
·         java.math.BigInteger and java.math.BigDecimal (at least objects of those classes themselves, subclasses could introduce mutability, though this is not a good idea)
·         java.io.File. Note that this represents an object external to the VM (a file on the local system), which may or may not exist, and has some methods modifying and querying the state of this external object. But the File object itself stays immutable. (All other classes in java.io are mutable.)
·         java.awt.Font - representing a font for drawing text on the screen (there may be some mutable subclasses, but this would certainly not be useful)
·         java.awt.BasicStroke - a helper object for drawing lines on graphic contexts
·         java.awt.Color - (at least objects of this class, some subclasses may be mutable or depending on some external factors (like system colors)), and most other implementations of java.awt.Paint .
How to create Immutable class ?
The steps to create a Immutable class  in Java  -
1)    Mark the class final .
2)    Mark the fields private and final.
3)    Set the values of properties of the class final and Private , i.e do not  use any setter methods,.
4)    Do not change the state of  the objects in any methods of  the class. If the instance fields includes references to mutable objects, don’t allow those objects to be changed.
5)    Don’t provide methods that modified the mutable objects.
6)    Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
Write a Custom immutable class ?

Example of  Immutable class in Java:

package Java91.blogspot.in;

public final class TestImmutableClass {
       private final Integer id;
       private final String name;
       private final String password;

       public TestImmutableClass(Integer id, String name, String password) {
              super();
              this.id = id;
              this.name = name;
              this.password = password;
       }
      
       public Integer getId() {
              return id;
       }

       public String getName() {
              return name;
       }

       public String getPassword() {
              return password;
       }
}
What are the advantage of  Immutability ?
1.     Immutable objects are thread-safe so you will not have any synchronization issues.
2.     Immutable objects are good Map keys and Set elements, since these typically do not change once created.
3.     Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged)
4.     Immutability makes it easier to parallelize your program as there are no conflicts among objects.
5.     The internal state of your program will be consistent even if you have exceptions.
6.     References to immutable objects can be cached as they are not going to change.
In Java the good programming practice is one should try to use immutable objects as far as possible. Immutability can have a performance cost, since when an object cannot be mutated we need to copy it if we want to write to it.
By Joshua Bloch
Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible.
Why is it important in multi-threading context ?
As we all know if an object is  Immutable , it is thread safe. But some scenario It is not thread safe . I am going to explain why Immutable class not fully thread safe .
Let look into the  String class code:
public class String {
       private final char value[];
       /** Cache the hash code for the string */
       private int hash; // Default to 0

       public String(char[] value) {
              this.value = Arrays.copyOf(value, value.length);
       }

       public int hashCode() {
              int h = hash;
              if (h == 0 && value.length > 0) {
                     char val[] = value;
                     for (int i = 0; i < value.length; i++) {
                           h = 31 * h + val[i];
                     }
                     hash = h;
              }
              return h;
       }
}
String is considered immutable. Looking at its implementation, we can deduce one thing: an immutable string can change its internal state (in this case, the hashcode which is lazy loaded) as long as it is not externally visible.Now I am going to rewrite the hashcode method in a non-thread safe way:
public int hashCode() {
    if (hash == 0 && value.length > 0) {
        char val[] = value;
        for (int i = 0; i < value.length; i++) {
            hash = 31 * hash + val[i];
        }
    }
    return hash;
}
As you can see, I have removed the local variable h and I have instead affected the variable hash directly. This implementation is NOT thread safe! If several threads call hashcode at the same time, the returned value could be different for each thread. The question is, 'is this class immutable?' Since two different threads can see a different hashcode, in an external point of view we have a change of state and so it is not immutable.We can so conclude that String is immutable because it is thread safe and not the opposite. So... What's the point of saying "Use an immutable object, it is thread-safe! But take care, you have to make your immutable object thread-safe!"?
What are semantics for writing an Immutable Class in java ?
1.     Immutable objects are thread-safe so you will not have any synchronization issues.
2.     Immutable objects are good Map keys and Set elements, since these typically do not change once created.
3.     Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged)
4.     Immutability makes it easier to parallelize your program as there are no conflicts among objects.
5.     The internal state of your program will be consistent even if you have exceptions.
6.     References to immutable objects can be cached as they are not going to change.

















Tuesday, 17 January 2017

Why is String immutable?

·   It is mainly for security reasons. String is used as parameter in network connection, database url etc. It can be easily attacked if it is mutable·Immutability of String solves some synchronization issues, it makes the String thread safe· To support StringPool facility· To cache the hashcode of String To support class loading mechanism in which String is used as arguments. String being mutable results in wrong class being loaded.

What is Immutable objects ? Why String is immutable in Java ?

Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer.
Immutable objects greatly simplify your program since they:

1) Are simple to construct, test, and use.
2) Are automatically thread-safe and have no synchronization issues.
3) Do not need a copy constructor.
4)Allow hashCode to use lazy initialization, and to cache its return value
5)Do not need to be copied defensively when used as a field

 You can make a class immutable by following these guidelines:
1) Ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
2)Make fields private and final

3)Do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state


Intern method in String pool

Intern method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string object will be added in String pool and the reference of this String is returned.

interning is automatic for String literals, the intern() method is to be used on Strings constructed with new String().
String s1 = "Rakesh";
String s2 = new String("Rakesh").intern();


s1==s2 return true in above case now.


Monday, 29 June 2015

Difference between String literal and New String object in Java

String is a special class in Java API and has so many special behaviours which is not obvious

to many programmers. In order to master Java, first step is to master String class, and one 
way to explore is checking what kind of String related questions are asked on Java interviews.
 Apart from usual questions like why String is final, or  equals vs == operator, one of the most
frequently asked question is what is difference between String literal and String object in
 Java.For example, what is the difference between String object created in following two
 expression :
String strObject = new String("Java");
and
String strLiteral = "Java";
Both expression gives you String object, but there is subtle difference between them. When
you create String object using new() operator, it always create a new object in heap
 memory. On theother hand, if you create object using String literal syntax e.g. "Java",
 it may return an existing object from String pool (a cache of String object in Perm gen
 space, which is now moved to heap space in recent Java release), if it's already exists. 
Otherwise it will create a new string object and put in string pool for future re-use. In 
rest of this article, why it is one of the most important thing
 you should remember about String in Java.



What is String literal and String Pool

Since String is one of the most used type in any application, Java designer took a step further
to optimize uses of this class. They know that Strings will not going to be cheap, and that's
 why they come up with an idea to cache all String instances created inside double quotes
 e.g. "Java".These double quoted literal is known as String literal and the cache which 
stored these String instances are known as as String pool. In earlier version of Java, I think 
up-to Java 1.6 String pool is located in permgen area of heap, but in Java 1.7 updates its 
moved to main heap area. Earlier since it was in PermGen space, it was always a risk to 
create too many String object, because its a very limited space, default size 64 MB and used
 to store classmetadata e.g. .class files. Creating too many String literals can cause
 java.lang.OutOfMemory: permgen space. Now because String pool is moved to a much 
larger memory space, it's much more safe. By the way, don't misuse memory
here, always try to minimize temporary String object e.g. "a", "b" and then "ab".
Always use StringBuilder to deal with temporary String object.


Difference between String literal and String objectString literal vs New String in Java

At high level both are String object, but main difference comes from the point that new()
operator always creates a new String object. Also when you create String using literal they 
are interned. This will be much more clear when you compare two String objects created 
using String literal and new operator, as shown in below example :

String a = "Java";
String b = "Java";
System.out.println(a == b);  // True

Here two different objects are created and they have different references:

String c = new String("Java");
String d = new String("Java");
System.out.println(c == d);  // False

Similarly when you compare a String literal with an String object created using new()
 operator using ==operator, it will return false, as shown below :

String e = "JDK";
String f =  new String("JDK");
System.out.println(e == f);  // False

In general you should use the string literal notation when possible. It is easier to read and
it gives  the compiler a chance to optimize your code. By the way any answer to this 
question is incomplete until you explain what is String interning, so let's see that in
 next section.

String interning using inter() method

Java by default doesn't put all String object into String pool, instead they gives you
flexibility to explicitly store any arbitrary object in String pool. You can put any object
to String pool by calling 
intern()method of java.lang.String class. Though,
 when you create using String  literal notation of Java, it automatically call intern()
 method to put that object into String pool, provided it was not present in the pool 
already. This is another difference between string literal and  new string, because in 
case of new, interning doesn't happen automatically, until you call intern() method
 on that object. Also don't forget to use StringBuffer and StringBuilder for
string concatenation, they will reduce number


That's all about this question, what is difference between String literal and String object 
in Java. Always remember that literal Strings are returned from string pool and Java put
them in pool if not stored already. This difference is most obvious, when you compare two 
String objects using equality operator (==). That's why it's suggested as always compare 
two String object using equals() method and never compare them using == operator,
 because you never know which one is coming from pool and which one is created using
 new() operator. If you know the difference between string object and string literal, you
 can also solve questions from Java written test, which also test this concept. It's something, 
every Java programmer should know.  of temporary
String object in heap space.