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.
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.
The prefix added to the beginning of the number determines the base number.
Instance variables with the final qualifier must be initialized in the constructor
Processes related to object initialization are executed in the following order
name () and toString () return their own string representationname () is final and cannot be overridden. toString () is possiblevalueOf () methodenum 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 () is the samehashCode (), implement so that values are returned from objects with the same value.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"); }
}
| 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 |
Supplier, ʻUnaryOperator, BinaryOperator follow below ** 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 |
- | - |
| 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 |
Arrays#asList
is ** incompatible with ʻArrayList <E>. ** Cast failsList is the order of the index in principleSet and Map distinguish their properties by the prefix of the class nameLinked will be inserted in the order they are inserted.Tree are sorted by natural order. When arranged in natural order, it becomes ** number → alphabet (large) → alphabet (small) **remove ()get ()poll ()peek ()Queue is that you can insert or remove elements at the beginning or end, as the name of ** Double Ended Queue ** suggests., push (E) / ʻaddLast (E)removeFirst () / removeLast ()getFirst (), pop () / getLast ()/ ʻoffset Last (E)pollFirst () / pollLast ()peekFirst () / peekLast ()Queue, the element cannot be accessed by indexQueue interface extension in the java.util.concurrent package also has a method that allows you to set a timeout.
Waiting does not always occur, and waiting occurs when you cannot insert or delete.Deque, ʻArrayDeque`, cannot contain nulls..class"?" Instead of"*"("*"is Kotlin)<? Super XXXXX> can contain objects of the same type as XXXXX.java.lang packageComparable iscompareTo (To). Returns a negative value if it is less than the comparison partner, zero if it is equal, and a positive value if it is greater.Comparable <T> is given the type of the object that compareTo takes as an argument.java.util packageComparable interface.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
Collection#stream() -> Stream<E>Arrays#stream(E[] array) -> Stream<E>Arrays#stream(int[] array) -> IntStreamArrays#stream(long[] array) -> LongStreamArrays#stream(double[] array) -> DoubleStreamStream#of(E… values) -> Stream<E>Stream#empty() -> Stream<E>IntStream#of(int… values) -> IntStreamLongStream#of(long… values) -> LongStreamDoubleStream#of(double… values) -> DoubleStreamIntStream#range() / IntStream#rangeClosed() -> IntStreamLongStream#range() / LongStream#rangeClosed() -> LongStreamBufferedReader#lines() -> Stream<String>java.nio.file.Files#lines() -> Stream<String>Both methods of java.util.stream.Stream
generate(Supplier<T> supplier)Stream that holds an infinite number of elements provided by the supplieriterate(T seed, UnaryOperator<T> f)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`
reduce (BinaryOperator op)… The return value is ʻOptional reduce (T initial, BinaryOperator op)… The return value is TfindAny ()… Results may change each time you runfindFirst ()… The same result can be obtained no matter how many times it is executed.
min()max()reduce(BinaryOperator op) differs depending on the type of Stream. For example, findAny ()` is as follows
Stream#findAny() … Optional<T>IntStream#findAny() … OptionalIntLongStream#findAny() … OptionalLongDoubleStream#findAny() … OptionalDoubleOptionalInt#of(int value)OptionalLong#of(long value)OptionalDouble#of(double value)… Execute Consumer` if there is a valueThe method to get the value from ʻOptional
get()NoSuchElementException if it does not existorElse(T)orElseGet(Supplier<T>)Supplier if it does not existorElseThrow(Supplier<X extends Exception>)Supplier if it does not existʻThe method for retrieving the related class and value of Optional
Optional<T>#get()OptionalInt#getAsInt()OptionalLong#getAsLong()OptionalDouble#getAsDouble()Stream types ismap ()Stream <T> type is mapToObj () type is mapToInt () `LongStream type ismapToLong ()DoubleStream type ismapToDouble ()collect () is a method that aggregates the elements in Stream to get one object.Collectors class provides an implementation of the Collector interface that suits your needs.
Due to its nature, some methods and roles of the Stream class overlap.Error、Exception、 RuntimeException
Throwable and belong to the java.lang package and ʻException are subclasses of ThrowableRuntimeException is a subclass of ʻException (a grandchild of Throwable`)try ~ catch are subclasses of ʻException other than RuntimeException`.throws and catch methods do not have to match.//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;
}
}
throws declaration in a subclass, it is up to you to declare the overridden method throws.throws in an overridden method must be the same as or a subclass of the original method.RuntimeException and its subclasses can be unconditionally specified in throws. However, since it is an unchecked exception, compilation will pass without catching at the caller.try only in try ~ with ~ resources statementjava.lang.AutoCloseable or its subinterface java.io.Closeable. / Closeablehave athrows declaration in close () , so whether you use it for a resource or in try`, you must catch an exception to get a compile error.
AutoCloseable#close() throws ExceptionCloseable#close() throws IOExceptionclose () of ʻAutoCloseable or Closeable`, it will be caught by catch.try block and the resource close, the exception raised byclose ()is stored as an array of Throwable in the exception object caught as a suppressed exception, and getSuppressed ( ) Can be obtainedtry ~ with ~ resources statement is as follows.try blockfinally 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)
}
when false is detected in the ʻassert statement, and the syntax is as follows.
ʻAssert boolean expression: error message;`java -ea: [class name].Date and Time API
LocalDate… DateLocalTime… TimeLocalDateTime… Date + timeZonedDateTime… Date + time including the difference from UTC / GMT in time zone IDTemporal interface. Moreover, its super interface is TemporalAccessorLocalDateTime # toLocalDate () and LocalDateTime # toLocalTime ()getMonth ()… Month Get by enumeration valuegetMonthValue ()… Get by int valueMonth: Represents the month
JANUARY, FEBRUARY, MARCH, …, DECEMBERDayOfWeek: Represents the day of the week
SUNDAY, MONDAY, TUESDAY, …, SATURDAYnow()of(year, month, dayOfMonth, ...)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 argumentsparse(String)、parse(String, DateTimeFormatter)DateTimeFormatter together, you can use any format string.LocalDate # of has two overload methods. In both cases, the date is specified, but the other differences are as follows.Month enumeration valueLocalTime # of has three overloaded methods, all specifying the hour and minute, but the other differences are as follows:java.time.format.DateTimeFormatter
ofPattern(String)ofLocalizedDate(FormatStyle)ofLocalizedTime(FormatStyle)ofLocalizedDateTime(FormatStyle)ofLocalizedDateTime(FormatStyle, FormatStyle)BASIC_ISO_DATE etc.java.time.format.FormatStyle
There are 4 types of FormatStyle
FormatStyle.FULLFormatStyle.LONGFormatStyle.MEDIUMFormatStyle.SHORTLocalDateTime 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));
Add ... plus (Temporal Amount amount ToAdd)
Subtraction… minus (Temporal Amount amount To Subtract)
Period and Duration implement the TemporalAmount interfaceplusYears and plusWeeks, but when dealing with multiple fields at once, call plus with Period and Duration as arguments.toString () is ** "P00Y00M00D" **
The leading "P" is an acronym for "Period"PeriodLocalDate and LocalDateTime with the between methodPeriod can be added or subtracted by year, month, day or week
The addition and subtraction methods are plusXXXXX / minusXXXXX. plusYears (1) etc.
If you add the weeks with plusWeeks (3), you get "P21D". Because there is no Period expression for the weekLocalDate / LocalDateTime can add or subtract dates with Period as an argument with the plus / minus method.//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 expression oftoString ()is " PT00H00M00S "
The leading "PT" is an abbreviation for "Period of Time"DurationLocalDateTime and LocalTime with the between methodChromeUnit in of methods such as ʻof (1, ChronoUnit.HOURS)`Duration can be added or subtracted in days, hours, minutes, seconds, milliseconds, nanoseconds
When the days are added, it becomes PT24H, and when it is less than a millisecond, it becomes PT0.13S.LocalTime / LocalDateTime can add or subtract hours, minutes and seconds with Duration as an argument with the plus / minus method.java.time.Instant
Instant#now()Instant#ofEposSecond(long)Instant#ofEpocMilli(long)LocalDateTime#toInstant(ZoneOffset)ZonedDateTime#toInstant()LocalDateTime # toInstant requires ZoneOffset because LocalDateTime does not contain time zone information.Reader
public int read()public int read(char[] buffer)public int read(char[] buffer, int offset, int length)BufferedReader
public String readLine()Writer
public void write(char[] buffer)public void write(char[] buffer, int offset, int length)public void write(int c)public void write(String str)public void write(String str, int offset, int length)BufferedWriter
public void newLine()skip(long bytes)mark(int readAheadLimit)reset (). The argument is ** the upper limit of the number of characters that can be read while maintaining the mark **reset()mark () was done//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.Writer that can output primitive types as they are
For boolean / char / char [] / int / float / long / String / Objectformat in addition to print and printlnPrintStream in a class with the same function
Replaced by PrintWriter in JDK1.2, but remains for backward compatibilityjava.io.Console
System # console (). ** Returns null if not available **readLine ()readPassword (). Since the password is read, the character string is not displayed when enteringPrintWriter and Reader associated with the console with writer () and reader (), respectively.Console itself has printf and format methods to print strings to the consolejava.io.Serializable interface can be serializedSerializable itself, but the superclass is not SerializableSerializableNIO2
Paths#get(String, String...)FileSystem#getPath(String, String...)java.io.Filejava.io.File is possible
File#toPath()Path#toFile()getRoot()subpath(int start, int end)getName(int)relativize(Path)resolve(String)、resolve(Path)resolveSibling(String)、resolveSibling(Path)normalize()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
FileSystems#getDefaultFileSystems#getFileSystemFileSystems#newFileSystemThe following are all static methods
copymovegetAttribute(Path, String, LinkOption...)Stream<String> lines(Path)List<String> readAllLines(Path)The following are all static methods
createDirectory()createDirectories()delete / deleteIfExistsnewDirectoryStream(Path)DirectoryStream <Path> of ʻIterable`list(Path)Stream <Path>. Exception throws if argument is not a directoryThe following are all static methods
walk()walkFileTree()list()find()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
BasicFileAttributes interface
Basic attribute informationDosFileAttributes interface
DOS attribute informationPosixFileAttributes interface
Unix / Linux attribute informationBasicFileAttributeViewDosFileAttributeViewPosixFileAttributeViewjava.util.concurrent packagesBlockingQueue interfaceBlockingDeque interfaceConcurrentMap interfaceConcurrentHashMap classCopyOnWriteArrayList classCopyOnWriteArraySet classjava.util.ConcurrentModificationException will occur.V getOrDefault(Object key, V defaultValue)V putIfAbsent(K key, V value)boolean remove(Object key, Object value)V replace(K key, V value)V replace(K key, V oldValue, V newValue)//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)
new CyclicBarrier(int)new CyclicBarrier(int, Runnable)waits until the number of threads specified in the constructor ofCyclicBarrier` awaits.
await(long timeout)
No timeoutawait(long timeout, TimeUnit unit)
There is a timeoutnew CyclicBarrier (3) for 4 threads, a trip will occur when 3 threads ʻawait. But the last one can't break through the barrier until two more threads ʻawait, so it can't continue.//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();
Executor … execute(Runnabble)… submit (Runnable)etc. *ThreadPoolExecutor *ForkJoinPool`ScheduledExecutorService…schedule (Runnable, long, TimeUnit)etc.
* ScheduledThreadPoolExecutornewSingleThreadExecutor()newCachedThreadPool()newFixedThreadPool(int)newScheduledThreadPool(int)newSingleThreadScheduledExecutor()ExecutorService#execute
object of the appropriate nature with a static method of the ʻExecutors class and execute it with the ʻexecute (Runnable)` methodisShutdown()isTerminated() is not true, a new task ʻexecute is possible. ʻExcute` when true raises an exceptionExecutorService#submit
Future<T> submit(Runnable)Future<?> submit(Runnable, T)Future<T> submit(Callable<T>)Future # get () is executed, there will be a waiting time until the value can be obtained even after the task is completed.submitted fromFuture <T>(only if possible).Runnable or submit`CallablesubmitV get()boolean cancel(boolean)boolean isCancelled()boolean isDone()Collection#parallelStream()BaseStream#parallel()BaseStream#sequential()BaseStream#isParallel()//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);
JDBC
java.sql and javax.sqljdbc: [DB name] // [host (: port)] / [db-name](? option)Connection withDriverManager # getConnection (url, id, pass)Statement withConnection # createStatement ()ResultSet withStatement # executeQuery (sql)ResultSetClass.forName ([JDBC driver class name]) before DriverManager # getConnection.is 0, the return value will be emptyResultSet` instead of null.ResultSet can be handled by oneStatement. If you get another ResultSet without closing the first ResultSet, the first one will be closed automatically. Exception when trying to manipulate a closed ResultSet
ʻAutomatically closes when executeUpdate` etc. is executedResultSet executeQuery(String sql)int executeUpdate(String sql)boolean execute(String sql)ResultSet. If true, ResultSet is returned, if false, it is not.
If ResultSet is returned as a result of processing, get it withStatement # getResultSet (). If it is not ResultSet, useStatement # getUpdateCount ()to get the number of processes.Connection # createStatement (type, concurrency), specify "scrollability" and "table data updateability" of ResultSet in order.ResultSet class.TYPE_FORWARD_ONLY… Can only be moved in the forward directionTYPE_SCROLL_INSENSITIVE… Can be moved in both directions. Does not reflect changes to the cursorTYPE_SCROLL_SENSITIVE… Can be moved in both directions. Reflect changes to the cursorResultSet class.CONCUR_READ_ONLY… Read onlyCONCUR_UPDATABLE… UpdatableResultSet withStatement # createStatement (..., ResultSet.CONCUR_UPDATABLE), the column to be updated must be specified in the select statement of ʻexecuteQuery`.boolean absolute(int)boolean relative(int)boolean next()boolean previous()boolean first()void beforeFirst()boolean last()void afterLast() or ʻupdateInt and confirm the change with ʻupdateRowEven if the type ofStatement is TYPE_SCROLL_INSENSITIVE, the contents of the DB and even the result set will not be changed unless it is ʻupdateRow.
updateString(int, String)updateInt(int, int)updateRow()moveToInsertRow to move to the insert row, use ʻupdateString or ʻupdateInt to specify the insertion content, and use ʻinsertRow` to insert.
moveToInsertRow()insertRow()deleteRow()Locale#getDefault()new Locale(String)new Loacle(String, String)new Loacle(String, String, String)Locale.Builder generated by new and generate it withbuild ()java.util.Properties
load(InputStream)load(Reader)loadFromXML(InputStream)list(OutputStream)list(Writer)entrySet()forEach(BiConsumer)getProperty(String)getProperty(String, String)java.util.ListResourceBundle
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"ListResourceBundle
The naming rule is ** "base name_language code_country code" **
Example: The class name for the English locale will be "MyResource_en_US"ListResourceBundle object withResourceBundle # getBundle (base name [, locale])ResourceBundle # getXXXXX (key string)java.util.PropertyResourceBundle
ListResourceBundleListResourceBundlePropertyResourceBundle object withResourceBundle # getBundle (base name [, locale])ListResourceBundleResourceBundle # getObject (key string)ResourceBundle # getString (key string)ResourceBundle # getStringArray (key string)MissingResourceException exception will be thrown.MissingResourceException will occur.ListResourceBundle class and the properties file have the same name, the class takes precedence over the file.NumberFormat class to get the desired object
getInstance()getInstance(Locale)getCurrencyInstance(Locale)getIntegerInstance(Locale)format (long) or format (double)parse (String). The return value is NumberRecommended Posts