Thursday, November 14, 2013

String in JAVA

String object is immutable whereas StringBuffer/StringBuilder objects are mutable.

StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized

StringBuilder is faster than StringBuffer as it is not synchronized.

The maximum size for either of these is Integer.MAX_VALUE (231 - 1 = 2,147,483,647)

package com.anshul.projects.iwts.tutor.string;
public class StringDemo {
    public static void main(String args[]){
        String s = "Let’s test";
        s.concat(" if the String object is IMMUTABLE");
        System.out.println(s);
        s = s.concat(" if the String object is IMMUTABLE");
        System.out.println(s);
        StringBuffer s1 = new StringBuffer("Hello");
        s1.append(" Hello");
        System.out.println(s1);
        s1 = s1.append(" Hello ");
        System.out.println(s1);
    }
}


==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location. A very simple example will help clarify this:  

The equals() method actually behaves the same as the “==” operator – meaning it checks to see if both objects reference the same place in memory. But, the equals method is actually meant to compare the contents of 2 objects, and not their location in memory. So, how is that behavior actually accomplished? Simple – the equals class is overridden to get the desired functionality whereby the object contents are compared instead of the object locations.

No comments:

Post a Comment

SpringBoot Application Event Listeners

When a spring boot application starts few events occurs in below order ApplicationStartingEvent ApplicationEnvironmentPreparedEvent Applicat...