What is String?
String Objects are immutable in nature
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 String, that value can never be changed.
String implements Serializable, Comparable and CharSequence interfaces.
We override compareTo(Object object) method in String class and define custom logic.
String overrides equals() and hashCode() methods.
This is another important point related to String, which makes String differ from StringBuffer. In String equals() and hashcode() is overridden and it has been defined custom logic inside equals() and hashcode(). Let’s see code snippet, how equals() and hashcode() is overridden.
String Constants Pool.
String works on String constant pool – String uses special memory location for reusability of String literals that is called String constant pool.
String Interview questions with examples:
- String constant pool in Java
- Why is String immutable in java
- Comparing of two String using == and equals()
- Important methods of String
- How will we define an immutable class in java
- How to create an immutable class with mutable object references in Java
String Constant Pool In Java with Example:
String uses a special memory location to reuse of String objects, is called String Constant Pool. Suppose we create a String object without new keyword i.e String s1 = “onlinetutorials” and again we do String s2 = “onlinetutorials” and String s3 = “onlinetutorials”. Here String will create only one object with value i.e "onlinetutorials". We will have three reference s1, s2, and s3 which are pointing the same object “onlinetutorials”.
How it works:
- 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”.
- 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”.
Creating String object with new operator (How it works):
String str1 = new String(“onlinetutorials”);
Here the first JVM will check, is there any object available with the name “onlinetutorials” 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).
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); } }
Immutable String in Java:
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.
Suppose now we are doing str1 = “onlinetutorials” and if String is not immutable, str2 and str3 will start pointing to “onlinetutorials”. As of now, we have three objects, it might possible we have a hundred or thousands of objects, all will start to point “onlinetutorials”. That’s the very big problem.
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.
Comparing of two String using == and equals():
Before proceeding let’s see differences between == and equals(). == operator checks for references, if two different reference variable is pointing the same object == will return true, while equals() method is overridden in String class and it will check for actual content.
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)); } }
Output:
true
true
Important methods of String:
public boolean equals(Object o)
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 –
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)); } }
public boolean equalsIgnoreCase(String anotherString)
equalsIgnoreCase() will return true if all character in given String objects is the same, even an object contains the capital letters.
public class StringEqualsIgnore { public static void main(String[] args) { String s1 = "onlinetutorials"; String s2 = "ONLIETUTORIALS"; System.out.println(s1.equalsIgnoreCase(s2)); } }
public String[] split(String regex)
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).
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); } } }
How will we define an immutable class in java:
- Define class as final.
- Make fields as private and final.
- Make the constructor private and create an instance within factory methods.
- Initialize the field through the constructor.
- Don’t define the setter method.
- provide getter method for the corresponding fields.
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()); } }
you can also refer How to create an immutable class with mutable object references in Java
Top comments (0)