General Notes

String is a sneaky member of the Java standard library:

  1. Instances can be created as literals (without a constructor). For example, a new String s can be created by writing:
    String s = "Foo!";
    
    rather than using a constructor, as in:
    String s = new String("Foo!");
    

    Readers will note the recursive nature of the last example, as the constructor's argument ("Foo!") is itself a string literal. In most implementations of String, calling new String(String s) will copy the parameter String's implementing character array using native array copy methods, making sure that the array isn't longer than the stored String.

  2. The '+' and '+=' operators are overloaded for String concatenation, e.g.

    String s = "Foo!" + "Bar!";
    // s == "Foo!Bar!"
    
    s += "Baz!";
    // s == "Foo!Bar!Baz!"
    

    The fact that operator overloading is available (in a limited fashion) for use with the String class but not in user-defined classes is often cited as a reason why Java sucks.

Comparing With String Literals

When comparing String variables to String literals, many Java novices munge together something like this:

String foo = getARandomStringFromElsewhere();

if (foo.equals("Foo!")) {
    // do something
}

"Ah," you say, "But foo could be null!"

The next iteration in the novice's journey usually looks a bit like this:

if (foo != null && foo.equals("Foo!")) {
    // do something
}

This will work, but exceptionally lazy typists (like myself) object on moral (read: keystroke count) grounds. One of two approaches will make the world Safe for DemocracyTM:

  1. Compare your String to a static variable you've stashed somewhere. Either a public static final in an abstract class or a simple String in an interface will work. I'm partial to the interface approach, myself. Your comparision might look like this:
    if (IConstants.FooConst.equals(foo)) { ... }
    
  2. Or you can be weird. String literals in Java ("Foo!" is a String literal) are perfectly valid instances of java.lang.String, so:
    if("Foo!".equals(foo)) { ... }
    
    will work fine.

Log in or registerto write something here or to contact authors.