Java - Interview Questions - Explain The Code - String

String str = getObject().getString().concat("Explain").concat("This").concat("Code").trim();

** assuming it compiles fine.

Q1. What are we doing with this code ?

Possible Ans. We are calling getObject method to get an object and then calling object's getString method to get the string, appending the Strings "Explain" , "This" and "Code" to it, trimming the trailing and leading spaces and then assigning the final string to str.

Q2. What kind of method is getObject - static or instance ?

Possible Ans. That depends on the method that holds this code. If it's within static method or static block, getString is a static method.  If it's within instance method , it could be either static or instance method.

Q3. What kind of method is getString - static or instance ?

Possible Ans. It could be anything. We cannot find that out by this code alone.

Q4. Can this code throw NullPointerException ? when ?

Possible Ans. If the getObject method returns null or  getObject().getString() returns null.

Q5. What check should we have to make sure that this code doesn't throw NullPointerException ?

Possible Ans. if(getObject() != null && getObject().getString() != null ) {
              String str = getObject().getString().concat("Explain").concat("This").concat("Code").trim();
Q6. Won't the second condition evaluation getObject().getString() != null result in NPE again if getObject() is null ?

Possible Ans. No, If the first condition is returned false, it will result in boolean short circuit and second condition will not be evaluated.

Q7. How many Strings will get created in memory for this code ?

Possible Ans. That depends on the strings we already have in String Pool, Assuming that we don't have string literals "Explain","This" and "Code" in String Pool, This code will create 6 new strings

1. Explain
2. This
3. Code
4. String created by concatenating Explain to the base string.
5. String created by concatenating This
6. String created by concatenating code

Q8. Can we avoid creation of 4,5 and 6 ?

Possible Ans. Yes , by having immutable classes like StringBuffer and StringBuilder.

Q9. Lets say the base string which we get getObject().getString() is "Lets" ? Will new strings "Lets Explain","Lets Explain This" and "Lets Explain This code" be created in String Pool ?

Possible Ans. No, String Pool only maintains strings that are specified as string literals.