Today, I want to write blog post to summarize all the important review notes for Oracle Certification Associate (OCA) - Java SE 8 Programmer. This post will be separated into several subjects. They’re:
- Java Basics
- Java Data Types
- Methods and Encapsulation
- Java Core APIs
- Flow control
- Inheritance
- Exception Handling
Java Basics
- Check access modifier
- Check non-access modifier
- Check return type
- Check method type (constructor, getter / setter)
- Check parameter types
Java Packages
- An
import
statement allows to import a class or interface. - An
import
statement allows to import a package using wildcard*
. - An
import static
statement allows to import a static method. - An
import static
statement allows to import all the static methods of the target class using wildcard*
. - If a
package
statement is present, it must be the first non-commented line of code in the file.
Compilation
- If a variable declaration fails to compile, then all the following lines which use this variable will fail to compile, because variable is undefined.
- A local variable must be initialized before being used. Otherwise, Java fails to compile at those lines where this variable is used.
- A local variable is not required to be initialized if it is not used.
Java Data Types
Primitives
- Characters
char
can be concatenated, such as'a' + 'b'
. When doing so, they are considered as integer using their corresponding value in ASCII table. - Binary number starts with the prefix
0b
or0B
, e.g.0b1101
. - Octal number starts with the prefix
0
, e.g.011
. - Decimal number does not start with
0
, e.g.11
. - Hexadecimal number starts with the prefix
0x
, e.g.0xAAA
. - A literal ends with a character could be a
float
, adouble
, along
, or a hexadecimal number. - A
long
can be assigned using an integerint
, because Java knows how to widen the type. - An integer cannot be assigned as a decimal number automatically.
- Wrapper classes
Byte
,Short
,Integer
, andLong
cache objects with values in the range of-128
to127
. - Wrapper class
Character
caches objects with values0
to127
. - Wrapper class
Boolean
has 2 cached instances,Boolean.TRUE
andBoolean.FALSE
. They’re accessible directly because only two exist. Int
is not defined in the Java API, the correct wrapper class forint
isInteger
.Bool
is not defined in the Java API, the correct wrapper class forboolean
isBoolean
.
Operators
- The logical operator AND
&&
has a higher operator precedence than the operator||
.
Methods and Encapsulation
Constructor
- Initializer blocks are used to initialize the variables of anonymous classes.
- A constructor must not define any return type.
- A default constructor (a public, non-argument constructor) is generated by JVM if and only if there’s no constructor defined by user.
- A constructor does not have return type, e.g.
void
- If a subclass does not make an explicit call to a parent constructor, the
compiler attempts to compensate for this by insert a call to the default
no-argument constructor
super()
. However, this will fail if there’s no such constructor in the parent class. - Subclass must make an explicit call to the parent constructor with the
super()
command if parent does not have a no-argument constructor. - Overloaded constructors cannot be defined by just a change in the access levels.
- A constructor can call another overloaded constructor by using the keyword
this
. - A constructor cannot invoke a constructor by using its class’s name.
- If present, the call to another constructor must be the first statement in a constructor.
Interface
- Interface methods are assumed to be
public
andabstract
even if they’re not written as modifier. Therefore, a class implementing the methods of an interface must follow the same accessibility:public
. - Interface method cannot be marked
static
ordefault
if it is already markedabstract
. - A
static
method in an interface can’t be called using a reference variable. It must be called using the interface name. - Unlike an interface, if you define a
static
method in a base class, it can be accessed using either a reference variable or the class name.
Method
- Overloaded method means the method name is the same and the method parameter list is different. Anything else is allowed to vary. Remember that Java is case sensitive.
- Overloaded methods may or may not define a different return type.
- Overloaded methods may or may not define different access levels.
- Return type is not part of a method signature.
- If you try to execute a method using values that can be passed to multiple overloaded methods, in this case, the code will fail to compile.
- Java prefers the most specific overloaded signature it can find.
- Java prefers a single object over a vararg parameter.
- Java prefers an autoboxed parameter over a vararg parameter.
- The
return
statement need not be the last statement in a method, but it must be the last statement to execute in a method. - If the compiler determines that a
return
statement isn’t the last statement to execute in a method, the method will fail to compile. - If the return type of a method is
int
, the method can return a value of typebyte
. - If a
char
variable gets expanded among a list of overloaded methods, it will be expanded to its nearest type, e.g.int
instead oflong
. - If the return type of a method is
int
, the method can return a value of typebyte
.
Garbage Collection
- You can only determine which objects are eligible to be garbage collected.
- You cannot determine when a particular object will be garbage collected. The execution of a garbage collector is controlled by the JVM.
- Removing all references to an object makes the object eligible for garbage collection, but the rules of garbage collection do not guarantee when the this deletion from memory will occur.
- The method
java.lang.Object#finalize()
hasprotected
modifier. - The method
finalize
is called when the object is first attempted to be garbage collected. - The method
finalize
will not be called more than once for the same instance. - A group of instances with no external references forms an island of isolation. which is eligible for garbage collection.
- A garbage collector is a low-priority thread, and its exact execution time will depend on the OS. The OS will start this thread if it needs to claim unused space. You can only be sure how many objects are eligible for GC.
Java Core APIs
String
- All the string literals are automatically instantiated into a
String
object. - Whenever the JRE receives a new request to initialize a
String
variable using the assignment operator, it checks whether aString
object with the same value already exists in the string pool. String
objects created using the operatornew
are never placed in the string pool.- The method
substring
does not include the character at the end position.
String Builder
StringBuilder
andStringBuffer
have the same methods.StringBuilder
has a constructor without any parameter.StringBuilder
has a constructor with a customized capacity asint
.StringBuilder
has a constructor with a default capacity and an initial word asString
.StringBuilder
does not have methodtrim
.StringBuilder
does not have methodconcat
.StringBuilder#subSequence(int, int)
does not modify the content of builder, a new string is returned.
Arrays
- An array itself is an object.
- The creation of an array involves three steps: declaration of an array, allocation of an array, and initialization of array elements.
- An array is an object, so it’s allocated using the keyword
new
. - Elements of an array that store primitive data types store
0
for integer types (byte
,short
,int
,long
). - Elements of an array that store primitive data types store
0.0
for decimal types (float
,double
). - Elements of an array that store primitive data types store
false
forboolean
. - Elements of an array that store primitive data types store
/u0000
forchar
data. - A multidimensional array can be asymmetrical. it may or may not define the same number of columns for each of its rows.
- Array anonymous initializer is only allowed in the declaration.
ArrayList
ArrayList#remove(Object o)
removes the first occurrence of the specified element from this list, if it is present.- Using generics only on one side in a declaration is allowed, so
List<Integer> nums = new ArrayList();
compiles. However, this is not suggested. An unchecked warning will be issued by the compiler. - It’s not possible to remove elements from an
ArrayList
while iterating through it using afor
loop. indexOf(Object o)
returns the index of the first occurrence of the specified element in the list, or-1
if the list doesn’t contain the element.- An
ArrayList
can store any type of object. ArrayList#contains(Object)
compares value and not reference.ArrayList
has overridden the defaulttoString
method, so an empty array list prints[]
.
Date
LocalDate
instances are immutable.- All the methods that seem to manipulate
LocalDate
’s value return a copy of theLocalDate
instance on which it’s called. - The
withXX
methods return a copy ofLocalDate
’s value replacing the specified day, month, or year in it. LocalTime
stores time to nanosecond precision.LocalDate
doesn’t define aplus()
method, which accepts an integer value to be added to it. You should useplusXXX
where the expression can be days, weeks, months, years.- Cannot use a
DateTimeFormatter
to format a date object, because it has no time.
Lambda Expression
- Parentheses can be omitted ONLY if there’s one parameter and the parameter
type is not declared. So,
(String s) -> ...
ors -> ...
. - When braces are used around the body, the
return
keyword and the semicolon are required. For example,p -> { return p.getAge() < 5; }
- Lambdas work only with functional interfaces—interfaces that define exactly
one
abstract
method. - Each lambda expression has multiple optional and mandatory sections:
- Parameter type (optional)
- Parameter name (mandatory)
- Arrow (mandatory)
- Curly braces (optional)
- Keyword
return
(optional) - Lambda body (mandatory)
- The return type of the functional method
test
in the functional interfacePredicate
isboolean
. If you try to return another type, the code fails to compile. SoPredicate<String> p = (s) -> s == null ? "A" : "B";
is incorrect. - A simple lambda expression could be written in one line:
Validate v = p -> p.getAge() <= 26;
Flow control
- The braces
{}
are required for methods,try
blocks, andcatch
blocks even if there’s only one statement inside. - If there’re duplicate constant values in a
switch
statements, all the duplicate cases will raise a compile error. - The
default
case executes only of no matching values are found. In this case.
Inheritance
Interface
- All interface variables are implicitly assumed
public static final
. For these variables, they mush declare a value when they are initialized. Otherwise, the compilation fails.
Method
- The access modifier of an inherited method cannot be more restrictive than its parent.
Exception Handling
- Exceptions are divided into three categories: checked exceptions, runtime (unchecked) exceptions, and errors.
- You should not handle errors.
- If a method throws a checked exception, it must be either handled by the
method or specified in its
throws
clause. - If a method throws a runtime exception, it may include the exception in its
throws
clause. - An exception is an object of the class
java.lang.Throwable
. - When calling a method having checked exception(s), you must handle them
properly, e.g.
throws
from method or adding atry ... catch
block. - If a method declares to throw a checked exception, its body can’t throw a more general exception.
- Error is not a checked or unchecked exception.
- If the creation of an object calls itself recursively without an exit
condition, it will result a
java.lang.StackOverflowError
. For example:class MyClass { MyClass my = new MyClass(); }
. ExceptionInInitializerError
may be thrown by the JVM when astatic
initializer in your code throws aNullPointerException
.
Other notes
- Consider yourself as the Java Compiler
- Read the question carefully. Be careful about the assumption, or the given context.
- Read all the options before answer a question. Sometimes multiple choices are correct.
- Be careful about the name of variable, e.g.
s1
ands2
may be used in a mixed way to confuse you. - You cannot assume the
import
statement if the code snippet displayed starts from line 1. (No previous lines can be hidden in this case.) - Be careful about the application entry point, it must be
public static void
where the position ofpublic static
can be changed.