" Hello World "
|
with the leading and trailing spaces. Some would expect a trimmed "Hello World".
So, what concepts does this question try to test?
What follow on questions can you expect?
|
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
- Core Java coding questions frequently asked in written tests and interviews - part 2 - == Vs equals()
- Core Java coding questions frequently asked in written tests and interview - part 3 - overload Vs override
- Core Java coding questions frequently asked in written tests and interview - part 4 -- iteration Vs recursion
- Reviewing a given Java code at job interviews and code review sessions
- Java coding question and answer on multi-threading
- Java OO interview questions and answers.
- Java coding interview questions and answers -- swapping, reversing a string, etc
- Can you write code by asking the right questions?
- Handling the programming question on the popular Fibonacci number.
- Java writing code -- compare two CSV files in Java.
- Working with Java Calendar and Dates - coding Q&A.

nice post :)
ReplyDeleteIn first illustration... comment line 3 and use System.out.println(s.trim());
ReplyDeleteThe 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".)
Yes, you could do
ReplyDeleteString s = " Hello ";
s += " World ";
System.out.println(s.trim( ));
The main purpose of this question is to understand immutability and object references.
It was really a nice article and i failed with ur question but m glad that i understood the concept
ReplyDelete"String objects are immutable and there is a trick in s.trim( ) line."
ReplyDeleteI 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.
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.
ReplyDeleteIn 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.
You are right jlem, and thanks for pointing this out.
ReplyDeleteAs 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.
In Java 7, the interned String (i.e. literals) are placed in the main heap space.
ReplyDeletethanks for removing the incorrect information from the page (I hope it's not in the books also).
ReplyDeleteone 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.
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.
ReplyDeleteHere is what the JDK7 reference says:
ReplyDeleteIn 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.
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.
ReplyDelete(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
who is jlemm :)
ReplyDeleteThere are 4 objects that are created not 3.
ReplyDelete1) " Hello "
2) " World "
3) " Hello World "
4) "Hello World"
Thanks for writing the post. You idea is correct, string concatenation is inefficient.
How to write a method, which recieved a number and return its 2's power?
ReplyDeletei.g. if passed number to method is 13 it should return 3 as 13=2^3+5.
I have one doubt pls help me in this
ReplyDeletestring 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
Try the program by executing and see what happens. That is the best way to learn.
ReplyDeleteGreatly explained.
ReplyDeletewhat is the diff b/t class A and B
ReplyDeleteclass A
{
int a;
int b;
public A()
{}
}
class B
{
public B()
{
int a=0;
int b=0;
}
}
There are 4 objects that are created not 3.
ReplyDeleteanother is " World "
nice blog.. try to give ans of java codes in my blog
ReplyDeletekapjava.blogspot.com
String s1= "hi";
ReplyDeleteString 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
IMHO, there should not be any "frequently" asked interview questions to access someone's skills. A nice article though. :-)
ReplyDelete