Note to Myself: String Concatenation

In the effort of trying to make my java code NOT look like it was written 10 years ago, here’s another note to myself.

Use String.format for concatenating strings, especially when concatenating strings within strings.

In other words…

Do less of this:

String className = "RandomNumberUltimateClassFactory";
int lineNumber = 42;
System.out.println("Class name, "
     + className
     + ", has thrown an exception on line "
     + lineNumber + ".");

And more of this:

String className = "RandomNumberUltimateClassFactory";
int lineNumber = 42;
System.out.println(String.format(
     "Class name, %s, has thrown an exception on line %d.",
     className, lineNumber));
Advertisements
This entry was posted in it makes your code look old, java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s