Tuesday, April 19, 2011

Java Strings Interview Questions

The following are some questions you might encounter with respect to Strings in any Java Interview. Strings are very powerful and frankly speaking, there can be no Java based application that does not use Strings.

Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Strings that you might find useful. You can use them to revise/review your understanding of Strings.

They are:

Java String Class
StringBuffer & StringBuilder


Questions:

1. What would you use to compare two String variables - the operator == or the equals() method?

I would personally prefer/use the equals() method to compare two Strings if I want to check the value of the Strings and the == operator if I want to check if the two variables point to the same instance of the String object.

2. For concatenation of strings, which method is good, StringBuffer or String ?

StringBuffer is faster than String for concatenation. Also, it is less memory/resource intensive when compared to Strings.

3. As a continuation to the previous question - Why would you say StringBuffers are less resource intensive than Strings during Concatenation?

As you might already know, Strings are immutable. So, when you concatenate some value to a String, you are actually creating a fresh String object that is going to hold some more data. This way you have created a new object while the old String object is still alive. As you keep concatenating values to the String, newer objects are going to get created which are going to use up the virtual memory. Whereas, if you use a StringBuffer, you are just editing the objects value rather than creating new objects.

4. To what value is a variable of the String type automatically initialized?

The default value of String variable is null.

5. What is the difference between the String and StringBuffer classes?

String objects are constants or in other words immutable while StringBuffer objects are not.

6. What happens when you add a double value to a String?

The result is a String object. For that matter, if you add anything to a String, you will end up with a String.

7. What will be the result if you compare StringBuffer with String if both have same values?

It will return false as you cannot compare String with StringBuffer directly. If you really want to compare the contents of the String & the StringBuffer you would have to invoke the equals method with the String and the toString() output of the StringBuffer.

8. What is difference between String, StringBuffer and StringBuilder? When to use them?

For all practical understanding purposes, all these 3 classes are used to handle/manipulate Strings. The main difference between these 3 classes is:

* Strings are immutable while StringBuffer & StringBuilder objects are mutable (can be modified)
* StringBuffer is synchronized (thread safe) while StringBuilder is not. 

9. When to use Strings or StringBuffer or StringBuilder? What will drive this decision? 

The type of objects you need to create and how they will be used will drive this decision. So, 

* If the object value is not going to change, use the String class
* If the object value will be changed frequently we must choose either the StringBuffer or the StringBuilder. 
* Here, if your object will be accessed only by a single thread use StringBuilder because it is faster 
* If your object may be accessed my multiple threads use the StringBuffer because it is thread safe 

Note: Thread safety is not free and comes at the expense of performance. So, if your system is not multi-threaded then use the StringBuilder which will be much faster than the StringBuffer. 

10. Why String class is final or immutable?

The reason "Why" the string class is final is because - The developers of the Java language did not want programmers to mess with the basic functionality of the String Class. Almost all the basic or core functionality related classes in Java are final for the same reason. 

If String were not final, you could create a subclass and have two strings that look alike when you see the value in the string, but that are actually different. 

Ex: See the two string objects below, MyString and YourString are two classes that are sub-classes of the "String" class and contain the same value but their equality check might fail which does not look right. Doesnt it? 

MyString str1 = "Rocky";
YourString str2 = "Rocky";

This is why String class is final. 


If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on Strings that you have faced during your interviews and wish to add them to this collection - pls drop a note to anandvijayakumar007@gmail.com and I shall be glad to add them to this list.

More Java & J2EE Interview Questions with Answers - Click Here

11 comments:

  1. Can you tell me about string pool........

    ReplyDelete
    Replies
    1. Case 1:

      String s1 = "xyx";
      String s2 = s1;

      Case 2:

      String s1 = "xyz";
      String s2 = "abc";

      Concept of String pool is such that each string value occupies the place in the Heap memory of JVM inside the String pool.

      In Case 1:
      s1 variable with value as xyz get stored in String pool. And second variable s2 gives reference to same place in pool with same value.

      In case2:

      S1 variable is created within the string pool within the heap memory of jvm having value xyz.While, S2 has new space in heap memory within the string pool having value as "abc".

      if we now do string operations of comparing such as (equals() or == )method ,then it checks the presence of the declared varaible in the string pool present in the heap memory of the JVM.

      Delete
  2. @ anonymous

    JVM has the String Pool. All the String Objects which are created by assignment are stored in the pool. This pool is present in the heap. So whenever any assignment is done for a String, the JVM first checks in the String Pool whether that String is already present or not. This is done by calling intern() method present in the String class. If the JVM finds the same String then it return the same reference else it creates a new one.

    But, if you use the new Operator, a new object is created every time.

    ReplyDelete
  3. Can you answer the two following questions?

    1. What is difference between String, StringBuffer and StringBuilder? When to use them?
    2. Why String class is final or immutable?

    Thanks
    Mukesh

    ReplyDelete
    Replies
    1. These questions are added to the list above. Check out the answers man.

      Thanks
      Anand

      Delete
  4. you have explained why String is marked final. But final and immutable are two very different aspects. As String object is immutable, you can pass it around as method parameter without worrying if the invoked method changes its state(content), just like in case of a primitive (pass by value).

    ReplyDelete
  5. u hv explained in easy way !

    ReplyDelete
  6. In one of the interview I face question on strings as
    What will be the output if you compare null with string, and what will be the output if you compare string with null?

    Can you please let me know how java handle null?

    ReplyDelete
  7. Handling Strings in Java is tricky esp if they are nulls. Actually speaking, this null problem could creep up for any object in java.

    It is a good idea to check for nulls before you use a string or any object in any operation.

    Ex:

    public String st = null;

    if(st.equals("AB")) {
    .. do something..
    }

    The above code will throw a null pointer exception because the JVM cannot execute a equals check on the string object st because it is null.

    Instead if you try like

    if(null != st && st.equals("AB"){
    ..do something..
    }

    The above will not give an error because the first part of the condition is checking for null and only if st is not a null string the second condition will execute and hence your code is safe from null pointer exceptions.

    null pointer exceptions are probably the single biggest bugs faced/introduced by novice java developers.

    best of luck.

    Anand

    ReplyDelete

© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers