Java Strings Interview Questions

Java String Interview Questions

Java is one of the most widely used programming languages in the world, and its built-in String class is one of the most important classes in Java. In this article, we’ve curated a list of interview questions and answers focused specifically on Java String handling. 

It is always preferable to start preparation topics-wise and move ahead with a different set of questions. The article has got you the basics of advanced Java string interview questions. You can expect most of these questions here in an interview.

So, let’s begin with Java String interview questions for both freshers and experienced.

Ques.1. What is String in Java?

Java String can be defined as a container used to store a sequence of characters of any datatype. String is a class in Java and is declared in the “java.lang” package. 

E.g; String S=”Hello”;

Here ‘S’ is the string variable name that stores a sequence of characters ‘H’,’e’,’l’,’l’,’o’.

Ques.2. How to create a string in Java?

String in Java can be declared in two ways:

  1. Using String Literal: When we declare a string using literal or double quotes, the JVM searches the String pool for any other string with the same value. If the same value is identified, it returns a reference to that string; otherwise, a new object is created with the given new value. 
    E.g. – String s=”apple”
  1. Using ‘new’ operator: When we declare a  string using ‘new’ operator it is not stored in the string pool, instead it is created in Java Heap memory.
    E.g. – String s = new String(“apple”);

Ques.3. Is string a primitive data type or object in Java?

Strings in Java are objects, not primitive data types. Primitive data types have specific sizes, one variable data type, and no other methods.

Ques.4. What is the main purpose of strings in Java?

Strings are widely used in Java for text processing and data manipulation. They prove effective to Java developers as they are immutable and provide several methods to work with.

Ques.5. Why is string immutable in Java?

  • Since the string is immutable, sensitive data like username, and password cannot be changed once created. Thus, it reduces the chance of threats.
  • Immutable strings are thread-safe to use in multithreading without synchronization.
  • Java class loaders use Strings and immutability ensures that the correct class is getting loaded by the ClassLoader class.

Ques.6. Differentiate between String, StringBuffer, and StringBuilder in Java?

StringStringBufferStringBuilder
Strings are immutable.They are mutable.They are mutable.
Strings are not used in the threaded environment.StringBuffer is suitable for multiple threads.It is suitable for a single threaded environment.
The performance of String is quite slow.Speed is more than String but less than StringBuilder.Fastest in performing operations.

Ques.7. What is the difference between String ‘==’ and equals()?

This is one of the most frequently asked Java String interview questions.

String “==” operators compare references of two objects. If both the objects refer to the same object, it returns true, else false.

String s1=”apple”;
String s2=”apple”;

Both the strings are created in the string pool and refer to the same object, so it returns true.

equals() methods compare two strings considering the content of two strings and their case. If it matches, it returns true otherwise false.

String s1=”apple”;
String s2=”apple”;

It returns true, as both the strings have the same content.

Ques.8. What is the difference between compareTo() and equals() methods in Java?

compareTo() method compares two strings lexicographically i.e. compares the corresponding character position for both strings. If all characters are the same(including case) are the same then it returns 0(i.e. strings are equal) otherwise it returns the difference of the unmatched Unicode character. 

String s = “APPLE”;
String s1 = “BEET”;

System.out.println(s.compareTo(s1));

It returns -1, since ASCII code of A=65 and B=66 and their lexicographic difference is 65-66=-1;

equals() methods compare two strings considering the content of two strings and their case. If it matches, it returns true otherwise false.

String s1 = “apple”;
String s2 = “apple”;

It returns true, as both the strings have the same content.

Ques.9. How to convert a string array to a char array in Java?

String object is basically a sequence of characters. We can use the tocharArray() method to convert a given string to a character array. The function charAt(index) is also used to find a character from the string for a given index.

Example-

String str = "apple"; 
char[] c = str.toCharArray(); 
System.out.println(c.length); 
for (int i = 0; i < c.length; i++) { 
      System.out.print(c[i] + ""); 
}

Output: a p p l e

Ques.10. Write a Java method to check if the input string is palindrome.

private static boolean isPalindrome(String s) {
    if (s == null)
        return false;
    StringBuilder sBuilder = new StringBuilder(s);
    sBuilder.reverse();
    return sBuilder.toString().equals(s);
}

A string is a palindrome if it remains the same after reversing. We use the reverse() method of the StringBuilder class to reverse the string and then use equals() method to check with the given string.

Ques.11. How to split a string in Java?

We can use split() function to split a string  based on the matches of the regular expression. It returns an array of string[] with the splitted string values. 

E.g.-

String str = "java string manipulation interview questions "; 
        String[] strings = str.split(" "); 
        for (int i = 0; i < strings.length; i++) { 
            System.out.println(strings[i]+" ");
}


Ques.12. What is the use of the substring() method?

The substring() method is used to extract a portion of a given string. 

E.g; String s=”Apple”;

System.out.println(s.substring(1,3));

Output: ppl

‘1’ is the beginning index and ‘3’ is the end index. The index starts from 0.

Ques.13. Can we use String in the switch case in Java?

Previously, it was not allowed to use String in switch cases in Java. But Java 7 and the higher versions use Strings in switch statements. The introduction of switch cases has made code more readable without the use of multiple if-else conditions.

Ques.14. What is the difference between equals() and equalsIgnoreCase() methods?

The equals() method compares two strings based on the equality of two strings considering their case. E.g;

String s1 = “apple”;
String s2= “APPLE”;

It returns false since two strings are checked considering their cases.

equalsIgnoreCase() method compares two strings without considering the case of characters i.e, it will only compare their spelling. E.g;

String s1 = “apple”;
String s2 = “Apple”;

It returns true.

Ques.15. How to check if a given string is Empty or not?

To check for a given string is Empty or not in Java, we use the isEmpty() method. The method returns a boolean value. E.g;

String s = "";
if(s.isEmpty())
System.out.println("String is Empty");
else
System.out.println("String is not empty");

Ques.16. Write a program to swap two strings without a third string.

String a = "Apple";  
String b = "Guava";  
System.out.println("Before swap: " + a + b);  
a = a + b;  
b = a.substring(0, a.length() - b.length());  
a = a.substring(b.length());  
System.out.println("After swap : " + a + b);  

We add the strings a and b and store them in a. Now we will store the substring with start index 0 to length and subtract from the length of b and store in string b. Now we store the substring from index = b.length() till the end of the String ‘a’ in String ‘a’.

 

Ques.17. What is a string constant pool?

String constant pool refers to the space allocated in the heap memory to store the objects created using string literals. String constant pool is unique, no two Strings of objects have the same value.

Ques.18. Why is Java provided with a String constant pool?

String constant pools make the existing string objects more reusable. It decreases the number of string objects created in the memory, thus saving it as no two objects have the same content.

Ques.19. How to convert string to StringBuilder?

We use the constructor parameter of StringBuilder, to convert string to StringBuilder. The string value is passed to the constructor of the StringBuilder class to convert the StringBuilder object.

Ques.20. How to remove a specific character from the string?

private static String removeChar(String s, char ch)

{
    if (s == null){
        return null;
    }
    return s.replaceAll(Character.toString(ch), "");
}

The replaceAll() method replaces all the characters in the given string. The specific character is converted into a string and then, by using the replaceAll() method, we can remove all the occurrences of the given character in the string.

Ques.21. What is the difference between indexOf and lastIndexOf methods in Java?

indexOf() checks the occurrence of a given character within the specified position of the string and returns the index position of that character. E.g; 

String s = "apple";
System.out.println(s.indexOf('l'));
Output: 3
lastIndexOf() checks the last occurrence of a given character and returns the index position of that character. Example-
String s = "java";
System.out.println(s.lastIndexOf('a'));
Output: 3

Ques.22. Why string is not used for storing the passwords rather a char array is preferred for the same?

A String is immutable in Java and once created it stays in the string pool and is available in memory for a longer duration. Thus, anyone having access to a memory dump can extract the password in clear text format. This creates a security threat. But if a char array stores a password, you can set it to blank after use to avoid any security threat.

Ques.23. Why is String mostly used as a key in HashMap class?

String is immutable and the hashcode of the String is cached every time it is created. So it need not be calculated repeatedly. Because of its faster processing than other HashMap keys, String is a great choice for the key in Map.

Ques.24. Write a program to count the occurrence of a given character in a string.

String str = "java";
int Count=0;
for(int i=0;i<str.length();i++)
    if(ch==’a’)
      Count++;
System.out.println(Count);

We take a count variable and initialize to 0. We run a loop till the total length of the string. Each time the given character is found, the count variable is incremented by 1.

Ques.25. How to make a string upper or lowercase in Java?

We can use the toUpperCase() and toLowerCase() method to convert all characters of a string in uppercase format and lowercase format in Java.

Ques.26. Find the length of the String without using the length() method? 

static int length(String s) { 
s = "apple";
int i=0, count=0; 
        try { 
            for(i=0,count=0;0<=i;i++,count++) 
                s.charAt(i); 
        } catch(StringIndexOutOfBoundsException e) { 
         e.printStackTrace(); 
        } 
        return count; 
} 

       

Iterate the string in a loop and when the loop reaches the end of the string it throws an exception.

Ques.27. Explain the difference between str1.equals(“abc”) and “abc”.equals(str1), where str1 is any String object?

If we pass str1 value as NULL, then the first statement will throw a null pointer exception while the second statement will return false.

Ques.28. How do you check if a string is numeric in Java?

String str = "9999.99"; 
boolean isNumeric = true; 
        try { 
            Double num = Double.parseDouble(str); 
        } catch (NumberFormatException e) { 
            isNumeric = false; 
        } 
        if (isNumeric) 
            System.out.println(str + " is a number"); 
        else 
            System.out.println(str + " is not a number"); 

We can use the parseDouble() method of Double class to convert String to Double number and check if string is numeric. If it doesn’t throw a NumberFormatException, it means the given string is numeric.

Ques.29. Write a program to remove space from a given string.

We can use the replaceAll() method of the string class and the regex function to replace spaces in a string. 

public static String removeSpace(String str) { 
       str = "I   love      India";
       str = str.replaceAll("\\s",""); 
       return str; 
}

Ques.30. Explain the difference between UTF-8 and UTF-16.

UTF-8 and UTF-16 are examples of character encoding. It describes how characters are represented in bytes. UTF stands for Unicode Transformation Format. UTF-8 uses a minimum of 1 byte or 8 bits to represent a character while UTF-16 uses a minimum of 2 bytes or 16 bits memory to represent a character.

Java string is a topic that should not be missed while preparing for an interview. Whether you are an experienced developer preparing for your upcoming interview or just looking to increase your knowledge of Java strings, these Java String interview questions will help you prepare well. 

Advertisement

Leave a Comment