Why don’t Java’s +=, -=, *=, /= compound assignment operators require casting?

As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract: A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once. An example cited from §15.26.2 […] the following code is … Read more

Proper use cases for Android UserManager.isUserAGoat()?

Android R Update: From Android R, this method always returns false. Google says that this is done “to protect goat privacy”: /** * Used to determine whether the user making this call is subject to * teleportations. * * <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can * now automatically identify goats using advanced goat recognition … Read more

How do I generate random integers within a specific range in Java?

In Java 1.7 or later, the standard way to do this is as follows: import java.util.concurrent.ThreadLocalRandom; // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1); See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize … Read more