String in java
Tags: stringinjava, immutable, contantspool
Published: 2021-01-20 09:48:47

<hr />

<h1>What is String?</h1>
<h3>String Objects are immutable in nature</h3>
This one is a very important point for interview perspective. What does it mean when we say String is immutable. Immutability is – Once we assign some value to <strong>String</strong>, that value can never be changed.
<h3>String implements Serializable, Comparable and CharSequence interfaces.</h3>
We override <strong>compareTo</strong>(Object object) method in String class and define custom logic.
<h3>String overrides equals() and hashCode() methods.</h3>
This is another important point related to String, which makes String differ from <strong>StringBuffer</strong>. In String equals() and <strong>hashcode</strong>() is overridden and it has been defined custom logic inside <strong>equals</strong>() and <strong>hashcode</strong>(). Let’s see code snippet, how equals() and <strong>hashcode</strong>() is overridden.
<h3>String Constants Pool.</h3>
String works on String constant pool – String uses special memory location for reusability of String literals that is called String constant pool.
<h4>String Interview questions with examples:</h4>
<ul>
 	<li><a href="#string_constant_pool_in_java">String constant pool in Java</a></li>
 	<li><a href="http://immutable_string_in_java">Why is String immutable in java</a></li>
 	<li><a href="#comapring_of_two_string_using_operators_and_equals_method">Comparing of two String using == and equals()</a></li>
 	<li><a href="#important_methods_of_string">Important methods of String</a></li>
 	<li><a href="#how_define_immutable_class_in_java">How will we define an immutable class in java</a></li>
 	<li><a href="https://onlinetutorials.tech/how-to-create-an-immutable-class-with-mutable-object-references-in-java/">How to create an immutable class with mutable object references in Java</a></li>
</ul>
<h2 id="string_constant_pool_in_java">String Constant Pool In Java with Example:</h2>
String uses a special memory location to reuse of String objects, is called String Constant Pool. Suppose we create a <em><strong>String object without new keyword</strong></em> i.e <em>String s1 = “onlinetutorials”</em> and again we do <em>String s2 = “onlinetutorials”</em> and <em>String s3 = “onlinetutorials”</em>. Here String will create only one object with value i.e "<em>onlinetutorials</em>". We will have three reference <em>s1, s2, and s3</em> which are pointing the same object “onlinetutorials”.
<h3>How it works:</h3>
<ul>
 	<li>When first time we do String s1 = “onlinetutorials”, JVM will create a new object in String Constant Pool and s1 will refer to that object i.e “onlinetutorials”.</li>
 	<li>When we do the second time String s2 = “onlinetutorials”, JVM will check is there any object with value “onlinetutorials” already there in String Constant pool. As of now yes we have already “onlinetutorials” is there in String Constant pool, so it will not create a new object, just s2 reference variable will point to that existing “onlinetutorials” object. The same process will happen for String s3 = “onlinetutorials”.</li>
</ul>
<h3>Creating String object with new operator (How it works):</h3>
String str1 = new String(“onlinetutorials”);

Here the first JVM will check, is there any object available with the name “<strong>onlinetutorials</strong>” in String Constant Pool or not, if not it will create one object inside String Constant Pool and it will also create another object outside of String Constant Pool and str1 will point this object (the object which has been created outside of String Constant Pool).
<pre class="EnlighterJSRAW" data-enlighter-language="generic">public class StringExample {
    public static void main(String[] args) {

        String s1 = "OnlineTutorials";
        String s2 = s1 + "tech";
        s1.concat("technology");
        s2.concat(s1);
        s1 += "Java";
        System.out.println(s1 + "   " + s2);

    }
}</pre>
<h3 id="immutable_string_in_java">Immutable String in Java:</h3>
As we know String uses the string constant pool for the memory location. Suppose we have multiple reference variables, all are pointing to the same object, if String is not immutable and we change the value of any reference then all others reference will get affected.
<blockquote><em>Suppose now we are doing <strong>str1</strong> = “<strong>onlinetutorials</strong>” and if String is not immutable, <strong>str2</strong> and <strong>str3</strong> will start pointing to “<strong>onlinetutorials</strong>”. As of now, we have three objects, it might possible we have a hundred or thousands of objects, all will start to point “<strong>onlinetutorials</strong>”. That’s the very big problem.</em></blockquote>
Since String is immutable, it is safe to use in multithreading. This avoids the use of synchronization for thread safety, String is implicitly thread safe in nature.
<h3 id="comapring_of_two_string_using_operators_and_equals_method">Comparing of two String using == and equals():</h3>
Before proceeding let’s see differences between <strong>== and equals()</strong>. <strong>== operator</strong> <em><strong>checks for references</strong></em>, if two different reference variable is pointing the same object == will return true, while equals() method is overridden in String class and it will <em><strong>check for actual content</strong></em>.
<pre class="EnlighterJSRAW" data-enlighter-language="java">public class StringExample {
    public static void main(String[] args) {

        String s1 = "onlinetutorials";
        String s2 = "onlinetutorials";

        System.out.println(s1 == s2);
        System.out.println(s1.equals(s2));

    }
}</pre>
Output:

<em><strong>true</strong></em>

<em><strong>true</strong></em>
<h3 id="important_methods_of_string">Important methods of String:</h3>
<h4>public boolean equals(Object o)</h4>
This is a very frequently used method, which is overridden in String class. It checks for content, if the content is equal it returns true else it returns false. Let’s see a simple example –
<pre class="EnlighterJSRAW" data-enlighter-language="java">public class StringEquals {
public static void main(String[] args) {

String s1 = new String("onlinetutorials");
String s2 = new String("onlinetutorials");

System.out.println(s1.equals(s2));

}
}</pre>
<h4>public boolean equalsIgnoreCase(String anotherString)</h4>
equalsIgnoreCase() will return true if all character in given String objects is the same, even an object contains the capital letters.
<pre class="EnlighterJSRAW" data-enlighter-language="java">public class StringEqualsIgnore {
public static void main(String[] args) {

String s1 = "onlinetutorials";
String s2 = "ONLIETUTORIALS";

System.out.println(s1.equalsIgnoreCase(s2));

}
}</pre>
<h4>public String[] split(String regex)</h4>
split() method returns String array. We can split any string on the basis of some regex value like space, comma or hyphen(or other regex value).
<pre class="EnlighterJSRAW" data-enlighter-language="java">public class StringSplit {
public static void main(String[] args) {

String str= "online tutorials tech";

String[] splitArray = str.split(" ");
for(String s: splitArray){
System.out.println(s);
}

}
}</pre>
<h4 id="how_define_immutable_class_in_java">How will we define an immutable class in java:</h4>
<ol>
 	<li>Define class as final.</li>
 	<li>Make fields as private and final.</li>
 	<li>Make the constructor private and create an instance within factory methods.</li>
 	<li>Initialize the field through the constructor.</li>
 	<li>Don’t define the setter method.</li>
 	<li>provide getter method for the corresponding fields.</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">final class ImmutableExample {
    private final String name;

    private ImmutableExample(String name) {
        this.name = name;
    }

    public static ImmutableExample getInstance() {
        return new ImmutableExample("ram");
    }

    public String getName() {
        return name;
    }

}

public class Test {
    public static void main(String[] args) {
        ImmutableExample m = ImmutableExample.getInstance();
        System.out.println("name  :-" + m.getName());

    }
}</pre>
you can also refer <a href="https://onlinetutorials.tech/how-to-create-an-immutable-class-with-mutable-object-references-in-java/">How to create an immutable class with mutable object references in Java</a>

<hr />