The Official BLOG and Wiki for CustomMode.com
[ start | index | login ]
start > Java Tricks

Java Tricks

Created by dmitry. Last edited by dmitry, 4 years and 22 days ago. Viewed 356 times. #3
[diff] [history] [edit] [rdf]
labels
attachments

String concatinations

Even thouhg Java comes with the "+" (plus operator) overloaded for Strings only to make it more convinient for developers to use, this convinience feature comes with hidden cost. Strings are immutable. It means that every time we write:
String a = "string a";
String b = "string b";
String c = a + b;
it will create 3 Java objects. This does not seem like a big problem. Now try to imagine some log messages that are composed from different Strings:
System.out.println( "user account:" 
                       + userAccount.id 
                       + " is emabled since:" 
                       + userAccount.activationDate")
and if this portion of the code is executed by councurent threads under havy load it might quickly become a botleneck.


Comparing a String object to a contant with equals

There are two ways of comparing a string object with the string constant.

The first way is straigh forward and the most obvious:

String myString = "genericString";
if(myString.equals("genericString")) {
   System.out.println("great");
}

The same thing can be accomplished better with following code:

String myString = "genericString";
if("genericString".equals(myString)) {
   System.out.println("great");
}

Since "genericString" is a Java Object, the java.lang.Object methods can be called directly on it. It's better because it's more readable and more error prone. If for some reason myString object is null the first example will throw a NullPointerException wich will have to be handled. The second example will just return false.

no comments | post comment
custommode.com | ©2000-2005
webmaster at custommode dot com