Game Development Community

A question about Java Strings

by Mike Stoddart · in Technical Issues · 07/15/2002 (5:49 pm) · 6 replies

I'm slowly teaching myself Java, and I came across something that I need help with relating to the String class. I thought I'd ask here to get opinions, as my book doesn't give me an answer.

If I return a String from a method, should I make a copy of it before using it? Or can I access the instance that is returned from the method?

Thanks

#1
07/15/2002 (6:10 pm)
You don't have to make a copy. In Java Strings are objects, and all objects are in scope until their reference count goes to 0. There are no c++ "returning reference to temporary" problems.

Also, 'return "Foo"' is equivalent to 'return new String("Foo")'
#2
07/15/2002 (6:14 pm)
Thanks John; the part about the returned String being a new instance is what I was looking for.
#3
07/16/2002 (9:57 am)
There are no issues with returning objects from methods, as John mentioned, but whether String is right for you depends upon what you want to do. If you return a String from a method, you will get a fully new instance, which may be what you want, but perhaps you want to be able to modify the string in multiple places and have the changes reflect globally.

When dealing with these issues it helps to know that in Java *ALL* String objects are static and can't be modified after they are initialized.

If you do string concatenation using the + operator, for example, it doesn't actually append the new string to the existing string, it creates a whole new string object and assigns the value of the concatenated string to that object, eg:

String s1 = "this";
s1 += " and that";

On that second line a whole new s1 string object is created, it is not just an append.

If you want to deal with highly dynamic strings in a quicker manner, or get an in-place modifyable string return from another method use StringBuffer.
#4
07/16/2002 (9:58 am)
Thanks George; that info really helps.
#5
07/17/2002 (1:56 am)
Just a note: Java strings can KILL your performance.

I once wrote a JSP page that wrote to a large string, then outputted it. When I changed the page to write directly to output it ran literally twice as fast at least.

Basically anything you do with a string will create a new string. (multiple + operations on the same line are optmized to use a string buffer though) You would be amazed at how changing a hashtable to hash based on Integers instead of Strings will improve performance.

Be wary of using strings a lot. They are really convenient but come at a price.
#6
07/17/2002 (6:50 am)
I'm going to reemphasize what George said: use StringBuffer if you can.