Friday, December 26, 2014

String pool concept in Java

String pooling (sometimes also called as string canonicalisation) is a process of replacing several String objects with equal value but different identity with a single shared String object. This is the most basic and predominant concept that every Java developer should know. In this article, we understand the concept of pooling with the help of few examples.
You can create objects of the class String by using the new operator, by using the assignment operator ( = ), or by enclosing a value within double quotes ( " ). But you may have noticed a big difference in how these objects are created, stored, and referred by Java.

Let’s create two String objects with the value "JavaLatte" using the operator new :

This image illustrates the previous code.

In the previous code, a comparison of the String reference variables str1 and str2 prints false . The operator == compares the addresses of the objects referred to by the variables str1 and str2 . Even though these String objects store the same sequence of characters, they refer to separate objects that are stored at separate locations.


Let’s create two String objects with the value "Latte" using the assignment operator ( = ). 
The variables str3 and str4 and the objects referred to by these variables
In the previous example, the variables str1 and str2 referred to different String objects, even if they were created using the same sequence of characters. In the case of variables str3 and str4, the objects are created and stored in a pool of String objects. Before creating a new object in the pool, Java first searches for an object with similar contents.

When the following line of code executes, no String object with the value "Latte" is found in the pool of String objects:
String str3 = "Latte";
As a result, Java creates a String object with the value "Latte" in the pool of String objects referred to by variable str3. See the image for understanding this
When the following line of code executes, Java is able to find a String object with the value "Latte" in the pool of String objects:
String str4 = "Latte";



Java doesn’t create a new String object in this case, and the variable str4 refers to the existing String object "Latte".


You can also create a String object by enclosing a value within double quotes ( " ):


These values are reused from the String constant pool if a matching value is found. If a matching value isn’t found, the JVM creates a String object with the specified value and places it in the String constant pool:

Compare the preceding example with the following example, which creates a String object using the operator new and (only) double quotes and then compares their references:

The preceding code shows that object references of String objects that exist in the String constant pool and object references of String objects that don’t exist in the String constant pool don’t refer to the same String object, even if they define the same String value.

Where String pool is stored in memory

  • Java 6
    Permanent Generation part of the heap structure - the fixed size part of heap mainly used for storing loaded classes and string pool. Note that the permanent generation is not part of the heap. It's a separate space for class definitions and related data, as well as where interned strings live

  • Java 7
    The string pool was relocated to the heap. It means that you are no longer limited by a separate fixed size memory area. All strings are now located in the heap, as most of other ordinary objects, which allows you to manage only the heap size while tuning your application
Note strings in the JVM string pool are eligible for garbage collection if there are no references to them from your program roots. It means that if your interned string went out of scope and there are no other references to it – it will be garbage collected from the JVM string pool.

Use of String intern() method
Returns a canonical representation for the string object.

A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned.

String allocation, like any other object creation proves costly in time and memory.The JVM do some trickery while instantiating the string literals to increase performance and decrease memory overhead. To decease the number of creation of String object in JVM, the String class keeps a pool of Strings. Each time you create a string literal, the JVM checks the string literal pool first. If a string is found in the pool, a reference to the pooled string is return.if the String is not exist in the pool, a new string object is instantiates, then placed in the pool.


If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Monday, December 22, 2014

ClassCastException in Java

ClassCastException exception is thrown when an attempt is made to cast between incompatible types (such as String to Integer type or vice versa).  In this article, we understand this exception in more detail and find out the way to avoid this exception with examples.


ClassCastException 
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:
Object x = new Integer(0);
System.out.println((String)x);

Take a look at the above figure to review the class hierarchy of this exception. Examine the code where the line of code that throws the ClassCastException is shown in bold.

ClassCastException is thrown when an object fails an IS-A test with the class type to which it’s being cast. In the preceding example, class Ink is the base class for classes ColorInk and BlackInk. The JVM throws a ClassCastException in the previous case because the line of code in bold tries to explicitly cast an object of ColorInk to BlackInk.


Why above code avoided the compilation error
Note that above line of code avoided the compilation error because the variable inks defines an ArrayList of type Ink , which is capable of storing objects of type Ink and all its subclasses. The code then correctly adds the allowed objects: one each of BlackInk and ColorInk.

If the code had defined an ArrayList of type BlackInk or ColorInk , the code would have failed the compilation, as follows:
Here’s the compilation error thrown by the previously modified piece of code:

How to avoid ClassCastException
If a ClassCastException is thrown while executing a program, and if there are no exception handlers for that, the program will terminate. So, how about providing an exception handler like this?
Yes, this will work and the program will not crash. But this is a really bad idea! There are two main problems in this code.

  • Providing exception handlers for RuntimeExceptions like this create an illusion that the program is working perfectly fine, when it is not!
  • Runtime exceptions like ClassCastException indicate programming errors and should not be caught using exception handlers.
Okay, so what do you do now? Before downcasting, check for the dynamic type of the object and then downcast. You can use the instanceof operator to verify whether an object can be cast to another class before casting it.

This is an effective and proper way to achieve downcasting. Using the instanceof operator checks the dynamic type of obj, which helps you to decide whether to downcast it to a String object.

Continue with our main example. Assuming that the definition of classes Ink , ColorInk, and BlackInk are the same as defined in the previous example, the following lines of code will avoid the ClassCastException

In the previous example, the condition ( inks.get(0)instanceofBlackInk ) evaluates to false , so the then part of the if statement doesn’t execute.


Question
Try to examine and share the output of the following program in comment section




If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...