Using underscores in numeric literals
I traced the source code of OkHttp library and stumbled across this:
int connectTimeout = 10_000; // 10 seconds
int readTimeout = 10_000;
int writeTimeout = 10_000;
There is an underscore character between digits in a numerical literal. It’s useful when we need to convert seconds into milliseconds. It amazed me at the first. Then I found the specification of this rule:
More examples are:
It makes code more readable and clear without having to write lots of ‘0’.
In some cases, we not only need to convert seconds into milliseconds, but days into milliseconds or into seconds. That’s TimeUnit class coming for help.
TimeUnit class
An original way to convert 2 days into milliseconds is:
long twoDaysInMillis = 2 * 24 * 60 * 60 * 1000;
It’s a little bit hard to read and may be error prone, an elegant way to convert it is like:
long twoDaysInMillis = TimeUnit.DAYS.toMillis(2); // =172800000
It’s more readable, isn’t it? There are more utility methods to convert across units:
long twoDaysInSeconds = TimeUnit.DAYS.toSeconds(2); // =172800
long millisToDays = TimeUnit.MILLISECONDS.toDays(172800000); // =2
There are two classes naming TimeUnit, make sure the java.util.concurrent.TimeUnit one is imported. More detail of TimeUnit class could be found: