Java String Interview Questions - Part 1

 Java String Interview Questions


1. is String a primitive data type?

    It’s not a primitive data type. String class represents the character of Strings
    The string is immutable and final in Java and JVM uses String Pool to store all the String objects

2. What is the difference between equals() method and == operator?

The equals() method matches the content of the strings whereas the == operator matches the object or reference of the strings.


3.How will you create a String object in java?

    We can create a String object using a "new" operator or we can use double quotes to create a String object

    String str = new String("Hello");

    String str1 = "Hello";

  

    while creating a String using double quotes, JVM looks in the String pool to find if any other String is stored with the same value. If it is found, it just returns the reference to that String object otherwise it creates a new String object with a given value and stores it in the String pool

When we use the new operator, JVM creates the String object but it will not store it in the String Pool. if We need we can use intern() method to store the String object into the String pool or return the reference if there is already a String with equal value present in the pool.

4.How to check the String is a palindrome?

  

  What is a palindrome - A string is said to be Palindrome if its value is the same when reversed. For example “madam” is a Palindrome String

  

  private static boolean isPalindromeString(String str) {

        if (str == null)

            return false;

        int length = str.length();

        System.out.println(length / 2);

        for (int i = 0; i < length / 2; i++) {


            if (str.charAt(i) != str.charAt(length - i - 1))

                return false;

        }

        return true;

    }


5.What is StringBuffer? 

  •  StringBuffer class is mutable.
  •  StringBuffer is fast and consumes less memory when you concat strings.
  •  StringBuffer class doesn't override the equals() method of Object class.
  •  StringBuffer is synchronized i.e. thread-safe. It means two threads can't call the methods of StringBuffer simultaneously.

6.What is StringBuilder

  • StringBuilder is non-synchronized i.e. not thread-safe. It means two threads can call the methods of StringBuilder simultaneously.
  • StringBuilder is more efficient than StringBuffer.




Comments