[Java] Java Programmer Gold SE 8 Qualification Summary (For those who are familiar with Java)

35 minute read

Article purpose

This is a summary of the contents of the Java Programmer Gold SE 8 exam. It’s for a niche of “I’ve been doing Java for a long time, but I don’t know SE8 subtly”.

The reason for writing this article

I recently passed and passed the Java SE 8 Programmer II (1Z0-809) and got the Oracle Certified Java Programmer, Gold SE 8. I got it once when I was using Java2, but it was clearly different from the knowledge level required by the world today, so I’ve re-studied it to update my knowledge. SE8 knowledge is becoming essential even in Android development. There is a compilation of the test range for the test, but I don’t want to leave it in the warehouse as soon as the test ends, so I decided to leave it in the form of an article. I would be very happy if someone could benefit me.

Summary

Java basics

Numeric literal prefix

The prefix added to the beginning of the number determines how many numbers are represented.

  • “0b”…binary number
  • “0”…octal number
  • None…decimal
  • “0x”… Hexadecimal number

timing of final variable initialization

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

Order of initialization by initializer and constructor

Processes related to object initialization are executed in the following order

  1. static initializer When class is loaded
  2. Instance initializer At instance generation, before constructor execution Just declaring a variable won’t execute it. Requires instantiation
  3. Constructor

Enumeration value inheritance and interface implementation

  • Enumeration methods name() and toString() return their own string representation
  • name() is final and cannot be overridden. toString() is possible
  • Enumeration can implement interface and define abstract method. If you do these, you need to override them with each enum value
  • If you want to get the enumeration value from a string, you can use the valueOf() method

Notes on enumerated values

  • A constructor can be defined for the enumeration value, but since instantiation by new is not allowed, adding public or protected to the constructor results in a compilation error. If you don’t add anything, it will compile but you can’t do new (compile error).
  • If you define a field without a final declaration, the value of that field can be changed at any time.
enum Direction {
    North(0), South(1);

    // You can change this value if you do not declare final
    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()

  • The following two points are the conditions for equalizing multiple objects.
    • The return value (hash value) of hashCode() is the same
    • equals() is true
  • Check for duplicates in the collection as follows. If both are established, it is regarded as the same value
    1. Check if the hash values are the same
    2. Compare only with the same hash value with equals()
  • When implementing hashCode(), implement so that a value is returned from an object with the same value.
  • The argument of equals() is Object. If the same type as the receiver is used, the override will not be established and the overload will be established. No compile error

Interface methods

  • The instance method defined in the interface may be a public abstract method. Compiles even if there is a description such as abstract
  • In a situation where default methods with the same name are defined in multiple interfaces and inheriting or implementing both, default methods conflict and a compile error occurs. However, overriding the default method on the inheriting or implementing side resolves the error
interface Sample {
    // Compiles with or without "public abstract"
    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 {
    // Uncomment this to eliminate the compilation error
    // default void execute() {System.out.println("C");}
}

Condition for overriding

  • When overriding a method, the return value must be the same as or a subclass of the superclass type
  • Method overriding does not occur unless the following match. Overload even if the order does not match
    1. Method name
    2. Argument type
    3. Argument order
  • static methods and static fields can be redefined in subclasses However, since it is “hidden” rather than overridden, you cannot call the parent static method using the super keyword.

Method local class

  • Method You can directly refer to a variable in a method from a local class, but the variable must be effectively final. Even if there is no final declaration, it will be automatically treated as final when referenced from the method local class. This is the same for lambda
  • When giving a method variable to a method local class in the constructor, it is not necessary to make it final because the original variable is not directly referenced.
  • When a method local class references a member variable of a class outside the method, that member variable may be changed.

Lambda type

  1. Data type of argument can be omitted
  2. ”()” can be omitted if there is one argument
  3. If there is one expression on the right side, “{}” can be omitted with or without a return value from the right side.
  4. If the expression on the right side is one and the return value is returned, return can be omitted.

Functional interface

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
Interface Method Return Type
Consumer<T> accept(T t) void
BiConsumer<T, U> accept(T t, U u) void
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 receives a primitive type

  • Each of int, long, and double has its own functional interface. boolean has only BooleanSupplier
  • The method names of Supplier, UnaryOperator, and BinaryOperator are as follows Rule: [Method name] As [Data type] Example: applyAsInt, getAsBoolean, etc.
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 value of type T
ToIntBiFunction<T, U> applyAsInt(T t, U u) Returns an int from T and U values
ToLongFunction<T> applyAsLong(T t) Returns a long from a value of type T
ToLongBiFunction<T, U> applyAsLong(T t, U u) Returns a long from T and U values
ToDoubleFunction<T> applyAsDouble(T t) Returns a double from a value of type T
ToDoubleBiFunction<T, U> applyAsDouble(T t, U u) Returns a double from T and U values

Method reference

  • Can only be used in a functional interface* When taking an argument, use the same format as a static method reference

Collection

Arrays#asList

  • The list generated by Arrays#asList only refers to the array given as an argument. Changes made to the original array are also reflected in the list
  • The list generated by Arrays#asList is not ** compatible with ArrayList<E>. ** Cast fails

Nature of collection class and how to identify

  • List is the order of index in principle
  • Set and Map are distinguished by class name prefix
    • Classes starting with Linked are preserved in the order of insertion
    • Classes starting with Tree are sorted by natural order. When arranged in natural order, it becomes ** number → alphabet (large) → alphabet (small) **

Nature of the Queue interface

  • There are two types of insert/delete/check methods, and the behavior when the method execution fails is different.
    • Exception occurred
      • Insert…add(E)
      • Remove… remove()
      • Inspection… get()
    • return null
      • Insert…offer(E)
      • Delete… poll()
      • Inspection… peek()
  • Cannot access element by index

Nature of the Deque interface

  • The difference from Queue is that you can insert or remove elements at the beginning or end, as the name of Double Ended Queue means.
    • Exception occurred
      • Insert…addFirst(E), push(E) / addLast(E)
      • Remove… removeFirst() / removeLast()
      • Inspection…getFirst(), pop() / getLast()
    • return null
      • Insert…offerFirst(E) / offsetLast(E)
      • Delete… pollFirst() / pollLast()
      • Inspection… peekFirst() / peekLast()
  • Same as Queue, element cannot be accessed by index
  • Extending the Queue interface in the java.util.concurrent package also has a method that allows you to set a timeout Waiting time does not always occur, waiting occurs when insert or delete is not possible
  • Null cannot be put in ArrayDeque which is an implementation of Deque

Generics

Generics and type parameters

  • When declaring a type parameter for a class, the type parameter cannot be used for the following purposes
    • static member Creating an instance or array using the * new operator
    • Type validation with instanceof
    • .class reference
  • You may or may not specify the type when using a method with type parameters applied
  • The syntax of generic type is as follows class class name <type parameter (, type parameter n)> {…}
  • When using type parameters in a class declaration, you can use the extends keyword but not the super keyword
  • The method syntax is as follows Declaration: ** return type method name (type argument name) {...}** Use: ** receiver. method name (type argument name) {...}**

Wildcard

  • The wildcard is "?" ("*" is Kotlin), not "*"
  • Wildcards cannot be used as type parameters in class declarations
  • The wildcard type is not fixed until it is executed, so using a wildcard to add the inside datatype to the specified list results in a compilation error. As an exception, the list declared with <? super XXXXX> can contain objects of the same type as XXXXX.
  • If you use a wildcard, if there is no problem as long as it can be judged from the declared contents, a compile error will not occur. If it becomes clear that the types are incompatible, you will get a compilation error

Where a compile error occurs when a wildcard is used in the type parameter

  • Using a wildcard in a type parameter results in a compilation error at where you actually add the object

Comparable and Comparator

Comparable Interface

  • belongs to the java.lang package
  • Interface to be compared with
  • The only method that should be implemented in Comparable is compareTo(T o). Returns a negative value if less than the peer, zero if equal, positive value if greater.
  • When declaring a class, the type parameter of Comparable<T> is given to the object type of compareTo.

Comparator Interface

  • belongs to the java.util package
  • Interface for comparing. Note that the comparison target is not limited to those that implement the Comparable interface.
  • The following two methods should be implemented in Comparator (equals is optional)
    • compare(T t1, T t2)
    • equals(T o)
  • compare(T t1, T t2) returns a positive value if t1 is greater than t2, zero if t1 and t2 are equal, and a negative value if t1 is less than t2

Stream API

Generate a stream with a finite number of elements

  • Collection#stream() -> Stream<E>
  • Arrays#stream(E[] array) -> Stream<E>
  • Arrays#stream(int[] array) -> IntStream
  • Arrays#stream(long[] array) -> LongStream
  • Arrays#stream(double[] array) -> DoubleStream
  • Stream#of(E… values) -> Stream<E>
  • Stream#empty() -> Stream<E>
  • IntStream#of(int… values) -> IntStream
  • LongStream#of(long… values) -> LongStream
  • DoubleStream#of(double… values) -> DoubleStream
  • IntStream#range() / IntStream#rangeClosed() -> IntStream
  • LongStream#range() / LongStream#rangeClosed() -> LongStream
  • BufferedReader#lines() -> Stream<String>
  • java.nio.file.Files#lines() -> Stream<String>

Generate a stream with an unlimited number of elements

Both are methods of java.util.stream.Stream

  • generate(Supplier<T> supplier) Create a Stream that holds the elements provided by the supplier indefinitely
  • iterate(T seed, UnaryOperator<T> f) Seed is the first element, and after that, the Stream that holds the element which multiplied the previous element by f infinitely is generated

Stream end operation

  • Only one end operation for the same stream. IllegalStateException occurs when it is performed multiple times
  • Calling an intermediate operation does nothing and does nothing unless you call a terminal operation. When the end operation is called, all processing is executed
  • In pipeline processing, the elements in the stream are sequentially processed one by one, and then the next element is processed. In other words, ** “intermediate operation of element 1 x m → end operation of element 1” ⇒ “intermediate operation of element 2 x m → end operation of element 2” ⇒ … ⇒ “intermediate operation of element n x m → end of element n” Operation”** order

Stream#reduce return value

Stream#reduce is a method to aggregate the contents of Stream. In the method that sets the initial value to the first argument, the return value is not Optional

  • reduce(BinaryOperator op) …The return value is Optional<T>
  • reduce(T initial, BinaryOperator op) …The return value is T

Terminal operation whose return value is Optional

  • The following methods have a return value of Optional
    • findAny() …The result may change each time it is executed
    • findFirst() …The same result can be obtained no matter how many times it is executed
    • min()
    • max()
    • reduce(BinaryOperator op)
  • The type of Optional depends on the type of Stream. For example findAny() is as follows
    • Stream#findAny() Optional<T>
    • IntStream#findAny()OptionalInt
    • LongStream#findAny()OptionalLong
    • DoubleStream#findAny()OptionalDouble

Create an optional instance

  • Optional#of(T value) …value cannot be null
  • Optional#ofNullable(T value) …You can put null in value
  • OptionalInt#of(int value)
  • OptionalLong#of(long value)
  • OptionalDouble#of(double value)

Optional#ifPresent and Optional#isPresent

  • There are two methods for determining whether there is a value (null or not null)
    1. isPresent() …Determine whether there is a value
    2. ifPresent(Consumer)… If there is a value, execute Consumer#### There are multiple methods to retrieve values from Optional

The method to get the value from Optional<T> is as follows. If the value exists, the value is obtained, but the behavior when it does not exist is different

  • get() NoSuchElementException if it does not exist
  • orElse(T) Returns the argument if it does not exist
  • orElseGet(Supplier<T>) Returns the value returned by Supplier if it does not exist
  • orElseThrow(Supplier<X extends Exception>) Throws the exception returned by Supplier if it does not exist

Optional types specialized for specific data types

The method for fetching the related class and value of Optional<T> is as follows

  • Optional<T>#get()
  • OptionalInt#getAsInt()
  • OptionalLong#getAsLong()
  • OptionalDouble#getAsDouble()

Stream and XXXStream type conversion

  • Conversion between the same Stream types is done with map()
  • Conversion to Stream<T> type is mapToObj()
  • Conversion to IntStream type is mapToInt()
  • Conversion to LongStream type is mapToLong()
  • Conversion to DoubleStream type is mapToDouble()

Stream#collect() method and Collector class

  • collect() is a method that collects the elements in Stream to get one object.
  • The Collectors class provides a customizable implementation of the Collector interface Due to its nature, it plays a role with some methods of the Stream class.

Exception

Error, Exception, RuntimeException

  • All are subclasses of Throwable and belong to the java.lang package
  • Error and Exception are subclasses of Throwable
  • RuntimeException is a subclass of Exception (a grandchild of Throwable)
  • The checked exceptions that require try ~ catch are only the subclasses of Exception other than RuntimeException.

Order to catch exceptions

  • Exceptions must be caught in order from subclass
  • Catching superclass before subclass causes compile error *Not a runtime error

Multi catch of exception

  • Compile error when catching multiple inherited exceptions together
  • Exception object when multi catch is implicitly treated as final and cannot be reassigned If it is not multi catch, it is not treated as final

exception rethrow

  • If one method catches and rethrows multiple types of exception objects, the exceptions taken by the throws and catch methods do not have to match.
  • Picking up parent classes of all possible exceptions in catch and throwing them as they are
// In SE7 and later, you may catch two exceptions at once
// IllegalAccessException and ArighmeticException are thrown from execute instead of Exception
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;
    }
}

Overriding the method that throws an exception

  • When a method with a throws declaration is overridden in a subclass, whether or not to declare throws in the overridden method is free.
  • The exception in declaring throws in the overridden method must be the same as the original method or a subclass of it.
  • RuntimeException and its subclasses can be unconditionally specified in throws. However, since it is an unchecked exception, it will compile without catching it at the caller.

try ~ with ~ resources statement

  • Can be used as a single try only in try ~ with ~ resources statement
  • The resource used must implement java.lang.AutoCloseable or its sub-interface java.io.Closeable.
  • Both AutoCloseable and Closeable have a throws declaration in close(), so a compilation error occurs if you do not catch an exception, whether you use it for a resource or in a try.
    • AutoCloseable#close() throws Exception
    • Closeable#close() throws IOException
  • If an exception occurs in Close() of AutoCloseable or Closeable, it is caught by catch.
  • If both the try block and the closing of the resource raise an exception, the exception raised by close() is stored as an array of Throwable in the exception object that was caught as a suppressed exception, and getSuppressed( ) can be obtained
  • The execution order when an exception occurs in the try ~ with ~ resources statement is as follows
    1. try block
    2. Close the resources in the reverse order in which they are declared (in the code below, the resources are closed in order from N to 1)
    3. catch block
    4. The finally block
// (1) -> execute from ResourceN in order of 1 and close() -> (2) -> (3)
try (Resource1; Resource2; ...; ResourceN) {
    (1)
} catch (Exception e) {
    (2)

    // getSuppressed() can take a Throwable array
    for (Throwable th :e.getSuppressed()) {...}
} finally {
    (3)
}

Assertions and how to use them

  • Assertion is a function that throws AssertionError when false is detected in the assert statement. The syntax is as follows. assert boolean expression: error message;
  • Boolean expressions may or may not be enclosed in parentheses
  • Error message can be omitted
  • Assertions are disabled by default. AssertError is not thrown unless you explicitly specify “-ea” option (short for “enable assertion”?) in java command
  • To explicitly disable it, specify “-da” option (abbreviation for “disable assertion”?) in java command.
  • If you want to specify the target of assertion, specify the target of assertion (non-target if -da) as a colon-separated with java -ea: [class name].

Date and Time API

Class list

  1. LocalDate …Date
  2. LocalTime …Time
  3. LocalDateTime …Date + time
  4. OffsetTime …Time that includes the difference from UTC/GMT as “+hh:mm”
  5. OffsetDateTime …Date and time including the difference from UTC/GMT as “+hh:mm”
  6. ZonedDateTime …Date + time including the time zone ID including the difference from UTC/GMT
  • Implements all Temporal interfaces. Furthermore, its super interface is TemporalAccessor
  • The difference between “Local ~”, “Offset ~” and “Zoned ~” is the difference in the method of expressing the same date and time.
  • Can be converted to each with LocalDateTime#toLocalDate() and LocalDateTime#toLocalTime()
  • There are two methods that can get the month
    • getMonth() …get with Month enumeration value
    • getMonthValue() …get as int value

Enumerated type 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 by using the value that each class can handle as an argument It is OK to set Month enumeration value instead of integer for argument month. Only LocalDateTime has an overload that takes LocalDate and LocalTime as arguments. May take year, month, day, hour, minute, second, millisecond as argument
  3. parse(String), parse(String, DateTimeFormatter) Create instance from string If you also use DateTimeFormatter, you can use any format string.

LocalDate#of and LocalTime#of overloads

  • LocalDate#of has two overloaded methods. Both specify the date, but other differences are as follows
    1. The second argument is int
    2. The second argument is a Month enumerated value* LocalTime#of has three overloaded methods, all of which specify the time and minute, but the other differences are as follows.
    3. Hours and minutes only
    4. Specify seconds in addition to hours and minutes
    5. Specify seconds and nanoseconds in addition to hours and minutes

java.time.format.DateTimeFormatter

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

java.time.format.FormatStyle

There are 4 types of FormatStyle

  • FormatStyle.FULL Full format including time zone. Exception at runtime when applied to LocalDateTime which does not have zone information
  • FormatStyle.LONG A brief format that includes the time zone. Exception at runtime when applied to LocalDateTime which does not have zone information
  • FormatStyle.MEDIUM Concise format without time zone
  • FormatStyle.SHORT Simple date and time format without time zone
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

  • “y”… year
  • “M” …Month (capital letter)
  • “d”… day
  • “H” …hour (capital letter)
  • “m” … minutes
  • ”s”… seconds
  • “S” …milliseconds (uppercase)
  • “n”…nanosecond

Addition/subtraction of date/time

Addition… plus(TemporalAmount amountToAdd) Subtraction…minus(TemporalAmount amountToSubtract)

  • Period and Duration implement the TemporalAmount interface
  • Addition and subtraction can be performed on individual fields such as plusYears and plusWeeks, but when handling multiple fields together, call plus with Period and Duration as arguments.

Daylight saving time

  • The start date (advance time) and end date (return time) of daylight saving time differ in the same area every year. However, the time is constant at 02:00
  • Once applied, the offset will decrease by 1 hour and the time will advance by 1 hour One hour starts from 02:00, so 1 minute after 01:59 will be 03:00 1 hour instead of 2 hours, with 01:00 and 03:00 intervals on the start date
  • When the application is completed, the offset increases by 1 hour and the time returns by 1 hour. 1 hour back from 02:00, so 1 minute after 01:59 will be 01:00

Period: Date

  • Period expression which is toString() becomes “P00Y00M00D” The first “P” is an acronym for “Period”
  • There are several ways to create an instance of Period.
    • Diff two LocalDate or LocalDateTime with between method
    • Generated by ofXXXXX methods such as ofYears(1). However, method chain is not possible
  • Period can be added/subtracted by year, month, day and week The method of addition and subtraction is plusXXXXX / minusXXXXX. plusYears(1) etc. Adding weeks with plusWeeks(3) gives “P21D”. There is no Period expression for the week
  • LocalDate / LocalDateTime can add/subtract dates with Period as argument in plus / minus method
// Add years using Period
LocalDateTime dt = LocalDateTime.now();
Period p = Period.ofYears(1);

// This is equivalent to the following two lines (method chains have no meaning)
// Period p1 = Period.ofDays(1);
// Period p = Period.ofYears(2);
Period p = Period.ofDays(1).ofYears(2);

Duration: Hours, minutes, seconds

  • The Duration representation of toString() is “PT00H00M00S” The first “PT” is an abbreviation for “Period of Time”
  • There are several ways to create an instance of Duration
    • Diff two LocalDateTime or LocalTime with between method
    • Generated by ofXXXXX method such as ofHours(1)
    • Generated by using ChromeUnit together with of method such as of(1, ChronoUnit.HOURS)
  • Duration can add/subtract day, hour, minute, second, millisecond, nanosecond If you add the day, it will be PT24H, and if it is milliseconds or less, it will be PT0.13S.
  • LocalTime / LocalDateTime can add and subtract hours, minutes and seconds with Duration as argument in plus / minus method

java.time.Instant

  • Class that expresses the elapsed time from the epoch time
  • There are several ways to create an instance
    1. Instant#now()
    2. Instant#ofEposSecond(long)
    3. Instant#ofEpocMilli(long)
    4. LocalDateTime#toInstant(ZoneOffset)
    5. ZonedDateTime#toInstant()
  • ZoneOffset is required in LocalDateTime#toInstant because LocalDateTime does not include time zone information.
  • Instant time zone is always UTC

I/O

Reading using java.io.Reader

  • Reader
    • public int read() Returns the read single character. When the end is reached -1
    • public int read(char[] buffer)
    • public int read(char[] buffer, int offset, int length) Puts the read characters into some or all of the array and returns the number of characters. When the end is reached -1
  • BufferedReader
    • public String readLine() Returns the read line of text. Null when the end is reached

Writing using java.io.Writer

  • Writer
    • public void write(char[] buffer)
    • public void write(char[] buffer, int offset, int length) Write part or all of the array
    • public void write(int c) Write 1 character
    • public void write(String str)
    • public void write(String str, int offset, int length) Write part or all of the character string
  • BufferedWriter
    • public void newLine() Write a newline character

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

  • skip(long bytes) Skip a specified number of bytes from the current position
  • mark(int readAheadLimit) Mark the current position and return with reset(). The argument is ** the maximum number of characters that can be read while maintaining the mark **
  • reset() Return to the position marked with mark()
// The content of the file is "01234567"
// 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); // Mark current position (location of INDEX=5 with "6")
    System.out.print(br.readLine());
    br.reset(); //Return to the marked position (location of INDEX=5)
    System.out.println((char)br.read());
} catch (IOException e) {
    e.printStackTrace();
}

java.io.PrintWriter

  • A subclass of java.io.Writer that can output the primitive type as istarget boolean/char/char[]/int/float/long/String/Object
  • You can format strings using format in addition to print and println
  • Has automatic flash function
  • There is a PrintStream in a class that has the same function. Changed to PrintWriter in JDK1.2, but remains for backward compatibility

java.io.Console

  • Read data from standard input
  • Get a singleton instance with System#console(). If unavailable, returns null
  • Get the input string as a String with readLine()
  • Get the input string with char[] with readPassword(). Since the password is read, the character string is not displayed when entering it.
  • You can get PrintWriter and Reader associated with the console with writer() and reader() respectively.
  • Console itself also has printf and format methods to output a string to the console.

Notes on serialization

  • Classes that implement the java.io.Serializable interface can be serialized
  • Either of the following is not subject to serialization
    1. static variable
    2. Member variables declared as transient
  • If superclass is serializable, subclass is also serializable
  • In deserialization, neither the instance initialization block nor the constructor is called. But the static initialization block is called In the following cases, only the superclass constructor is called.
    1. It is Serializable itself, but the superclass is not Serializable
    2. Superclass has no-argument constructor
    3. Subclass constructor does not explicitly call parent constructor
  • Whether or not a member variable can be serialized is determined by the data type of the content, not the field Serializable if the variable type is Serializable, regardless of the variable type

NIO2

java.nio.file.Path (feature)

  • Generated by the following method
    • Paths#get(String, String...)
    • FileSystem#getPath(String, String...)
  • The main features are as follows. Has features not found in java.io.File
    • Handles file and directory paths
    • File attributes (owner, permissions, etc.) can be acquired and changed
    • Can handle symbolic links
    • It is possible to change and monitor events that occurred in the directory such as file creation.
  • Mutual conversion with java.io.File is possible
    • File#toPath()
    • Path#toFile()

java.nio.file.Path (method)

  • getRoot() Returns the root of the path. Null from Path generated by relative path
  • subpath(int start, int end) Generate a Path that excludes the root and extracts the range specified by the index
  • getName(int) Returns a String with the indexed part, excluding the root
  • relativize(Path) Returns the relative path to the argument
  • resolve(String), resolve(Path) Resolve the path. Path that is the return value depends on the argument
    • Argument is a relative path… Returns the concatenated argument to the receiver
    • Argument is an absolute path… Returns the argument as it is
    • Argument is empty…Returns the receiver itself
  • resolveSibling(String), resolveSibling(Path) Resolve the path to the receiver’s parent. Path that is the return value depends on the argument
    • Argument is an absolute path… Returns the concatenated argument to the receiver
    • Other… Returns the concatenated arguments to the receiver
  • normalize() Returns a path converted to an appropriate form by removing redundant parts such as “.” and “..”
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. Obtained by static method of FileSystems class

  • FileSystems#getDefault
  • FileSystems#getFileSystem
  • FileSystems#newFileSystem

java.nio.file.Files (file operations)

The following are all static methods

  • copy Copy files and directories
    1. The contents of the directory are not copied
    2. When there is a file with the same name in the copy destination, an exception is made if there is no overwrite specification in CopyOption.
    3. With the default behavior, copying files does not copy attributes
    4. When symbolic link is copied without specifying CopyOption, the entity indicated by the link is copied
    5. The path given as an argument is not the location to copy/move, but the path after movement/copy
  • move Move files and directories. Behavior is the same as 1-5 of copy
  • getAttribute(Path, String, LinkOption...) Read the attribute values of a file (file size, modification date, etc.)
  • Stream<String> lines(Path)
  • List<String> readAllLines(Path) Returns all lines in the file. Return type differs depending on the method

java.nio.file.Files (directory operations)

The following are all static methods

  • createDirectory() Create a directory but no parent
  • createDirectories() Create directory including parent
  • delete / deleteIfExists Delete the file. If it fails, the former returns an exception and the latter returns a boolean type. Both cannot be deleted if there is a file in the directory and an exception occurs
  • newDirectoryStream(Path) Return the path in the directory with Iterable implementation class DirectoryStream<Path>
  • list(Path) Returns a list of files and directories in a directory with Stream<Path>. Raises an exception if the argument is not a directory

java.nio.file.Files (Search directory)

The following are all static methods

  • walk()
  • walkFileTree() Search recursively including subdirectories
  • list() Search only that directory
  • find() Recursively search for items that match the conditions, including subdirectories
  • All of these return values are streams, so pipeline processing is possible

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 showing a set of attribute information

  • BasicFileAttributes interface Basic attribute information
  • DosFileAttributes interface DOS attribute information
  • PosixFileAttributes interface Unix/Linux attribute information
  • AttributeView interface A set of attribute information. The following exist as sub-interfaces
    • BasicFileAttributeView
    • DosFileAttributeView
    • PosixFileAttributeView

Parallel processing

Functions provided by the parallel processing utility

  1. Thread pool Thread creation and reuse
  2. Parallel collection Collection that can properly handle concurrent access from multiple threads
  3. Atomic variables Implements an indivisible set of operations that prevents concurrent access to inconsistent values (same as synchronized)
  4. Counting semaphore Can freely set the number of threads that can concurrently access finite resources

Parallel collection

  • APIs related to parallel processing are as follows. All java.util.concurrent packages
    • BlockingQueue interface
    • BlockingDeque interface
    • ConcurrentMap interface
    • ConcurrentHashMap class
    • CopyOnWriteArrayList class
    • CopyOnWriteArraySet class
  • When a collection object that does not support parallel processing is operated from multiple threads, java.util.ConcurrentModificationException occurs.
  • When an iterator is used in an extended for statement etc. when operating from multiple threads, the contents of the collection when the iterator is created are used.#### java.util.concurrent.ConcurrentMap interface

  • V getOrDefault(Object key, V defaultValue) Returns the value associated with key. Returns defaultValue if none
  • V putIfAbsent(K key, V value) Add only when the value associated with key does not exist in the map
  • boolean remove(Object key, Object value) If there is an element where both key and value match, delete it
  • V replace(K key, V value) Replace if the value specified for key is in the map
  • V replace(K key, V oldValue, V newValue) If there is an element where both key and oldValue match, replace the value with newValue
// map contents are [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 (element with KEY=1 already)
map.put(2, "Two");
map.replace(2, "Two.2"); // replace
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 remove (the second argument is different from the existing value)

java.util.concurrent.CopyOnWriteArrayList class

  • When changing the element held internally, copy the array containing the old element, change it, and replace it As a result, the overhead increases as the list size increases.
  • If another thread accesses the list while modifying an element (while copying to a new array), it will see the contents of the old array.

java.util.concurrent.CyclicBarrier class

  • Provides a function to align the threads of each thread in the thread party (set of threads that emphasizes and operates)
  • Specify the number of threads to cooperate in the constructor. The first argument is the number of threads to be coordinated, and if there is a second argument, the process executed when the trip (=barrier is released)
    • new CyclicBarrier(int)
    • new CyclicBarrier(int, Runnable)
  • The thread that executes await() waits until the number of threads specified in the CyclicBarrier constructor await.
    • await(long timeout) No timeout
    • await(long timeout, TimeUnit unit) There is a timeout
  • When new CyclicBarrier(3) is executed for four threads, a trip occurs when three threads await. However, the last one cannot break through the barrier until two more threads have await, so the subsequent processing cannot be executed.
// Since there are 3 threads for 2 barriers allowed,
// The process stops with "wait wait wait finish finish"
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

  • Executorexecute(Runnabble)
    • ExecutorServicesubmit(Runnable) etc.
      • ThreadPoolExecutor
      • ForkJoinPool
    • ScheduledExecutorServiceschedule(Runnable,long,TimeUnit) etc.
      • ScheduledThreadPoolExecutor

Executors methods and corresponding ExecutorService specifications

  • newSingleThreadExecutor() Perform tasks in a single thread
  • newCachedThreadPool() Create a new thread as needed or reuse it to execute a task
  • newFixedThreadPool(int) Perform tasks by reusing a fixed number of threads
  • newScheduledThreadPool(int) Perform tasks by reusing a fixed number of threads. Tasks can be scheduled
  • newSingleThreadScheduledExecutor() Perform tasks in a single thread. Tasks can be scheduled

ExecutorService#execute

  • Obtain a proper ExecutorService object with the static method of the Executors class and execute it with the execute(Runnable) method
  • Use the following method to check the task execution status
    • isShutdown() If true, new task cannot be accepted (may be unexecuted or in progress)
    • isTerminated() If true, new tasks cannot be accepted and all tasks have finished
  • If isShutdown() is not true, execute of new task is possible. Exception occurs when you execute execute when true

ExecutorService#submit

  • ExecutorService has multiple overloaded methods and the return value is Future. What you can get from Future depends on the method
    • Future<T> submit(Runnable) Execute the task. What can get is the success or failure of the task
    • Future<?> submit(Runnable, T) Executes the task of the first argument and returns the value of the second argument. What can get is the success or failure of the task
    • Future<T> submit(Callable<T>) Execute the task. The return value from the task can be get
  • The task is executed immediately, but if you execute Future#get(), there will be a waiting time until the value can be acquired even after the task ends.
  • From Future<T>, you can also cancel the task that you have submit (if possible)

Runnable and Callable

  • Runnable
    • Do not return
    • Cannot throw check exception
    • Can be executed by either execute or submit
  • Callable
    • Can return a return value
    • Can throw check exception
    • Can only be executed by submit

java.util.concurrent.Future interface

  • V get() Can obtain the execution result of the task
  • boolean cancel(boolean) Try to cancel the task
  • boolean isCancelled() Know if a task has been canceled
  • boolean isDone() Find out if a task is complete

Parallel stream

  • Generate
    • Collection#parallelStream() Generate parallel stream from collection
  • Mutual conversion
    • BaseStream#parallel() Generate parallel stream from sequential stream
    • BaseStream#sequential() Generate sequential stream from parallel stream
  • Judgment
    • BaseStream#isParallel() Determine if it is a parallel stream
// Generate parallel stream
Arrays.asList(1, 2, 3).parallelStream().forEach(System.out::println);

// Generate parallel stream from 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

  • I threw away here. If you are serious, study properly

Atomic variables

  • Classes with names starting with Atomic ~ guarantee that operations on the values they handle are thread-safe.
  • The main classes are as follows. No Float or Double
    • AtomicInteger… int type
    • AtomicLong …long type
    • AtomicBoolean …Boolean type
    • AtomicReference …Reference type

JDBC

Query execution

  • The packages to which the used class belongs are java.sql and javax.sql.
  • The URL format for connecting to DB with JDBC is as follows jdbc:[DB name]//[host(:port)]/[db-name](?option)
  • The basic processing flow is as follows
    1. Get Connection with DriverManager#getConnection(url,id,pass)2. Get Statement with Connection#createStatement()
    2. Get ResultSet by Statement#executeQuery(sql)
    3. Fetch query results from ResultSet
  • Before JDBC3.0, it was necessary to execute Class.forName([JDBC driver class name]) before DriverManager#getConnection.
  • Even if the result of the query executed by executeQuery is 0, the return value is not null but an empty ResultSet.
  • Only one ResultSet can be handled by one Statement. If you get another ResultSet without closing the first ResultSet, the first will be closed automatically. Exception when trying to operate on a closed ResultSet Also automatically closed when executing executeUpdate etc.

How to use the methods in #### Statement

  • ResultSet executeQuery(String sql) Returns the execution result of the query
  • int executeUpdate(String sql) Execute SQL such as INSERT/UPDATE/DELETE and return the processing number
  • boolean execute(String sql) Executes any kind of SQL, including queries, and returns whether a ResultSet was obtained as a result of processing. If it is true, ResultSet is returned, and if it is false, it is not. If ResultSet is returned as a result of processing, get it with Statement#getResultSet(). If it is not ResultSet, get the number of processing with Statement#getUpdateCount().

ResultSet acquisition and properties

  • In “Connection#createStatement(type, concurrency), specify "Scrollability" and "Table data updateability" of ResultSet` in order.
  • There are three types of scrollability, all of which are constants of the ResultSet class.
    • TYPE_FORWARD_ONLY …Moveable only in the forward direction
    • TYPE_SCROLL_INSENSITIVE …Moveable in both directions. Do not reflect changes to the cursor
    • TYPE_SCROLL_SENSITIVE …Moveable in both directions. Reflect changes to cursor
  • Table data can be updated in the following two types, all of which are constants of the ResultSet class.
    • CONCUR_READ_ONLY …Read only
    • CONCUR_UPDATABLE …Updatable
  • When retrieving updatable ResultSet by Statement#createStatement(..., ResultSet.CONCUR_UPDATABLE), the column to be updated must be specified in the select statement of executeQuery.

Method for scrolling ResultSet

  • boolean absolute(int) Move to the specified line (specify absolute position). The first line is 1. 0 is beforeFirst
  • boolean relative(int) Move by specifying the relative position. Go to the next line if the value is positive, go to the previous line if the value is negative
  • boolean next() Move to the next line
  • boolean previous() Move to the previous line
  • boolean first() Move to first line
  • void beforeFirst() Move to just before the first line
  • boolean last() Move to the last line
  • void afterLast() Move right after the last line

Updatable ResultSet

  • Update Make changes with updateString or updateInt and commit with updateRow Even if the type of Statement is TYPE_SCROLL_INSENSITIVE, it will not be changed, not even the contents of the DB, unless the updateRow is set.
    • updateString(int, String)
    • updateInt(int, int)
    • updateRow()
  • Insert Move to the insert row with moveToInsertRow, specify the insert contents with updateString and updateInt, and insert with insertRow.
    • moveToInsertRow()
    • insertRow()
  • Delete
    Delete current line
    • deleteRow()

Localization and format

Get java.util.Locale object

  1. Locale#getDefault() Locale of Java execution environment
  2. new Locale(String) Argument is “language code”
  3. new Loacle(String, String) Argument is “language code, country code”
  4. new Loacle(String, String, String) Argument is “language code, country code, variant”
  5. Set an appropriate value in Locale.Builder generated by new and generate by build()

java.util.Properties

  • Supported file formats are text and XML
  • In case of text file, enumerate keys and values separated by = or:
  • Load property list from file
    • load(InputStream)
    • load(Reader)
    • loadFromXML(InputStream)
  • Output property list
    • list(OutputStream)
    • list(Writer)
    • entrySet()
    • forEach(BiConsumer)
  • Get property
    • getProperty(String) Returns null if there is no corresponding Key
    • getProperty(String, String) If there is no corresponding Key, return the second argument

java.util.ListResourceBundle

  • Prepare resources in a .class file and place them in the place where the class path is set.
  • Usage is as follows
    1. Define a public class that inherits ListResourceBundle Override public Object[][] getContents() The fully qualified name (package name + class name) of this class is the base name, and this class is for the default locale. Example: Class name is “MyResource” Define a class for a locale different from 2.1 by inheriting ListResourceBundle The naming rule is ** “base name_language code_country code”** Example: Class name for English locale is “MyResource_en_US”
    2. Get a ListResourceBundle object with ResourceBundle#getBundle(base name[, locale])
    3. Retrieve the value with ResourceBundle#getXXXXX (key string)

java.util.PropertyResourceBundle

  • Prepare resource in .properties file and place it in the place where classpath is set up.
  • Usage is as follows
    1. Create a property file for the default locale
      • Extension is .properties
      • Define multiple properties in “key name = value” format
      • File must be ISO-8859-1 encoded
      • File naming convention is the same as the class name of ListResourceBundle Create a file for a locale different from 2.1
      • File naming convention is the same as the class name of ListResourceBundle
      • MyResource_en_US.properties for English locale
    2. Get PropertyResourceBundle object with ResourceBundle#getBundle(base name[, locale])
      • Same method as getting ListResourceBundle
    3. Retrieve the value with the following method. no getInt
      • ResourceBundle#getObject(key string)
      • ResourceBundle#getString(key string)
      • ResourceBundle#getStringArray(key string)

Resource bundle priority used

  • If there is no resource bundle corresponding to the locale, a MissingResourceException exception is thrown
  • There is no exception even if there are multiple resource bundles with the same name.
  • Resource bundles are searched by individual property rather than by file. The search priority is as follows
    1. Language code and country code match
    2. Language code matches
    3. Default locale matches
  • If the property corresponding to the specified key does not exist in any class/file, MissingResourceException is raised
  • If both the ListResourceBundle class and the properties file exist with the same name, the class takes precedence over the file.

Format numbers using #### NumberFormat

  • Use the static method of NumberFormat class to get the desired object
    • getInstance() Number format for the default locale
    • getInstance(Locale) Numeric format for any locale
    • getCurrencyInstance(Locale) Currency format for any locale
    • getIntegerInstance(Locale) Integer format for any locale
  • Get a formatted string with format(long) or format(double)
  • Get the numerical value from the character string with parse(String). The return value is Number# Change log

  • 2020/08/23 Publish to Qiita
  • 2020/08/24 Changed the list of functional interfaces to tabular format Added sample code for enumerated values