Tidbits

I have lots of random thoughts--some of which could warrant a full article (which may come in the future) and others which can remain short and sweet.

Underscores in Numeric Literals (Java, JavaScript)

Did you know you can put underscores in numeric literals in Java for readability?

final int MILLISECONDS_PER_HOUR = 3_600_000;

Now you do. Here's Java's documentation. You're welcome.

Oh, yeah. It's available in JavaScript as well (reference).

final (in Java)

I used to think final was just for constants (final int MILLISECONDS_PER_HOUR = 3_600_000;). Nope. Setting aside the use of final for classes and methods, the final modifier for variables simply means the variable must be assigned a value exactly once. No more. No less. In the MILLISECONDS_PER_HOUR example, it is a constant (all final primitives are constants); but consider a different example: final Set<Integer> myFavoriteNumbers = new HashSet<>(); Is this Set destined to be empty forever? Nope. We can call myFavoriteNumbers.add(13); or myFavoriteNumbers.remove(1); What we cannot do is later reassign myFavoriteNumbers to something else (like myFavoriteNumbers = someOtherSet; // Nope--won't compile).

So, when it comes to variables, final prevents reassignment; it doesn't prevent mutation of Objects stored in a final variable.

If you're familiar with JavaScript, think of a Java variable with the final modifier as a JavaScript const and a Java variable without the final modifier as a JavaScript let.

Finally (pun intended), use it! Reassigning variables is often (but not always) bad practice. I personally use final for every variable by default and only remove the modifier if I need to reassign the variable for a legitimate reason. This may annoy some people, because it seems like it adds unnecessary typing of 6 characters (including the space); but I've become used to it and don't see myself going back.