var test = "Hello World!";
In Java 10+, the above snippet compiles, and test
is inferred to be a String
at compile-time.
However, we can use the conditional (ternary) operator to return different types, such as:
var test = new Random().nextBoolean() ? "Hello World!" : 123;
If we were to print test.getClass()
at runtime, it would output either:
- class java.lang.String
- class java.lang.Integer
This makes sense, but what would the type of test
be at compile-time? Would it be Object
, or something else?