A String Question to Ponder

Posted on 2002-06-07
Last Modified: 2010-03-31
Ok. Experts, try this one....

I have a String Constant.

  String str1 = "Hey baby!";

So, what happens here is that there is a String in a memory location (say at Address 5000) and str1 is now pointing (Referring) to that address (meaning str1 has value 5000).

If I do a change to this string....

  str1 = "Hello Baby!";

now str1 is NOT pointing to the same address. i.e.str1 contains no 5000 but something else. i.e. "Hello Baby!" is a new string constant. In fact the original string "Hey Baby!" is now garbage collected by the gc.

Now if I allocate a string like this...

  String str2 = new String("Hey baby!");

Then a new memory location (an object) is created and the value "Hey Baby!" is placed in there. So str2 is now referring to a memory location say 8000). THIS NOT A STRING CONSTANT. THIS IS A STRING OBJECT according many books. If I do a change to this string...

  str2 = "Hello Baby!";

Then the same thing happened in str1 also happens here. In other words, the String Object str1 is now garbaged collected and str2 is now pointing to a new String object with the value "Hello Baby!".

So in both cases exact same result happens. If that is the case what's the use of having a String Constant?. Isn't a String object acts exactly as a String Constant?
Question by:prain
  • 4
  • 3
  • 2

Expert Comment

ID: 7061978
all string are objects - independently if they are constants or not.
to declare a constant - use this:
public static final Strig strConstant = "const_value";

this string object will never be garbage collected and the strConstant cannot be changed to point to another object

Author Comment

ID: 7062006
I agree.

But then why Java documentation, books  etc.... use the word "String Constant" to a declaration like...

String str1 = "Hello!";

Further is I declare anoter with the same value...

String str2 = "Hello!";

Why do both str1 and str2 have the same address?. Is'nt is because "Hello" is a constant?.


Expert Comment

ID: 7062026
"Hello!" is the string constant, str1 and str2 are only references to this constant. the reason for having same addresses for the both references is because java is doing some optimizations. As you can see - you don't have a way to modify a string object directly. If you want to perform such operation (for example str1 += " Second hello.";) then the result will be a new string object.
ScreenConnect 6.0 Free Trial

Check out the updates in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI that improves session organization and overall user experience. See the enhancements for yourself!

LVL 35

Expert Comment

ID: 7062043
>  Why do both str1 and str2 have the same address?. Is'nt is because "Hello" is a constant?.

  This done in Java in order to preserve memory and for optimization reasons (at least from Java2 onwards).

  Note that if you create two String objects using

  String s1 = new String("hello");
  String s2 = new String("hello");

  then the

  s1 == s2 will yield false while the

  String s1 = "hello";
  String s2 = "hello";

  s1 == s2 will yield true;

  In java new object are created using two ways, either by using the "new" operator or either by loading a class dynamically (for example Class.forName("<class name>")). By assigning the value "hello" (or any other value) to multiple Strings without using the "new" operator the JVM tries to preserve memory space, that's why you get variables that point to the same memory adress.

  Hope it helps.

Author Comment

ID: 7062045
I agree with all you say...

So. In otherwords, all Java strings including objects can be called as string "Constants".

Because even if you define a string like this...

  String str1 = new String("Hello");

What you say in last reply paragraph2 applies. Right?.

So in my opinion, a String constant and a constant String
are two different things. In a contant String, your make it final, so that the variable cannot be used for any other purposes. But if a String variable is used to point to a String Constant, that variable can be used to point to another String constant (or an object).


Accepted Solution

Venci75 earned 50 total points
ID: 7062054
yes - that is
LVL 35

Expert Comment

ID: 7062060
... as Venci75 clarified first of course...
LVL 35

Expert Comment

ID: 7062084
> So. In otherwords, all Java strings including objects can be called as string "Constants".

  Yes because in Java the object String is immutable, that is, once allocated it cannot be changed. Any change to the original String results in another, new String. This has performance and memory issues, this is why it is better to use StringBuffer for loads of String operations. And this si why it is called a String constant, because every change in the String results in a new one and the original is eligible for gc.

  As you said of course (and as Venci75 pointed out first) a constant String is one that is declared using the "final" keyword.

  Hope it helps.
LVL 35

Expert Comment

ID: 7062093
>  And this si why it is called
a String constant, because every change in the String results in a new one and the original is eligible
for gc.

  To add here... So the original one is constant, it cannot be changed.

  P.S. Whoah.. things move really fast with EE. :-)

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
sites similar to codingbat to improve coding hanson skills 3 49
print map entry 34 68
Java exception bubble up 2 18
Desingning Refactoring existing code 2 24
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question