Jump to content

Strings in Stack and Heap

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
ibad

ibad

    Learning Programmer

  • Members
  • PipPipPip
  • 39 posts
Ok...I am very confused.

I thought that with all strings that are local variables the reference was a local variable in the Stack and the string was in the Heap.

But someone told me that there is a difference between these two instantiations:

String a = "hello";

String b = new String("hello");

According to the "someone" who spoke to me in one of these the whole string will be stored in the Stack... or that two strings would be treated differently in memory than the normal I outlined above.

Is this true?? :(

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
Not in Java. A string is an object, and as such is automatically allocated on the heap like all Java objects. The two syntaxes behave in the same way, the only reason that occurs is because Java has special support for String objects built into the language, so you can use either syntax without problems.

While they're functionally similar, according to some, the secondary syntax produces two objects, one of which it instantly throws away and leaves to the garbage collector.
Wow I changed my sig!