Formatting and Styling Strings (Java/Android)
So, let’s say you’re reading the Android document on formatting and styling strings and come across the line
Hello, %1$s! You have %2$d new messages.
The document explains that %1$s and %2$d are a string and decimal value, respectively. The next chunk of code is
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
Now, how does this relate? Well, the 1$ and 2$ means first and second parameter, respectively. So in this case %1$s
is replaced with the variable username
and %2$d
is replaced with mailCount
.
Why should you construct strings this way instead of constructing a string with the plus sign? Well, either way is valid, but this is just the “old” way of constructing strings. There was a time where using the plus sign to construct strings required converting decimal numbers to a string or else the compiler would complain. It was an obnoxious intermediate step. With Java though, the plus sign is smart enough to change the datatype of a decimal to a string if the rest of the line contains strings. To make a string (that contains a number) to a decimal, just add “+ 0” to the end and Java will take care of it. Pretty slick, right?