Wednesday, July 6, 2022

Top 15 Java String interview Question Answers for 3 to 5 Years Experienced

10 Java String interviews Question answers
String interview questions in Java is one of Integral part of any Core Java or J2EE interviews. No one can deny the importance of String and how much it is used in any Java application irrespective of whether it's core Java desktop application, web application, Enterprise application or Mobile application. The string is one of the fundamentals of Java programming language and correct understanding of String class is a must for every Java programmer. What makes String interview questions in Java even more interesting is the special status of String in terms of features and privileges it has like the + operator is kind of overloaded to perform String concatenation despite the fact that Java does not support operator overloading. There is a separate String pool to store String literal etc.

In this article we will some frequently asked questions on String in a Java interview which focuses on a range of features like immutability, thread-safety, security, performance, memory consumption, mutable counterparts of String like StringBuilder and StringBuffer, comparing String instances in Java, equals() vs == check for String, using String as key in HashMap, storing String on the array and List, etc.




11 Java String Interview Questions and Answers

Here is my list of frequently asked question on String, feel free to add any other interesting question which you faced on String during any Core Java interview :


1. What is String in Java? Is String is data type?
String in Java is not a primitive data type like int, long or double. The string is a class or in more simple terms a user-defined type. This is confusing for someone who comes from C background. String is defined in java.lang package and wrappers its content in a character array.

String provides equals() method to compare two String and provides various other methods to operate on String like toUpperCase() to convert String into upper case, replace() to replace String contents, substring() to get substring, split() to split long String into multiple String.



2. Why is String final in Java? 
The string is final by design in Java, some of the points which make sense why String is final are Security, optimization, and maintaining a pool of String in Java. for details on each of these points see why String is final in Java.




3. What is the difference between String and StringBuffer in Java? 
This is probably the most common question on String I have seen in Java interviews. Though String and StringBuffer are two different classes they are used in the context of concatenating two Strings, Since String is immutable in Java every operation which changes String produces a new String, which can be avoided by using StringBuffer. See String vs StringBuffer for more details.


4. What is the difference between String on C and Java?
If you have mentioned C in your resume, then you are likely to face this String interview question. Well, C String and Java String are completely different from each other, C String is a null-terminated character array while String in Java is an Object. Also, String is more feature-rich in Java than C.



5. Why char array is better than a String for storing passwords? 
This String interview question is debatable and you might not agree with interviewer but this is also a chance to show that how deep and different, you can think of. One of the reasons which people give Why you should store a password in char array over String is related to immutability since it's not possible to erase the contents of String but you can erase contents of a char array. See Why char array preferred over String for a password for a complete discussion.



6. How do you compare two String in Java? 
This is another common String interview question that appears on fresher level interviews. There are multiple ways to compare two String like equals() method, equalsIgnoreCase() etc, You can also see 4 ways to compare String in Java for more examples. 

The main thing which interviewer checks is that whether candidate mentioned equality operator or not "==", comparing String with equality operator is a common mistake which works in some case and doesn't work in other. next String interview question is follow-up up of this.

Top 10 Java String interview Question answers - Advanced




7. Can we compare String using == operator? What is the risk? 
As discussed in previous String question, You can compare String using equality operator but that is not suggested or advised because equality operator is used to compare primitives and equals() method should be used to compare objects. 

As we have seen in the pitfall of autoboxing in Java that how equality operator can cause a subtle issue while comparing primitive to Object, anyway String is free from that issue because it doesn't have a corresponding primitive type and not participate in autoboxing.

Almost all the time comparing String means comparing contents of String i.e. characters and equals() method is used to perform the character-based comparison. equals() return true if two String points to the same object or two String has same contents while == operator returns true if two String object points to the same object but return false if two different String object contains same contents. That explains why sometimes it works and sometimes it doesn't.

In short always use equals method in Java to check equality of two String object.



8. How does the substring method work in Java? 
This is one of the tricky Java questions relate to String and until you are familiar with the internals of the String class, it's difficult to answer. Substring shares same character array as original String which can create a memory leak if original String is quite big and not required to retain in memory but unintentionally retained by substring which is very small in size and prevents large array from begin claimed during Garbage collection in Java.

substring in Java




9. What is the String pool in Java?
This is another tough Java question was asked in the String interview. String pool is a special storage area in Java heap, mostly located on PerGen space, to store String literals like "ABC"

When the 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 then 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 the new() operator, a new String object will be created even if String with the same content is available in the pool.

Java String Interview Questions with answers



10. What does the intern() method do in Java?
As discussed in a previous String interview question, the String object created by the new() operator is by default not added in the String pool as opposed to String literal. The intern method allows putting a String object into a pool.


11. Is string thread-safe in Java? 
If you are familiar with the concept of immutability and thread-safety you can easily answer this String interview question in Java. Since String is immutable, it is thread-safe and it can be shared between multiple threads without external synchronization.

If you are seriously preparing for Java interviews and do not want to leave any stone unturned, I strongly suggest you go through questions given in Java Programming Interview Exposed, one of the rare books which cover all important topics for Java interviews.




6 String-based Coding Questions for Java Programmers

These questions are mostly based upon Java's implementation of String and  you can only answer them well if you have good knowledge of java.lang.String class. But, String is very general data structure and you will find it in almost all programming and script language like C, C++, C#, Python, Perl or Ruby. 

That's why I am going to share some more String based coding question, which is not Java-specific. You can solve these question in any programming language as they are mostly logic-based programming questions.


1. Write a Java program to reverse String in Java without using any API? (solution)
This means you can not use StringBuffer's reverse() method or any of String utility method, all you can have is a character array for reversing contents.


2. Write a Program to check if a String is a palindrome or not? (solution)
For example, a String e.g. "madam" is a palindrome but "book" is not a palindrome. You also need to solve this question without taking any help from Java String API.


3. Write a Java program to check if two String are Anagram or not? (solution)
You need to write method e.g. isAnagram(String first, String second) which will return true if second String is an anagram of the first string. An anagram must contain the same number of characters and exactly same characters but in different order e.g. top and pot, or army and mary.


4. Write a method in Java to remove any character from String? (solution)
For example, you need to write method remove(String word, char removeThis), this method should return a String without character, which is asked to remove. you can use indexOf(), substring(), and similar methods from the String class, but your method must handle corner cases like passing null or empty String, String containing just one character etc.


5. Write a method to split a comma-separated String in Java? (solution)


6. Write Java program to print all permutations of a String  like passing "ABC" will print all permutations like "BCA", "CBA" etc (solution)

If you are hungry for more String-based coding questions, you can also check the Cracking the Coding Interview book, a collection of 189 programming questions and solutions from various programming job interviews of reputed tech companies like Amazon, Google, Facebook, and Microsoft.


That's all about Java String interview questions and answers. In Summary, there are a lot of specifics about String which needs to be known for anyone who has started Java programming and these String question will not just help to perform better on Java Interviews but also opens the new door of learning about String. I didn't know much String related concepts until I come across these question which motivated to research and learns more about String in Java.


Other Java String tutorials and questions from Javarevisited Blog
  1. How to convert Date to String in Java
  2. How to convert Enum to String in Java
  3. How to create comma separated String from Collection in Java
  4. How to convert String to Double in Java
  5. How to reverse String in Java with recursion
  6. How to format String in Java
  7. 130+ Core Java Interview questions with Answers

27 comments:

  1. Please, please don't mention StringBuffer. You should use StringBuilder 99.999% of the time.

    ReplyDelete
  2. Hi, Please confirm.. I face this question a lot in my interviews.
    String aa = new String("abc");
    String bb = "abc";

    How many object of string class are created.

    ReplyDelete
  3. @Shariq Bharat, Two object, one in each line. Second one will be added into String pool.

    ReplyDelete
  4. @Attila-Mihaly Balazs , 99.99% agree with you, and one should be using StringBuilder by default.

    ReplyDelete
  5. question pls
    input:"my name is jack"
    output:"ym eman si kcaj"

    ReplyDelete
  6. To answer Shariq Bharat questions in more detail, Yes, there are two objects are created, but both are created in first line itself. Before creating object using new String(), JVM creates an string literal "abc", that is your first object, now by using content of this object, second object is created by calling constructor of String, this object also has value "abc" but created in heap, rather than in permgen area, where first object was created. In second line no new object is created as bb will get reference of "abc" from String pool from permgen space.

    Now, from Java 7 onwards String pool is no longer located in permgen space, they are now part of Java heap space. Which means you can use String literals and intern() method more freely without worrying about OutOfMemoryError in permgen space. If you are still using Java 1.6, then remember that permgen area has less space than heap memory, by default around 64MB, by creating large number of String literals in String pool, you can quickly fill permgen space.

    ReplyDelete
  7. Hello Javin, Can we use String in Switch case? This question is asked to me at TCS Interview? I said no, because Switch only accept integer values, but interviewer was not happy at all?

    ReplyDelete
  8. In the JDK 7 release, you can use a String object in the expression of a switch statement

    http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html

    ReplyDelete
  9. @Sanidhya A quick implementation, hopefully without bugs :)

    public class ReverseWords {
    public String run(String input, char delimiter){
    if (input == null) return null;
    char[] charArray = input.toCharArray();
    int wordStartIdx = 0;
    for(int i = 0; i from; to--, from++){
    char tmp = charArray[from];
    charArray[from] = charArray[to];
    charArray[to] = tmp;
    }
    }

    }

    ReplyDelete
  10. I left in a bug :), this is the bugfix:
    ...
    flip(charArray, wordStartIdx, charArray.length-1);
    return new String(charArray);
    }
    ...

    ReplyDelete
  11. My previous String reversal implementation is very basic and limited, the task is a little bit more complicated because of the unicode character representation: http://docs.oracle.com/javase/6/docs/api/java/lang/Character.html#unicode
    One have to consider surrogate ranges (a unicode character could be represented by two char-s)

    ReplyDelete
  12. two object are created to answer of shariq bhagat

    for in heap memory and another will in string pool as constant'

    and both have different hascode

    ReplyDelete
  13. my question is

    why we create main method , and how it will be created

    ReplyDelete
    Replies
    1. We need main method because the code starts its execution from main method. We can also say that main is pre declared user defined method.

      Delete
  14. 2 months after this posting question #8 became voodoo optimization: http://www.javaadvent.com/2012/12/changes-to-stringsubstring-in-java-7.html

    2 years later I'm still seeing this blog post thrown around without the correction. Here is a good overview of the differences: http://jaxenter.com/the-state-of-string-in-java-49450.html

    ReplyDelete
  15. How substring method work in Java ? , Answer for this question need an attention. The new JDK provided the fix for memory leak.

    ReplyDelete
  16. One question you need to add into this list is "What encoding method do Strings use?", as I strongly feel that Java developer should be aware of character encoding and make sure they use right encoding while converting bytes to string and vice-versa. I expect "UTF-16" or "UCS 2" as answer, though UTF-16 is more appropriate. If candidate mention about use of surrogate character pairs to represent certain characters then give him bonus point.

    ReplyDelete
  17. package com.str1;
    import java.io.*;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;

    public class B
    {
    public static void main(String[] args)throws IOException
    {
    String s1;
    System.out.println("Enter the String= ");
    BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
    s1=in.readLine();
    System.out.println(s1);
    char ch[]=s1.toCharArray();
    int j=0;
    for(int i=0;i<ch.length;i++)
    {
    //System.out.println(i);
    j=i;
    }
    System.out.println("Length="+(j+1));
    int len=(j+1);
    System.out.println("=reverse String is=");
    for(j=len-1;j>=0;j--)
    {
    System.out.print(ch[j]);
    }
    }
    }

    ReplyDelete
  18. @ Anonymous: Yes in Java 7 we can use String in Switch. but We can achieve it using Enum.

    private enum Fruit {
    apple, carrot, mango, orange;
    }

    String value; // assume input
    Fruit fruit = Fruit.valueOf(value); // surround with try/catch

    switch(fruit) {
    case apple:
    method1;
    break;
    case carrot:
    method2;
    break;
    // etc...
    }

    ReplyDelete

  19. /*input : my name is rajesh
    output :ym eman si hsejar
    */
    class Program20
    {
    public static void main(String[] args)
    {
    System.out.println("---------------------------------");
    String str="my name is rajesh";
    System.out.println("Given string :"+str);
    String[] st=str.split(" ");
    for(int i=0;i=0;j--)
    {
    System.out.print(st[i].charAt(j));
    }
    System.out.print(" ");
    }

    }
    }

    ReplyDelete
  20. Hi,
    I am using some string objects in my programme and in finally block making it null. Will it be garbage collected?

    ReplyDelete
  21. Hello
    shariq bharat
    there will be created 3 string objects

    ReplyDelete
  22. My solution using StringBuffer:
    //input:"my name is jack"
    //output:"ym eman si kcaj"

    public class ReversingCharcaterInAString {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    String sentence = new String("my name is jack");
    StringBuffer sb = new StringBuffer();
    StringBuffer sb1 = new StringBuffer();
    String a[] = sentence.split(" ");
    for (int i=0; i<a.length;i++){
    sb1.append(a[i]);
    sb1.reverse();
    sb.append(sb1.toString());
    sb.append(" ");
    sb1.delete(0,a[i].length());


    }
    System.out.println(sb.toString());


    }}

    ReplyDelete
  23. Can you guys explain, why two objects?

    ReplyDelete