RE: Re: Comparsions of String objects with == produces incorrect result
"Shankar Unni" <[email protected]> Mon, 1 Nov 2004 08:44:03 -0800
| Newsgroups | gmane.comp.java.beanshell.devel |
|---|---|
| Message-ID | <[email protected]> |
> On Oct 30, 2004, at 1:50 AM, Ulrich Grude wrote:
>
> > The "Java Lang. Spec.", 2nd edition, says in chapter 3,
> > verse 10.5: "A string literal always refers to the same
> > instance (§4.3.1) of class String". I understand this as
> > "interning is mandatory", but I may be mistaken.
He's correct, really, as long as:
(a) we're talking only about *literals*, and
(b) we're in the *same classloader*.
> What is the scope of that... within a class? Or within
> classes compiled at the same time?
The language is as follows (with an example):
Test program:
package testPackage;
class Test {
public static void main(String[] args) {
String hello = "Hello", lo = "lo";
System.out.print((hello == "Hello") + " ");
System.out.print((Other.hello == hello) + " ");
System.out.print((other.Other.hello == hello) + " ");
System.out.print((hello == ("Hel"+"lo")) + " ");
System.out.print((hello == ("Hel"+lo)) + " ");
System.out.println(hello == ("Hel"+lo).intern());
}
}
class Other { static String hello = "Hello"; }
and the additional compilation unit:
package other;
public class Other { static String hello = "Hello"; }
produces the output:
true true true true false true
This example illustrates six points:
* Literal strings within the same class (§8) in the same package (§7)
represent references to the same String object (§4.3.1).
* Literal strings within different classes in the same package represent
references to the same String object.
* Literal strings within different classes in different packages likewise
represent references to the same String object.
* Strings computed by constant expressions (§15.28) are computed at compile
time and then treated as if they were literals.
* Strings computed at run time are newly created and therefore distinct.
* The result of explicitly interning a computed string is the same string as
any pre-existing literal string with the same contents.
> It's a one line change in BSHLiteral... just want to make
> sure it is correct and doesn't impact performance
> negatively...
That's the crux, really, but I think correctness demands that you intern
*literal* Strings loaded by the same classloader. If performance is a
concern, then maybe an option to Interpreter to do this (to pass on to any
BshClassLoaders it creates) would be OK (this is, after all, a fairly
marginal point).
-------------------------------------------------------
This SF.Net email is sponsored by:
Sybase ASE Linux Express Edition - download now for FREE
LinuxWorld Reader's Choice Award Winner for best database on Linux.
http://ads.osdn.com/?ad_idU88&alloc_id065&op=click