exampracticeonline.com
String Interview

Why String is immutable or final in Java?

  • String Pool is possible because String is immutable in java.
  • It increases security because any hacker can’t change its value and it’s used for storing sensitive information such as database username, password etc.
  • Since String is immutable, it’s safe to use in multi-threading and we don’t need any synchronization.
  • Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader.

What does the intern() method of String class do?

The intern() method of String class put the String into String pool e.g. str.intern() will put the String str into the pool. Once the String is the pool it can be reused and improve performance.

Is String thread-safe in Java?

Yes, String is thread-safe in java.

Why String is thread-safe in Java?

String is thread-safe because it's Immutable. All Immutable objects are thread-safe because once they are created, they can't be modified, hence no issue with respect to multiple threads accessing them.

How to check if a String is empty in Java?

  1. By use of isEmpty() method which returns true if String is empty.
  2. By use of length() method which returns 0 length if String is empty.

How to remove white space from String in Java?

By use of trim() method we can remove begning and ending white space from String in Java.

Example:

package com.example;

public class StringTrim {

    public static void main(String[] args) {
        String name=" Java World ";
        System.out.println("Before trim method name="+name);
        System.out.println("Before trim method name length="+name.length());
        
        name=name.trim();
        System.out.println("After trim method name"+name);
        System.out.println("After trim method name length="+name.length());
        
    }

}


Output:

Before trim method name= Java World
Before trim method name length=12


After trim method nameJava World
After trim method name length=10

Can we use String in switch case?

This is a tricky question used to check your knowledge of Java versions. Java 7 extended the capability of switch case to use Strings also, earlier java versions doesn’t support this.


Example:

package com.db;

public class StringInSwitch {

    public static void main(String[] args) {
        showLanguage("java");

        showLanguage("asp");
    }
    
    private static void showLanguage(String name) {
        switch(name) {
            case "java":
                System.out.println("Language : "+name);
                break;
            case "asp":
                System.out.println("Language : "+name);
                break;
            default:
                System.out.println("Invalid language");
        }
    }

}


Output:

Language : java
Language : asp

How can we make String upper case or lower case?

We can use String class toUpperCase() and toLowerCase() methods to get the String in all upper case or lower case.


Example:

       String name1="Java World";
        name1=name1.toUpperCase();
        System.out.println("Upper case name1 : "+name1);
        
        String name2="Java World";
        name2=name2.toLowerCase();
        System.out.println("Lower case name2 : "+name2);


Output:

Upper case name1 : JAVA WORLD
Lower case name2 : java world

What is String in Java?

String is a Class in java and defined in java.lang package. It’s not a primitive data type like int and long. String class represents character Strings.

Is String a primitive type or derived type?

String is a derived type.

What is the difference between creating String as new() and literal?

We can create String object in java by using new() and literal.

By using literal: When you declare String using literal ( assignment operator), you are actually calling intern() method on String to create String object in String constant pool. If same String is already exists in String constant pool, then String will reference of that string and no new String object will be created otherwise it will create new String in String constanct pool.

If you create another String with same content, both will reference to same object in String constant pool.

Example: String str = "hello java"; 

By using new() : If you create a String by using new operator, it is not interned. It will always create new object in heap memory even if String object already exists with same content and one object in String constant pool also if same String is not present.

Example: String str = new String("hello java"); 

Compare : 

  1. new() will create two object and literal will create one object.
  2. if we compare performance of string literal and new() , string new() will always take more time to execute than string literal because it will construct a new string every time it is executed.

How many objects will be created in below code?

String str1 = "Hello java";

String str2 = "Hello java";

Answer: Only one object will create.

Explanation: String str1 creates 1 object and str2 references with same String in constant pool.


String str1 = "Hello java";

String str2 = new String("Hello java");

Answer: Two objects will create.

Explanation: String str1 creates 1 object in constant pool and str2 creates one object in heap memory and references with same String in constant pool.


String str1 = new String("Hello java");

String str2 = new String("Hello java");

Answer: Three objects will create.(two objects in heap memory and one object in constant pool)

Explanation: String str1 creates 1 object in constant pool and 1 in heap memory and str2 creates one object in heap memory and references with same String in constant pool.

What is the difference between "==" and equals() in String comparison?

1. "==" : It compares refrences of String in java. If both String refrenced to same String in constant pool then it will return true otherwise it returns false.

Example 1 : 

String str1="hello java";

String str2="hello java";

str1 == str2 => It's true because both String refrence to same String in constant pool.


Example 2 : 

String str1="hello java";

String str2= new String("hello java");

str1 == str2 => It's false because both String refrence to different String.


Example 3 : 

String str1=new String("hello java");

String str2= new String("hello java");

str1 == str2 => It's false because both String refrence to different String.



2. equals(): It compares content of String in java. If both String refrenced to same or differenet String and same contant then it will return true otherwise it returns false.

Example 1 : 

String str1="hello java";

String str2="hello java";

str1.equals(str2) => It's true because both String have same contants.


Example 2 : 

String str1="hello java";

String str2= new String("hello java");

str1.equals(str2) => It's true because both String have same contants.


Example 3 : 

String str1=new String("hello java");

String str2= new String("hello java");

str1.equals(str2) => It's true because both String have same contants.

What is String pool in Java?

String pool is a special storage area in Java heap, mostly located on PerGen space, to store String literals like "ABC". When Java program creates a new String using String literal, JVM checks for that String in the pool and if String literal is already present in the pool than the same object is returned instead of creating a whole new object. String pool check is only performed when you create String as literal, if you create String using new() operator, a new String object will be created even if String with the same content is available in the pool.


4

What does intern() method do in Java?

String object created by new() operator is by default not added in String pool as opposed to String literal. The intern method allows putting a String object into a pool.

How do you compare two String in Java?

There are multiple ways to compare two String like equals() method, equalsIgnoreCase() etc.

What is StringBuffer?

As we know that String objects are immutable or unchangable in java.

StringBuffer class is used to create a mutable or changable String object i.e its state can be changed after it is created. It represents growable and writable character sequence. 

Example: 

 StringBuilder sb = StringBuilder(); // with blank value

sb.appand("hello java");

NOTE: So if we do a lot of modifications with String objects then we use StringBuffer instead of String object. StringBuffer is Synchronized so, it can be use in multi-threaded application.

What is StringBuilder?

As we know that String objects are immutable or unchangable in java.

StringBuilder class is used to create a mutable or changable String object i.e its state can be changed after it is created. It represents growable and writable character sequence. 

Example: 

 StringBuilder sb = StringBuilder(); // with blank value

sb.appand("hello java");

NOTE: So if we do a lot of modifications with String objects then we use StringBuffer instead of String object. StringBuilder is not Synchronized so, it can not be use in multi-threaded application.

What is the difference between String, StringBuffer and StringBuilder in Java?

String StringBuffer StringBuilder

 It's immutable.So, it can't be modify if we try to modify it will   create new object.

 It's muttable.So, it can be easly modify if we try to modify it will not create and   append in same object.v  It's muttable.So, it can be easly modify if we try to modify it will not create   and  append in same object.

 It's threadsafe or Synchronized.

 It's threadsafe or Synchronized.  It's not threadsafe or Synchronized.

 It can be use in multi-threaded application.

 It can be use in multi-threaded application.  It can't be use in multi-threaded application.

 String object can be create by using String literal or using   new() operator.

 StringBuffer object only can create by using using new() operator.  StringBuilder object only can create by using using new() operator.

Why is String final in Java?

Why is String final in Java?