I’m preparing the OCAJP: Oracle Certified Associate Java SE 8 Programmer. Here’re something interesting that I learned from the study guide, chapter 1 and chapter 2. They’re rarely used in our daily mission, but I just wrote them down for fun.
Numeric Literals
Numeric literals is a feature added in Java 7. You can have underscores in numbers to make them easier to read. You can add underscores anywhere except at the beginning of a literal, the end of a literal, right before a decimal, or right after a decimal point.
Numeric Promotion
Java may do things that seem unusual to you. In numeric promotion, for example,
smaller data types, namely byte
, short
, and char
, are first promoted to
int
any time they’re used with a Java binary arithmetic operator, even if
neither of the operands is int
.
Optional Label Parameter
The optional label parameter allows us to break out of a higher level outer loop. For example:
Implicit Casting in Compound Assignment Operators
Besides the simple assignment operator =
, there’re also numerous compound
assignment operators, e.g. +=
and -=
. Compound operators are useful for
more than just shorthand—they can also save us from having to explicitly cast a
value. For example, consider the following example, in which the last line will
not compile due to the result being promoted to a long
and assigned to an
int
variable. This could be fixed using the compound assignment operator.
Precedence of Importing
Given the following classes, which of the following snippets can be inserted in
place of INSERT IMPORTS HERE
and have the code compile? (Choose all that
apply)
package aquarium;
public class Water {
boolean salty = false;
}
package aquarium.jellies;
public class Water {
boolea salty = true;
}
package employee;
// INSERT IMPORTS HERE
public class WaterFiller {
Water water;
}
import aquarium.*;
import aquarium.Water; import aquarium.jellies.*;
import aquarium.*; import aquarium.jellies.Water;
import aquarium.*; import aquarium.jellies.*;
import aquarium.Water; import aquarium.jellies.Water;
- None of these imports can make the code compile.
The answer is 123. Option 1 is correct because it imports all the classes in the
aquarium
package including aquarium.Water
. Option 2 and 3 are correct
because they import Water
by classname. This is called single-type-import
declaration (JLS §7.5.1). Since importing by classname takes
precedence over wildcards, these statements compile. More precisely, type-import-on-demand
declarations are shadowed by the single-type-import declaration. Option 4
defines two type-import-on-demand declarations, both contain type Water
:
aquarium.Water
and aquarium.jellies.Water
. This is ambiguous so it does not
compile. Similar for option 5.