Get your CodeRanch badge!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes string construction Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "string construction " Watch "string construction " New topic
Author

string construction

zaghal mohd
Ranch Hand

Joined: Jun 27, 2002
Posts: 43
what is the different between the two forms of string construction
String a1 = "zaghal1";
String a2 = new String("zaghal");
if you can show me by code is better
Thanks in adv..


SCJP,SCWCD,CCNA,CCAI,MCP,MCSA,MCSE<br />working on CCNP+SCBCD
Nate Johnson
Ranch Hand

Joined: May 13, 2002
Posts: 301
Java keeps a table of strings that it already knows about, so in the case of a1, if that string is already in the table, it will just point to that table reference (or put a new ref in the table for future reference if it is not there).
When you say = new String("...") you are always creating a new string.
Try writing two loops that go to 50000 and time them. Inside of one put the a1 line and inside the other put the a2 line. You will see a big difference in the time it takes to run the two loops.


scwcd, scjd, scjp<br /><a href="http://natejohnson.us" target="_blank" rel="nofollow">http://natejohnson.us</a><br /><a href="http://rice.kuali.org" target="_blank" rel="nofollow">http://rice.kuali.org</a>
David Poglitsch
Greenhorn

Joined: Jul 26, 2002
Posts: 16
"a1" is a reference to a string literal that is created at compile time. The literal is stored on the stack.
"a2" is a reference to a string object that is created at run time. Objects are stored on the heap.
So since everything is spelled out at compile time for "a1", this should run faster.
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
Hello David.
The a1 variable is also pointing to a String object. In Java all the objects are created in the heap. The string literal is not in the stack, but in a structure called the constant pool. The first time the JVM is going to use it, it replaces it with the address to the object. (rough description)
All the variables that were initialized to same string literal content will be pointing to the same object.
[ August 03, 2002: Message edited by: Jose Botella ]

SCJP2. Please Indent your code using UBB Code
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Here's some:



Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Ian Wayne
Greenhorn

Joined: Aug 03, 2002
Posts: 8
Question about Stack and Heap, does java store local variables in Heap instead of Stack (as C++)?
Thanks.
Ian


Ian
David Poglitsch
Greenhorn

Joined: Jul 26, 2002
Posts: 16
Jose,
Am I right that the String literal that "a1" will reference is placed in the constant pool at compile time? And then the "a1" reference to that literal is resolved at run time because the "a1" is referring to a String object?
Will the "a2" String literal also go to the constant pool at compile time?
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9043
    
  10
All objects are on the heap. Primitives are on the stack. Strings are unique because they also have a "String pool".

originally written by Peter van der Linden in Just Java 2
The stack is a runtime data structure for keeping track of memory to support methods and recursive method invocation.

When you call a method, some housekeeping data, known as an activation record or stack frame, is pushed onto the stack. The activation record contains the return address, the arguments passed to the method, the space for local variables and so on. When you return from a method, the record is popped from the stack. The next method call will push another record into the same space.

If you have any pointers back into the old activation record on the stack, memory can be corrupted, as the pointer references an area that the next function call will reuse for a different purpost. This is a common problem in C/C++, and can be hard to debug. In other words, the lifetime of stack-based storage is tied to the scope in which it was allocated, and although some languages let you get this wrong, Java doesn't!

The heap is another runtime data structure used to support your program. It is a large storage area that is managed dynamically. All objects in Java are allocated on the heap; no objects are ever allocated on the stack.

[ August 03, 2002: Message edited by: Marilyn de Queiroz ]

JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
David Poglitsch
Greenhorn

Joined: Jul 26, 2002
Posts: 16
The byte code is kind of interesting comparing the two string assigments:

The "new String" line of code translates into 3 additional bytecodes.
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
ldc #2 loads in the operand stack a reference to the string object in the heap.
These are the related entries in the contant pool generated by the compiler -available in the class file.

The first (number 2) entry tell us that is of type literal string and give the number (16) of another entry that holds the content of the literal string.
The runtime contant pool is very similar to the one generated by the compiler. The first time the JVM uses the string literal it looks up in the string pool to see if another string object with the same contents already exist. If so it places the address of the string object in the CONSTANT_String_info entry. If there is no a string object with same content creates one new string object, adds it to the string pool and, again it places the address in the constant pool entry for the ldc bytecodes to use it.
[ August 04, 2002: Message edited by: Jose Botella ]
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
Local variables that are of primitive type are placed in the stack. Instance primitive fields are placed in the heap as part of the object image. Static primitive fields are placed in the method area as part of the class data -the class where they were declared.
zaghal mohd
Ranch Hand

Joined: Jun 27, 2002
Posts: 43
What I understand from this replay is that correct
String s = "Testing String";
creating the String object in the above format then the String object is available in the pool of string literals. If the same string is there already in pool of strings then the old string will be replaced with the new one.
String s1 = new String("Testing String");
constructing the String by calling new then the String object will be created at runtime and will not there in pool of strings
correct me if i am wrong!!
Thanks for having some patience with me.
Yours respectuflly zaghal mohd
David Poglitsch
Greenhorn

Joined: Jul 26, 2002
Posts: 16
So based on the bytecode, it seems to me the following is happening:
For String s1 = "String";
s1 (reference) --> a "String" constant in the
string pool
For String s2 = new String("String");
s2 (reference) --> String object, which in
turn has a reference to
the same "String" constant
that s1 is referencing.
In my mind the first code is more of a direct reference to a constant; the second code is indirect.
Who knew strings could be so much fun
David Poglitsch
Greenhorn

Joined: Jul 26, 2002
Posts: 16
I "discovered" the Google search, and found this discussion we're having was done way back in Feb 2000 with replies from the Trailboss!
Feb 4, 2000 String Discussion
Summary: s1 and s2 ultimately point to the same string constant. s2 just creates an extra object in doing it.
Have we beat this horse to death yet?
(I did appreciate seeing the graphics on the string pool - how'd ya do that, Jose?)
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
from zaghal:

If the same string is there already in pool of strings then the old string will be replaced with the new one.

Before creating the new string object the JVM looks up in the string pool. If an exactly matching string exists no new one is created and the one residing in the pool will be returned. Because of that all the string literals with the same content and all the string objects that were interned (see API String.intern() ) point to the same object; and thus, the operator == will return true.

String s1 = new String("Testing String");
constructing the String by calling new then the String object will be created at runtime and will not there in pool of strings

All the objects are created at runtime. It happens that the string object pointed by s1 won't be in the string pool.

From David:

For String s2 = new String("String");
s2 (reference) --> String object, which in
turn has a reference to
the same "String" constant
that s1 is referencing.

No, s2 is pointing a different string object than s1. Check it with ==.
You may be confused by "ldc #2 <String "String">" This only provides a paramater to the constructor with the content for the new object. The new string object won't be at he string pool unless you intern it.
The "graphics" are not the string pool but two entries in the constant pool. Each class has a constant pool that acts like the symbol table in other languages. You can get a free good old class file parser from here
zaghal mohd
Ranch Hand

Joined: Jun 27, 2002
Posts: 43
Thank you Jose David and every body´┐Ż. help me to understand this question
Thanks for having some patience with me.
Yours respectfully
zaghal mohd
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: string construction
 
Similar Threads
Ya got String, got StringBuffer - and now ya got StringBuilder!
easier way to tell the difference of these??
main() parameter construction
WA #1.....word association
Overloading constructors with differing intializations