aspose file tools*
The moose likes Java in General and the fly likes Local String literals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Local String literals" Watch "Local String literals" New topic
Author

Local String literals

Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
If I declare a String literal in a method, is that String literal pooled so that on the next call to the method the pooled string is used? String literals are not garbage collected I know, but the variable referencing the literal would go poof! when the method is exited.
Awaiting, breathlessly, for your answer...
-Worried, Zurich, Switzerland.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
If I declare a String literal in a method, is that String literal pooled so that on the next call to the method the pooled string is used?
Yes.
String literals are not garbage collected I know, but the variable referencing the literal would go poof! when the method is exited.
Well, depending on how the code is written there may or may not be one or more local variables referencing the string. Local variables are allocated on the stack, and so yes they go "poof when the method exits. But the JVM instruction set also has the ability to refer to a comppile-time constant (such as a String constant) directly, without using another reference. That's how any other references get initialized. E.g. this code:generates the following byte codes (interpreted by javap):while thisgenerates
The _1 instructions refer to reading and writing from local variable register #1, which corresponds to s in this case. But looking back at the earlier program, there was no local variable - the ldc command loaded a reference from the constants table (not shown here), and that was passed to the println method. The point is, there's infrastructure here to refer to constants without using local variables - the constants will be maintained even after local variables go "poof".


"I'm not back." - Bill Harding, Twister
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2854
    
  11

Well, Jim's answer is (as usual) more complete, but as I've already gone to the trouble, I might as well post this code:

The output I get is "true".
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Thanks Jim and Greg. Now I will put my question on a little more context. Consider the following:

I was recently critized for doing this with the remark "This is not data you are going to change, so you should move it outside of the method and make it final.
Defining constants inside your methods is a bad practice"
Now I like to think that I am localizing these Strings to the place where they are used, and because they are pooled there is no reason why they should be made into class members and made final.
I would like to have the opinion of others on this.
BTW the class was more complex than this and there were more methods.
Thanks
[ April 08, 2003: Message edited by: Barry Gaunt ]
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451

Now I like to think that I am localizing these Strings to the place where they are used, and because they are pooled there is no reason why they should be made into class members and made final.

I agree with you Barry. I think it makes your code more readable. Who want's to go searching thru the class to find a couple of (immutable)constants that you only use in one method.
Michael Morris


Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
I just wanted to mention that there are of course some strings that can and should be pulled up into the class or one of its superclasses.
jason adam
Chicken Farmer ()
Ranch Hand

Joined: May 08, 2001
Posts: 1932
I'd have to agree with ya Barry, if you have written the application so that all page output eventually gets passed through this method, versus having several methods that refer to the same constants, then why not stick them in the method?
Probably some OO concept that some may say this remotely violates, but probably more a personal preference. Seen some people who take moving Strings to the class level to the extreme and as Michael points out, it gets rather annoying having to hunt them down.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Barry, you're not trying to get me in trouble with Marilyn, are you?
I also tend to agree, though I can imagine circumstances where constants at the top/bottom of the class might be more readable. For example if the string is long, I might want to pull it out of my method, because I hate having methods too big to fit on my screen at once if I can avoid it. Or if htmlTop and htmlBottom were used by different methods, and those methods had some complex code in them, I might want to make the variables into class constants so that I could put most/all of the HTML in one place, without all that distracting Java code in between. (Then again, that's what a JSP would be for...).
So basically, I don't buy the argument that you should declare an instance variable just because something's constant - but I might well buy an argument based on reducing the visual complexity of a single method.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Jim:Barry, you're not trying to get me in trouble with Marilyn, are you?
No, no definitely not! Well maybe, just a little, I did put a post in CD linking over here. I'm more interested in justifying my arguments for use in my non-CD stuff (SCJD).
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20636
    ∞

It depends on your purpose. If you are just trying to keep from having a super long method call, there are lots of times I'll move something into a temporary variable just above the call. Or, if I feel I need a comment but think that self documenting code will work, I might introduce a variable to introduce some clarity.


permaculture Wood Burning Stoves 2.0 - 4-DVD set
Elouise Kivineva
Ranch Hand

Joined: Feb 07, 2002
Posts: 154
Seeing the key word final does give any reader of the code an important piece of information about your intentions.
I would also think it makes the code more expandable: if those html blurbs more readily available to all methods it's easier to add new methods to print new and different responses.
I think you only need the method
generateMoreHtml(PrintWriter pw). It could use constants htmlTop and htmlBottom. One less method (printIt is dumped) should make the code a bit more readable.
[ April 09, 2003: Message edited by: Elouise Kivineva ]
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9047
    
  10
Originally posted by Jim Yingst:
... I can imagine circumstances where constants at the top/bottom of the class might be more readable. For example if the string is long, I might want to pull it out of my method, because I hate having methods too big to fit on my screen at once if I can avoid it. Or if htmlTop and htmlBottom were used by different methods, and those methods had some complex code in them, I might want to make the variables into class constants so that I could put most/all of the HTML in one place, without all that distracting Java code in between. (Then again, that's what a JSP would be for...).


I think that Jim hit the nail on the head.
1) It depends on the size of the String/constant.
2) It depends on whether the String/constant is used by more than one method.


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

Joined: Oct 01, 2001
Posts: 2854
    
  11

It's a matter of style, and could go either way. We've already proved it won't affect performance.
For what it's worth, I had one class that used prepared SQL statements, which I made static finals. I can't remember if they were used in more than one method, but they were easier to find and update being at the top of the class like that. Obviously, they didn't change during the run of the application, but we did have to adapt to changing table structures several times, especially in the early development stages. That may not be a factor with your HTML.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671

2) It depends on whether the String/constant is used by more than one method.

Minor misunderstanding here, I think. I believe we were just talking about the case where a given constant is used in only one place; I think we already agree that if it's used in two different methods, it should probably by a class constant. I also said that if two different constants were used in separate methods (one method apiece), I might still find it useful to declare them as class fields, because that would allow me to put the two declarations next to each other. This is useful if the values are somehow related, like two pieces of HTML which will form a single document, or two different SQL statements dealing with the same table. (Good example, Greg.)
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Thanks, everybody, for your replies. You've given me some interesting opinions.
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9047
    
  10
Oh, sorry, Jim. I had misunderstood your statement. Thanks for the clarification. I agree with it as well.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Local String literals