Google

Jun 25, 2012

Core Java coding questions frequently asked in written tests and interviews - part 1: Immutability and object references

Core Java Coding Questions and Answers for beginner to intermediate level

Q1 Q2 Q3 Q4 Q5 - Q8 Q9 Q10 Q11 Q12 - Q14 Q15

Some core java questions are very frequently asked in job interviews and written tests to ascertain if you know the Java fundamentals. I have covered a few questions that are not covered in my books. These coding questions will also clear up the fundamentals.

Q1. What will be the output of the following code snippet?

String s = " Hello ";
s += " World ";
s.trim( );
System.out.println(s);

A1. The output will be

" Hello  World "

with the leading and trailing spaces. Some would expect a trimmed "Hello World".
So, what concepts does this question try to test?
  1. String objects are immutable and there is a trick in s.trim( ) line.
  2. Understanding object references and unreachable objects that are eligible for garbage collection.
What follow on questions can you expect?
  1. You might get a follow on question on how many string objects are created in the above example and when will it become an unreachable object to be garbage collected.
  2. You might also be asked a follow on question as to if the above code snippet is efficient.
The best way to explain this is via a self-explanatory diagram as shown below.






If you want the above code to output "Hello World" with leading and trailing spaces trimmed then assign the s.trim( ) to the variable "s". This will make the reference "s" to now point to the newly created trimmed String object.

The above code can be rewritten as shown below


StringBuilder sb = new StringBuilder(" Hello ");
sb.append(" World ");
System.out.println(sb.toString().trim( ));


The StringBuilder is not a thread-safe class. It is fine when you are using it as a local variable. If you want to use it as an instance variable then use the StringBuffer class which is thread-safe. If you are curious to know what happens under the covers during String manipulation -- String concatenation

Relevant must get it right coding questions and answers

Labels: ,

31 Comments:

Anonymous Anonymous said...

nice post :)

4:53 PM, June 27, 2012  
Anonymous Anonymous said...

In first illustration... comment line 3 and use System.out.println(s.trim());
The output is same as II illustration "Hello World", note the extra space between these two words. (It should have ideally truncate the space like "Hello World".)

6:30 PM, June 28, 2012  
Blogger Unknown said...

Yes, you could do

String s = " Hello ";
s += " World ";
System.out.println(s.trim( ));

The main purpose of this question is to understand immutability and object references.

7:00 PM, June 28, 2012  
Blogger Shahzad said...

It was really a nice article and i failed with ur question but m glad that i understood the concept

7:41 PM, July 12, 2012  
Anonymous jlemm said...

"String objects are immutable and there is a trick in s.trim( ) line."

I would thin the "trick" is in s += " World " since it makes it look like it's adding to the same String object while it is actually not.
There's not trick in s.trim() - the method signature is public String trim(), so it's pretty clear that the trimmed object is returned.

12:09 AM, July 13, 2012  
Anonymous jlemm said...

What you say above about the string being eligible for garbage collection is not correct and people should beware repeating this wrong information in an interview.

In your example you create string literals. String literals are special objects in Java and they are stored in a string literal pool, which is NOT garbage collected. This is precisely why concatenating strings in a loop can lead to problems, as it fills up the string pool.
Only strings created with new String(...) are garbage collected, since they're stored in the regular object heap.

11:59 PM, July 13, 2012  
Blogger Unknown said...

You are right jlem, and thanks for pointing this out.

As per the JVM Spec, the area for storing string literals is in the "runtime constant pool". The runtime constant pool memory area is allocated on a per-class or per-interface basis, so it's not tied to any object instances at all for which heap memory is used for. The JVM has "permgen heap" containing all the reflective data of the virtual machine itself, such as class and method objects. A string literal created like String s = "Hello" is stored in "permgen heap" and a string object created like String s = new String("Hello"); is stored in heap.

Under normal circumstances, String literals and other stuff in the permgen heap are not garbage collected. This means, the String literals are always reachable from the code that use them. However, I think the JVM can be configured to find and collect dynamically loaded classes that are no longer needed, and this may cause String literals to be garbage collected.

11:46 AM, July 14, 2012  
Blogger Unknown said...

In Java 7, the interned String (i.e. literals) are placed in the main heap space.

12:29 PM, July 14, 2012  
Anonymous jlemm said...

thanks for removing the incorrect information from the page (I hope it's not in the books also).
one more point, your phrase "permgen heap", even if you put it in quotes, is misleading, since the Permgen space is a separate area in the JVM that is NOT part of the heap.

12:59 AM, July 15, 2012  
Anonymous jlemm said...

Actually, I now see that the incorrect information about garbage collection is still part of the graphics on this page. I wonder why you keep information that you know is incorrect.

1:18 AM, July 15, 2012  
Blogger Unknown said...

Here is what the JDK7 reference says:

In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.

1:31 AM, July 15, 2012  
Anonymous jlemm said...

This documentation uses the word "heap" in an unusual way. What is usually referred to as "heap" is what they call the "main Java heap". If your aim is to provide information for interviews it is best to use standards understood by everyone rather than rely on an obscure reference in Oracle JDK 7 documentation.
(perhaps the explanation of this new vocabulary is that at some point in the development of JDK 7 the plan is to remove the Permgen space almost completely; see here: http://answerpot.com/showthread.php?3521332-Java+7+Perm+Gen)

See here for an explanation of why Permgen needs to be separate from the heap:
https://blogs.oracle.com/jonthecollector/entry/presenting_the_permanent_generation

1:05 AM, July 17, 2012  
Blogger DIPANKAR said...

who is jlemm :)

3:39 AM, July 18, 2012  
Blogger AVP said...

There are 4 objects that are created not 3.

1) " Hello "
2) " World "
3) " Hello World "
4) "Hello World"

Thanks for writing the post. You idea is correct, string concatenation is inefficient.

12:00 AM, September 17, 2012  
Blogger Kuldeep Singh said...

How to write a method, which recieved a number and return its 2's power?
i.g. if passed number to method is 13 it should return 3 as 13=2^3+5.

4:35 PM, September 26, 2012  
Blogger Unknown said...

I have one doubt pls help me in this

string s1="hi"
string s2 ="hello"
string s3=s1+s2
system.outprintln("valueis"+s3)
s1 ="world"
S3= s1+s2
system.outprintln("valueis"+s3)

what will the output of s3 will now
Pls ans this

5:12 AM, November 23, 2012  
Blogger Unknown said...

Try the program by executing and see what happens. That is the best way to learn.

1:43 PM, November 25, 2012  
Blogger aman said...

Greatly explained.

9:13 PM, December 01, 2012  
Blogger Unknown said...

what is the diff b/t class A and B
class A
{
int a;
int b;
public A()
{}
}

class B
{
public B()
{
int a=0;
int b=0;
}
}

8:41 PM, December 09, 2012  
Blogger Unknown said...

There are 4 objects that are created not 3.


another is " World "

4:00 PM, January 09, 2013  
Blogger KAP said...

nice blog.. try to give ans of java codes in my blog
kapjava.blogspot.com

9:11 PM, March 18, 2013  
Blogger Robin said...

String s1= "hi";
String s2 ="hello";
String s3=s1+s2;

System.out.println("valueis"+s3);
//It will print hihello

// Now s1 previous value is elligble for garbage
s1 ="world";
s3= s1+s2;
System.out.println("valueis"+s3);
so bow output woul be //worldhello

8:14 PM, April 22, 2013  
Blogger Ananth Chelladurai said...

IMHO, there should not be any "frequently" asked interview questions to access someone's skills. A nice article though. :-)

7:04 AM, May 07, 2013  
Anonymous Anonymous said...

valueishihello
valueisworldhello

12:48 AM, August 02, 2013  
Blogger Unknown said...

point taken Ananth.

2:53 AM, October 20, 2013  
Blogger Unknown said...

Your information is so helpful your giving brief information about the strings.I want to require more information on java.
java

7:51 PM, October 28, 2013  
Blogger Unknown said...

This comment has been removed by a blog administrator.

4:40 PM, November 29, 2013  
Blogger tofek khan said...

Hi Arun sir,

it is very good articles and help full for all of us. but my doubt is why string is immutable? what is the reason behind that.?

6:38 AM, April 01, 2014  
Blogger Unknown said...

The main reason is security so that passwords cannot be modified once constructed. Secondly, immutable objects are inherently thread-safe as they cannot be modified. Thirdly, it can be easily cached or reused.

5:12 PM, April 01, 2014  
Anonymous JAVA Training in Chennai said...

Thanks for sharing such a good information...

4:37 PM, April 17, 2014  
Anonymous Anonymous said...

nice trick to test:)

5:24 AM, October 14, 2014  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home