Skip to content

Tag: syntax

Shorthand class constructor member initialisation

Writing simple constructors in Java is pretty verbose. For each field that needs to be initialised you need to write the variable name four times, e.g. like so: Is there a shorthand for that like e.g. in Kotlin? This question was asked before here: Shorthand class constructor field initialisation But that was…

Nested if-else behaviour without braces

Consider the following unformatted nested if-else Java code My question is: according to the Java language specifications, to what if does the else branch apply? By hand-reformatting and adding braces, which of these two is correct? Block 1: Block 2: Answer From the Java Language Specification: The Java progr…

Java switch statement multiple cases

Just trying to figure out how to use many multiple cases for a Java switch statement. Here’s an example of what I’m trying to do: versus having to do: Any ideas if this possible, or what a good alternative is? Answer Sadly, it’s not possible in Java. You’ll have to resort to using if-e…