aspose file tools*
The moose likes Beginning Java and the fly likes Strings in java. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Strings in java." Watch "Strings in java." New topic
Author

Strings in java.

krishna nav
Greenhorn

Joined: May 25, 2006
Posts: 7
String s1 = new String("abc");

String s2 ="abc";

both can used interchangably to create String objects right ?
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
Yes. But they are a litte different. s1's string object is created on heap and s2's string object is in string pool.
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
Unless you are dabbling in the black art of hacking, I suggest you stick to the latter:

String s2 ="abc";


Perhaps the reason you see new String("abc") written sometimes, even in text books, is that the author is coming from a C++ background, where "abc" is not of type string. For 10 points, what's the primary type of expression "abc" in C++?
[ May 25, 2006: Message edited by: Jeff Albertson ]

There is no emoticon for what I am feeling!
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Originally posted by wise owen:
Yes. But they are a litte different. s1's string object is created on heap and s2's string object is in string pool.


Gaaaak!

s1 is a reference to an object that's already in the heap when this code executes. It is created while the class is loaded. There is another reference to this object in the string pool. The string pool is just like a Set of String references; it's not a special area of memory in which objects can be created.

s2 is a new object created right here in the code, a copy of the String s1 is already pointing to. As Jeff points out, there's virtually never any reason to use this String constructor -- mostly only to write tricky code fot the SCJP exam. It's just wasted cycles.


[Jess in Action][AskingGoodQuestions]
rama murthy
Ranch Hand

Joined: Jan 13, 2006
Posts: 82

"s1 is a reference to an object that's already in the heap when this code executes."


Ya I agree s1 is a reference to an object that's in the heap.


"It is created while the class is loaded."


I got doubt here. s1 is NOT declared as static here. Then how come it will be created when class in loaded.


Do you mean all String declarations like

String name = "Ranch";

will be created on heap when class is loaded.


"The string pool is just like a Set of String references; it's not a special area of memory in which objects can be created"


OK, then where does String constant pool exist.

Isn't String Constant Pool a part of heap. If its NOT then where does it reside.
rama murthy
Ranch Hand

Joined: Jan 13, 2006
Posts: 82
Anyone interested in answering this question.
ak pillai
author
Ranch Hand

Joined: Feb 11, 2006
Posts: 288
String pool is a special memory area where String str = "abc" are stored. When the compiler sees a new String then it first searches through this String pool to find this String for reuse, otherwise the new String is created and stored in this pool.


java j2ee job interview questions with answers | Learn the core concepts and the key areas
Jeroen T Wenting
Ranch Hand

Joined: Apr 21, 2006
Posts: 1847
not the compiler, the runtime


42
rama murthy
Ranch Hand

Joined: Jan 13, 2006
Posts: 82

String pool is a special memory area where String str = "abc" are stored. When the compiler sees a new String then it first searches through this String pool to find this String for reuse, otherwise the new String is created and stored in this pool.



ak pillai
String pool is a special memory area where String str = "abc" are stored.




Ernest Friedman-Hill
String pool is a NOT a special memory area, only String references are stored and NOT the actual String Object.

Objects are stored in HEAP.


Both your posts are highly contradicting.


When the compiler sees a new String then it first searches through this String pool to find this String for reuse, otherwise the new String is created and stored in this pool.


If String constant pool has only references then how come strings are compared and NOT new string objects created in heap.
Jeroen T Wenting
Ranch Hand

Joined: Apr 21, 2006
Posts: 1847
From the Java Virtual Machine Specification (2nd edition, paragraph 5.1):

The Java virtual machine maintains a per-type constant pool (�3.5.5), a runtime data structure that serves many of the purposes of the symbol table of a conventional programming language implementation.
The constant_pool table (�4.4) in the binary representation of a class or interface is used to construct the runtime constant pool upon class or interface creation (�5.3). All references in the runtime constant pool are initially symbolic. The symbolic references in the runtime constant pool are derived from structures in the binary representation of the class or interface as follows:


The constant pool contains references to String objects on the heap.
When a String is requested, this pool of references is checked for one that points to a String on the heap with the desired value.
If one is found, the matching reference is used. If not, a new String object is created on the heap, a reference to it is placed in the String constant pool, and that reference is used.
rama murthy
Ranch Hand

Joined: Jan 13, 2006
Posts: 82
Let me explain my understanding. Correct me if I am wrong.

String name = "abc";

So the JVM checks the string constant pool to see if any reference points to a string object with the same value(abc). If so NO new string object with the value "abc" is created on the heap. Instead the already existing reference is used internally which is assigned to the reference name. Or else new new string object is created on the heap and the reference "name" is placed in string constant pool.
Jeroen T Wenting
Ranch Hand

Joined: Apr 21, 2006
Posts: 1847
yup, that's pretty much what happens.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by rama murthy:
Let me explain my understanding. Correct me if I am wrong.

String name = "abc";

So the JVM checks the string constant pool to see if any reference points to a string object with the same value(abc). If so NO new string object with the value "abc" is created on the heap. Instead the already existing reference is used internally which is assigned to the reference name. Or else new new string object is created on the heap and the reference "name" is placed in string constant pool.


That is wrong.
The object (or instance if you prefer) is created at class load time. The rest is quite self-explanatory - or if it isn't, the issue has been covered many times already. Here is my contribution: http://jqa.tmorris.net/GetQAndA.action?qids=68&showAnswers=true


Tony Morris
Java Q&A (FAQ, Trivia)
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Mmmm, Rama doesn't seem to say when this occurs, so I see no contradition between his statements and Tony's. Though it does seem to be true in general that many people do not realize that this process occurs at class loading time, so it's probably worth explicitly pointing out.


"I'm not back." - Bill Harding, Twister
rama murthy
Ranch Hand

Joined: Jan 13, 2006
Posts: 82

Though it does seem to be true in general that many people do not realize that this process occurs at class loading time, so it's probably worth explicitly pointing out.


I am confused again.

Let me explain you my doubt. Lets consider the following example

Class Super {
int E_No = 1200;
}

Class A extends Super{

static int in = 5;
String name = "Java";
B b = new B();

public static void main(String[] args) {
}
}

Class B {
int i =10;
}

So as per your words during the class loading of "class A" two objects will be created
(1) String object &
(2) Object B.

But my understanding here is

1. Once I type "java A" from console JVM loads the class (Class A)

2. main method is invoked.

3. All static variables are initialized to their assigned values(like in = 5). And if any static reference variables are present then Objects refered by them are loaded.
[ Jim my understanding is only Objects refered by static reference variables are loaded. This happens before Constructor of current class and super class constructor completes]
[ You are saying even if non-static String declaration
String name = "Java";
will create an String object in heap.]

For example if it is like
static B b = new B();

then Object B will loaded during class loading of class A.

4. Then class A's constructor is called and all the instance variables are given their default values (like int assigned with 0, float assigned with 0.0, Object reference like "b" assigned with null)

5. The first thing that happens inside the constructor is a call to super class constructor is made and all the instance variables are initialized to their assigned values like (E_No = 1200) in the Super class.

6. Then control returns to the constructor of Class A and normal execution of class A continues.

. Kindly correct me if there are mistakes.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[prama]: So as per your words during the class loading of "class A" two objects will be created
(1) String object &
(2) Object B.


No, we were talking about String constants and constant expressions - those are created (if not already in the pool) at class load time. This is a special rule for String constants; other reference types like B are unaffected. So at class load time, the string "Java" is created (if it didn't already exist) and a reference is put in the string pool. No B instances are created however - that happens later, when you expect it to.

Going to some earlier posts:

[ak pillai]:
String pool is a special memory area where String str = "abc" are stored.

[Ernest Friedman-Hill]:

String pool is a NOT a special memory area, only String references are stored and NOT the actual String Object.

Objects are stored in HEAP.

[rama]: Both your posts are highly contradicting.


I would say that the string pool may indeed be a special area in memory for references to Strings, but the actual String instances they refer to are located on the normal heap.

Well, as far as we've been told. There are some indications that may not be entirely true, despite what the specs say, but it really doesn't matter, I think.

Jeroen, it looks like you're confusing two similar but different types of runtime pools. Each class has its own runtime constant pool which references any constants used by that class. This includes String constants, but also primitives. Meanwhile the String class also maintains its own intern pool, described most clearly at the String.intern() method. This intern pool contains only Strings, and there should be only one intern pool in the whole JVM. (Unless there's a way to load the String class twice with different classloaders, but thatshould be impossible as far as I know.) When a class uses a String constant, then there will be an entry for the constant in that class's runtime constant pool, and also in String's intern pool. It's the latter that is most responsible for the unusual behavior of String constants, because if a different class declares an equivalent String constant, that class will have a different runtime constant pool, but share the same String intern pool.
[ June 04, 2006: Message edited by: Jim Yingst ]
sun cheng
Greenhorn

Joined: Jun 02, 2006
Posts: 17
ok!All is answered!
stephen shields
Greenhorn

Joined: Jun 05, 2006
Posts: 20
to jeff albertson

i came from a c++ background and "abc" in c++ is a character array.
in c++ all strings are an array of characters
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Strings in java.