Strings and Equality
From Processing
The String class provided by the Java standard libraries is invaluable, but before using it, there are a few things you should be aware of.
Contents |
In Pursuit of Equality and Identity
Put briefly, if you want to compare two Strings you should always use:
and never:
if (name == BEST_NAME) {}
because the latter just checks whether they are the same String object, which can be false even if two objects contain the same text.
More information in the following threads:
Immutability And Using StringBuffers Instead
One of the properties of a Java String is that it is immutable. This means that once it's been created with some text, that text can never be changed without making a new String. So when you do something like this:
String sentence = "Hello, "; sentence += name + "!";
The original object containing "Hello, " is thrown away and an entirely new String object is created instead. It is OK in the given example but if you're doing a lot of appending (eg. in a loop), creating all these new String objects can get really slow.
StringBuffer was designed specifically for doing lots of appending. Its append() method is fast, and when you want the final result you can simply use toString().
StringBuffer sb = new StringBuffer("Hello, "); sb.append(name); sb.append("!"); String myFinalString = sb.toString();
For more advanced users: if you know StringBuffer will only be modified in one thread (quite likely for the vast majority of Processing apps) then you can swap it out for StringBuilder, which is even faster. It has the same syntax.
Some Of My Characters Are Escaping!
Related Links
Messing with the String store using Reflection - anything in this article is not recommended!