Java Programmer Gold SE 8 Qualification Summary (for those who are familiar with Java)

Purpose of the article

We have summarized the contents of the Java Programmer Gold SE 8 exam. It's for niche people who have been doing Java for a long time but don't know much about SE8.

How did you write this article?

The other day I took and passed the Java SE 8 Programmer II (1Z0-809) and got the Oracle Certified Java Programmer, Gold SE 8. I acquired it once when I was in Java2, but it was clearly different from the knowledge level required by the world today, so I decided to study again in the sense of updating my knowledge. Knowledge of SE8 is becoming essential even in Android development. When I take the test, I have a summary of the test range, but I can't stand to store it as it is when the test is over, so I decided to leave it in the form of an article. I would be very happy if it would be of benefit to anyone.

Summary of points

Java basics

Numeric literal prefix

The prefix added to the beginning of the number determines the base number.

Timing to initialize final variable

Instance variables with the final qualifier must be initialized in the constructor

Initialization order by initializer and constructor

Processes related to object initialization are executed in the following order

  1. static initializer When loading a class
  2. Instance initializer When creating an instance, before executing the constructor Declaring a variable does not execute it. Requires instantiation
  3. Constructor

Enumeration value inheritance and interface implementation

Notes on enumerated values

enum Direction {
    North(0), South(1);

    //If you do not declare final, you can change this value
    int index;
    private Direction(int index) { this.index = index; }
}

//Example of changing the index field of Direction
Direction d = Direction.North;
System.out.println(d.index);    // 0
d.index = 10;
System.out.println(d.index);    // 10

hashCode () and equals ()

  1. Check if the hash values are the same
  2. Compare only those with the same hash value with ʻequals () `

Interface method

interface Sample {
    // "public abstract"Compiles with or without
    public abstract void execute();
}

interface A { default void execute() { System.out.println("A"); } }
interface B { default void execute() { System.out.println("B"); } }
interface C extends A, B {
    //Uncommenting this will eliminate the compilation error
    // default void execute() { System.out.println("C"); }
}

Conditions for the override to hold

  1. Method name
  2. Argument type
  3. Argument order

Method local class

Lambda expression

  1. Argument data type can be omitted
  2. If there is one argument, "()" can be omitted
  3. If there is one expression on the right side, "{}" can be omitted regardless of whether there is a return value from the right side.
  4. If there is one expression on the right side and a return value is returned, return can be omitted.

Functional interface

Function related

Interface Method Return type
Function<T, R> apply(T t) R
UnaryOperator<T> apply(T t) T
BinaryOperator<T> apply(T t1, T t2) T
BiFunction<T, U, R> apply(T t, U u) R

Consumer related

Interface Method Return type
Consumer<T> accept(T t) void
BiConsumer<T, U> accept(T t, U u) void

Predicate related

Interface Method Return type
Predicate<T> test(T t) boolean
BiPredicate<T, U> test(T t, U u) boolean

Supplier

Interface Method Return type
Supplier<T> get() T

Functional interface that accepts primitive types

Data type Function Consumer Predicate Supplier UnaryOperator BinaryOperator
int IntFunction<R> IntConsumer IntPredicate IntSupplier IntUnaryOperator IntBinaryOperator
long LongFunction<R> LongConsumer LongPredicate LongSupplier LongUnaryOperator LongBinaryOperator
double DoubleFunction<R> DoubleConsumer DoublePredicate DoubleSupplier DoubleUnaryOperator DoubleBinaryOperator
boolean - - - BooleanSupplier - -

Functional interface that returns a primitive type

Interface name Method Description
ToIntFunction<T> applyAsInt(T t) Returns an int from a T-type value
ToIntBiFunction<T, U> applyAsInt(T t, U u) Returns an int from T and U values
ToLongFunction<T> applyAsLong(T t) Returns long from a T-type value
ToLongBiFunction<T, U> applyAsLong(T t, U u) Returns long from T and U values
ToDoubleFunction<T> applyAsDouble(T t) Returns a double from a T-type value
ToDoubleBiFunction<T, U> applyAsDouble(T t, U u) Returns double from T and U values

Method reference

collection

Arrays#asList

The nature of the collection class and how to distinguish it

The nature of the Queue interface

Deque interface properties

Generics

Generics and type parameters

Wildcard

Where a compile error occurs when using wildcards for type parameters

Comparable and Comparator

Comparable interface

Comparator interface

Stream API

Generate a stream with a finite number of elements

Generate a stream with an infinite number of elements

Both methods of java.util.stream.Stream

Stream termination operation

Stream # reduce return value

Stream # reduce is a method for aggregating the contents of Stream. In the method that sets the initial value in the first argument, the return value is not ʻOptional`

Termination operation with an optional return value

Create an instance of Optional

Optional # ifPresent and Optional # isPresent

  1. ʻisPresent () `… Determines the presence or absence of a value
  2. ʻifPresent (Consumer)… Execute Consumer` if there is a value

There are multiple methods for retrieving a value from Optional

The method to get the value from ʻOptional `is below. If a value exists, that value is obtained, but if it does not exist, the behavior is different.

Optional types specific to a particular data type

ʻThe method for retrieving the related class and value of Optional ` is as follows

Type conversion between Stream and XXXStream

Stream # collect () method and Collector class

exception

Error、Exception、 RuntimeException

Order to catch exceptions

Exception multi-catch

Exception rethrow

//In SE7 and later, you may catch two exceptions together.
//It is not Exception but IllegalAccessException and ArighmeticException that are thrown from execute
private void execute(int number) throws IllegalAccessException, ArithmeticException {
    try {
        switch (number) {
            case 1:
                throw new IllegalAccessException();
            case 2:
                throw new ArithmeticException();
            default:
                System.out.println("No exception");
        }
    } catch (Exception e) {
        throw e;
    }
}

Override method to throw exception

try ~ with ~ resources statement

  1. try block
  2. Close resources in the reverse order of declaration (the code below closes in order from N to 1)
  3. catch block
  4. finally block
// (1) ->Close in order from Resource N to 1() -> (2) -> (3)Execute in the order of
try (Resource1; Resource2; ...; ResourceN) {
    (1)
} catch (Exception e) {
    (2)

    // getSuppressed()You can take an array of Throwable with
    for (Throwable th : e.getSuppressed()) { ... }
} finally {
    (3)
}

Assertions and how to use them

Date and Time API

Class list

  1. LocalDate… Date
  2. LocalTime… Time
  3. LocalDateTime… Date + time
  4. ʻOffsetTime`… Time including the difference from UTC / GMT in “+ hh: mm”
  5. ʻOffsetDateTime`… Date & time including the difference from UTC / GMT in “+ hh: mm”
  6. ZonedDateTime… Date + time including the difference from UTC / GMT in time zone ID

Enumeration list

  1. Month: Represents the month JANUARY, FEBRUARY, MARCH, …, DECEMBER
  2. DayOfWeek: Represents the day of the week SUNDAY, MONDAY, TUESDAY, …, SATURDAY

Instantiation of LocalDate / LocalTime / LocalDateTime

  1. now()
  2. of(year, month, dayOfMonth, ...)
    Create an instance with a value that can be handled by each class as an argument You can set the argument month to the Month enumerated value instead of an integer. Only LocalDateTime has an overload that takes LocalDate and LocalTime as arguments. It may take year, month, day, hour, minute, second, millisecond as arguments
  3. parse(String)parse(String, DateTimeFormatter)
    Create an instance from a string If you use DateTimeFormatter together, you can use any format string.

LocalDate # of and LocalTime # of overloads

  1. The second argument is int
  2. The second argument is the Month enumeration value
  1. Hours only
  2. Specify seconds in addition to hours and minutes
  3. Specify seconds and nanoseconds in addition to hours and minutes

java.time.format.DateTimeFormatter

  1. ofPattern(String)
    Specify format pattern
  2. ofLocalizedDate(FormatStyle)
    Specify the date format method
  3. ofLocalizedTime(FormatStyle)
    Specify the time format method
  4. ofLocalizedDateTime(FormatStyle)
    Specify the date and time format
  5. ofLocalizedDateTime(FormatStyle, FormatStyle)
    Specify the date and time format method separately for date and time
  6. Static predefined formatter BASIC_ISO_DATE etc.

java.time.format.FormatStyle

There are 4 types of FormatStyle

LocalDateTime dateTime = LocalDateTime.of(2020, 8, 14, 9, 54, 30);
ZonedDateTime zDateTime =
    ZonedDateTime.of(dateTime, ZoneId.systemDefault());

// FormatStyle.FULL… “August 14, 2020 9:54:30”
println(fmt1.format(zDateTime));

// FormatStyle.LONG … 『2020/08/14 9:54:30 JST』
println(fmt2.format(zDateTime));

// FormatStyle.MEDIUM … 『2020/08/14 9:54:30』
println(fmt3.format(dateTime));

// FormatStyle.SHORT … 『20/08/14 9:54』
println(fmt4.format(dateTime));

Date and Time API format string

Date / time addition / subtraction

Add ... plus (Temporal Amount amount ToAdd) Subtraction… minus (Temporal Amount amount To Subtract)

Daylight saving time

Period: Date

//Addition of years using Period
LocalDateTime dt = LocalDateTime.now();
Period p = Period.ofYears(1);

//This is equivalent to the following two lines (method chain is meaningless)
// Period p1 = Period.ofDays(1);
// Period p = Period.ofYears(2);
Period p = Period.ofDays(1).ofYears(2);

Duration: hours, minutes and seconds

java.time.Instant

Input / output

Reading using java.io.Reader

Writing using java.io.Writer

Read position control of java.io.Reader and java.io.InputStream

//The contents of the file are"01234567"
//The execution result is"025676"
try (BufferedReader br =
        new BufferedReader(new FileReader("sample.txt"))) {
    for (int i = 0; i < 3; i++) {
        br.skip(i); //Skip i bytes
        System.out.print((char)br.read());
    }
    br.mark(3); //present location("6"INDEX with=5 places)Mark
    System.out.print(br.readLine());
    br.reset(); //Marked position(INDEX=5 places)Back to
    System.out.println((char)br.read());
} catch (IOException e) {
    e.printStackTrace();
}

java.io.PrintWriter

java.io.Console

Notes on serialization

  1. static variable
  2. Transient declared member variable
  1. It is Serializable itself, but the superclass is not Serializable
  2. The superclass has a no-argument constructor
  3. The subclass constructor does not explicitly call the parent constructor

NIO2

java.nio.file.Path (feature)

java.nio.file.Path (method)

String sp1 = "/tmp/work1/sample.txt";
String sp2 = "/tmp/work2/dummy.txt";
Path p1 = Paths.get(sp1);
Path p2 = FileSystems.getDefault().getPath(sp2);
println(p1.getRoot());      // "/"
println(p1.subpath(0, 2));  // "tmp/work1"
println(p1.relativize(p2)); // "../../work2/dummy.txt"
println(p1.getName(0));     // "tmp"

Path rp = p1.resolve("../dat");
println(rp);                // "/tmp/work1/sample.txt/../dat"
println(rp.normalize());    // "/tmp/work1/dat"

//For Windows
Path wp = Paths.get("C:¥¥temp¥¥work¥¥sample.txt");
println(wp.getRoot());      // "C:¥"

java.nio.file.FileSystem

Provides an interface to the file system. Get with the static method of the FileSystems class

java.nio.file.Files (file operation)

The following are all static methods

  1. The contents of the directory are not copied
  2. When a file with the same name exists in the copy destination, an exception is made if there is no overwrite specification in CopyOption.
  3. The default behavior is that copying a file does not copy attributes
  4. If you copy a symbolic link without specifying CopyOption, the entity indicated by the link will be copied.
  5. The path given to the argument is not the place to copy / move, but the path after moving / copying

java.nio.file.Files (directory manipulation)

The following are all static methods

java.nio.file.Files (search directory)

The following are all static methods

java.nio.file.attribute

A package that contains classes that represent the attributes of a file (creation time, access time, owner, etc.). Also includes an attribute view interface that shows a set of attribute information

Parallel processing

Functions provided by the concurrency utility

  1. Thread pool Thread creation and reuse
  2. Parallel collection A collection that can properly handle parallel access from multiple threads
  3. Atomic variables Implemented a series of indivisible operations to prevent value inconsistencies due to concurrent access (same as synchronized)
  4. Counting semaphore You can freely set the number of threads that can access a finite number of resources in parallel.

Parallel collection

java.util.concurrent.ConcurrentMap interface

//The contents of the map[1, "One"], [2, "Two.2"], [3, "Three"]
Map<Integer, String> map = new ConcurrentHashMap<>();
map.put(1, "One");
map.putIfAbsent(1, "One.2"); //Do not add(KEY=1 element already exists)
map.put(2, "Two");
map.replace(2, "Two.2");           //Replacement
map.replace(2, "Two.22", "Two.3"); //Do not replace(The second argument is different from the existing value)
map.put(3, "Three");     //Delete
map.remove(3, "Three2"); //Do not delete(The second argument is different from the existing value)

java.util.concurrent.CopyOnWriteArrayList class

java.util.concurrent.CyclicBarrier class

//There are 3 threads for 2 barriers, so
// "wait wait wait finish finish"And the process stops
ExecutorService service = Executors.newCachedThreadPool();
CyclicBarrier barrier = new CyclicBarrier(2);
for (int i = 0; i < 3; i++) {
    service.execute(() -> {
        try {
            System.out.print("wait ");
            barrier.await();
            System.out.println("finish ");
        } catch (BarrierBrokenException | InterruptedException ignore) {
        }
    });
}
service.shutdown();

ExecutorService inheritance relationship

Executors methods and corresponding ExecutorService specifications

ExecutorService#execute

ExecutorService#submit

Runnable and Callable

java.util.concurrent.Future interface

Parallel stream

//Parallel stream generation
Arrays.asList(1, 2, 3).parallelStream().forEach(System.out::println);

//Generate a parallel stream from a sequential stream
Stream.of("a", "b", "c").parallel().forEach(System.out::println);

//Generate sequential stream from parallel stream
Arrays.asList("A", "B", "C").parallelStream().sequential().forEach(System.out::println);

Fork / Join framework

Atomic variables

JDBC

Execute query

  1. Get Connection withDriverManager # getConnection (url, id, pass)
  2. Get Statement withConnection # createStatement ()
  3. Get ResultSet withStatement # executeQuery (sql)
  4. Extract the result of the query from ResultSet

Proper use of methods in Statement

Acquisition and properties of ResultSet

ResultSet scrolling method

Updatable ResultSet

Localization and format

Get java.util.Locale object

  1. Locale#getDefault()
    Java runtime environment locale
  2. new Locale(String)
    The argument is "language code"
  3. new Loacle(String, String)
    The argument is "language code, country code"
  4. new Loacle(String, String, String)
    The argument is "language code, country code, variant"
  5. Set the appropriate value for Locale.Builder generated by new and generate it withbuild ()

java.util.Properties

java.util.ListResourceBundle

  1. Define a public class that inherits ListResourceBundle Override public Object [] [] getContents () The fully qualified name (package name + class name) of this class will be the base name, and this class will be for the default locale. Example: Class name is "MyResource"
  2. Define a class for a locale different from 1 by inheriting ListResourceBundle The naming rule is ** "base name_language code_country code" ** Example: The class name for the English locale will be "MyResource_en_US"
  3. Get the ListResourceBundle object withResourceBundle # getBundle (base name [, locale])
  4. Get the value with ResourceBundle # getXXXXX (key string)

java.util.PropertyResourceBundle

  1. Create a properties file for the default locale
  1. Create a file for a locale different from 1
  1. Get the PropertyResourceBundle object withResourceBundle # getBundle (base name [, locale])
  1. Use the following method to retrieve the value. there is no getInt

Priority of resource bundles used

  1. Language code and country code match
  2. Language code matches
  3. Match default locale

Format numbers using NumberFormat

Change log

Recommended Posts

Java Programmer Gold SE 8 Qualification Summary (for those who are familiar with Java)
[Certified Java Programmer, Gold SE 11] Impressions, good points, bad points for those who are studying from now on
[Qualification Exam] (Java SE8 Gold) Learning Review & Summary
Oracle Certified Java Programmer, Gold SE 8
Diary for Java SE 8 Silver qualification
A note for those who live with JMockit
[Qualification Exam] Java SE 8 Silver Learning Method Summary
java se 8 programmer Ⅰ memo
[For those who create portfolios] Search function created with ransack
Stackdriver Logging logs are misaligned in GAE SE for Java 8
How to change arguments in [Java] method (for those who are confused by passing by value, passing by reference, passing by reference)
I took Java SE8 Gold.
[Java] Summary of for statements
[PHP] For those who are worried about weight ~ Private special case ~
[For those who create portfolios] How to use binding.pry with Docker