Schedule
Schedule
1.1.3 Casts
-The ternary ?:
1.1.8 Bitwise Operators
1.2 String-StringBuilder
1.2.1 String
-Final class
-Constructor: (), byte[], char[], String, StringBuilder
- Static methods: join, valueOf, format
-Instance methods: charAt, concat, contains, startsWith,
endsWith, equals, equalIgnoreCase, indexOf, indent,
isBlank, isEmpty, lastIndexOf, length, repeat, replace,
replaceAll, replaceFirst, split, strip, stripIndent,
stripLeading, stripTrailing, subString, toLowerCase,
toUpperCase, trim
-Escape character:\ and Escape Sequence:
\t Insert a tab in the text at this point.
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
\f Insert a form feed in the text at this point.
-Delimeter “””
+The starting delimiter is """ followed by any number of
white spaces followed by the ASCII LF character (i.e. the
new line character).
+The ending delimiter is """.
-Trailing white space:Incidental white space + essential
white space
+Incidental whitespace: whitespace before closing “””
+Essential whitespace: whitespace after starting “””
1.3 Typer inference with var
-var is not a keyword, can use var as variable name
-Var can use in:
+static/instance initialization block
+as a local variable
+iteration variable in enhanced for-loop
+as looping index in for-loop
+as a return value from another method,
+as a return value in a method,
1.4 Controlling Program Flow (5%)
-break: exit a switch and break out of a loop.
-label: can use to code block or block level statement
(for…) but not to declaration
-continue: transfer control to the header of innermost
enclosing loop
-Note: labeled break or continue statement must always
exist inside the loop where the label is declared
-Don’t use keyword for label.
1.5 if/else, swith-case, loops
1.5.1 Switch
-works with: byte, short, char, int+ their wrap+
enumarted+String
-case label must fit into switch selector
-Switch statement
-Switch expression
+”case L->: Labels:
-Scope:
+place where it’s true
-Initialization Blocks:
-Constructor flow
+ the class is loaded: static field initializer + static
initialization block in order in class
+ If having second constructor in constructor ->Call it
+ Otherwise:
default values
instance fields initializers+ instance initialization block in
the order in class declaration
The body of constructor.
-Note:
+Can name constructor’s name to any method
2.2 Fields, methods with instance, static,
overloading
-Method parameters can have at most one vararg and it
must appear as the last argument.
-Overloading: several methods have the same name but
different parameters and (maybe)different return types.
-final fields: must be assigned in instance initializer or all
constructor
-Choose method for overloading:
Class -> boxing-unboxing
2.3 Nested class, inner class, local class,
anonymous class
-Nested class = Inner class + Static nested class
2.3.1 Nested Class
-Nested Class: Class inside class
-Inner Class: Non-Static Nested Class
+Member inner class, local inner class, anonymous class
-Can have all access modifier + seal
-Can have static methods+ final static fields
-method gets to access both its own data fields and
outer object -> outer object can exist many instances of
inner class.
2.3.2 Syntax rules
-OuterClass.this denotes the outer class reference
+OuterClass1st.OuterClass2nd.this just refer to
OuterClass2nd object.
-Method:
+objectOuter.new InnerClass()
+new OuterClass.InnerClass()
+new OuterClass().new InnerClass()
-Refer to Inner class when it occurs outside the scope of
outer class:
2.3.3 Local inner classes
-Local classes are not declared with access specifier.
Their scope is restricted to the block they’re declared
-hidden from the outside
- can access final local variables + like nested class
2.3.4 Anonymous Inner Classes
-General syntax:
2.8 Enumeration
-Use property:
-CallableStatement: prepareCall():
-releaseSavepoint(SavePoint)
12. Date and Time API
12.1 Time Line
-Instant represents a point on the time line.
+Instant.MAX is 31/12/1000000000
+Instant.now() give the current instant.
+Instant.truncatedTo(ChronoUnit): make a copy
+You can compare 2 instants with equals() and
compareTo().
+Duration.between():
-
OffsetDateTime represents times with an offset from
UTCm without time zone rules.
9.Record and Sealed Class
9.1 Sealed class
-You can define permitted subclasses in the same file,
then you can omit permits:
-Permitted subclasses:
+Must extend the sealed class.
+Must be one of: final, sealed, non-sealed
+Must be in the same module or same package.
-Sealed interface: can have Record classes as permitted
subclasses
9.2 Record
- getters (Note: name of getter = name of instance fields,
example: name()), canonical constructor
-final: equals (true if objects of same type and values
match), hashCode (return same value for 2 objects if all
field values match implement), toString(name of
record+field names+field values)
-Record can’t be extended and can’t have extend clause.
-Record can Serializable interface
-Record may have at most 1 varagrs component.
-don’t have instance variable + instance initializers
-We can use static variables and static (and instance, not
setter) methods in record
9.2.3 Constructors
-Canonical constructor:
+ customize constructor for validation: (compact form)
+Example: fields aren’t null
-DataFormatter.ofPattern():
-DateFormat:
+Static: getCalendar(), getDateInstance(),
getDateTimeInstance(), getInstance(), getTimeInstance()
11.5 Number format
java.text.
11.5.1 Format numeric values
-NumberFormat: getInstance(), getNumberInstance(),
getCurrencyInstance(), getPercentInstance().
-NumberFormat.getCompactNumberInstance()
-NumberFormat.getCompactNumberInstance(Locale,
NumberFormat.Style)
+NumberFormat.Style: LONG, SHORT(default)
-parse() throws java.text.ParseException
-If your key function can return null, you will like the
nullFirst and nullLast adapters. These methods need a
comparator.
-Collection Interface:
-Iterators:
+listIterator():
+set():
+If an iterator traverses a collection while another
iterator is modifying it -> Exception:
Remov
remove() poll()
e
Examin
element() peek()
e
Throws Throws
Special value Special value
exception exception
Remov
removeFirst() pollFirst() removeLast() pollLast()
e
Examin
getFirst() peekFirst() getLast() peekLast()
e
push()=addFirst(), pop()=poll()
Deque interface: ArrayDeque and LinkedList
-PriorityQueue:
+A priority queue retrieves elements in sorted order:
remove() get the smallest element currently. But the
priority queue doesn’t sort all its elements. It uses heap.
You can implement Comparable and Comparator.
+A typical use for a priority queue is job scheduling.
4.3.4 Map
-Note: only HashMap +LinkedHashMap support null
key+value.
-Collection elements: must be exact the type of variable
+merge()
+compute(key)/computeIfAbsent(Function)/
computeIfPresent(BiFunction)
-Map views:
+The elements of the entry set are objects of a class
implementing Map.Entry interface.
+keySet() is class that implements Set interface.
Enumerate all keys of a map:
Or use forEach()
+If you remove() of the iterator on the key set view, you
remove the key and its value from the map. But you
can’t add element to the key set view.
-WeakHashMap
+ WeakHashMap class co-operates with the garbage
collector to remove key/value pair when the only
reference to the key is the one from the hash table entry
-LinkedHashSet + LinkedHashMap:
remember in which order you inserted items.
-IdentityHashMap:
+For comparison: use ==, not equals()
4.3.5 Views and Wrappers
-Small collections: .of()
-Subranges:
+subList(): obtain a view into the subrange of list:
SortedSet
SortedMap
Navigable
-Synchronized Views
4.3.6 Algorithms
-Sorting and Shuffling:
+sort: implement List+ Comparable :
-Binary search:
+Collections.binarySearch():sorted in ascending
order,implement List
-Bulk operations:
+ : remove all elements from coll1 that
are present in coll2.
+ remove all elements from coll1 that
are not present in coll2.
+Find the intersection of 2 sets:
-Hastable:
+Hashtable: HashMap+synchronized methods
+If you don’t require compatibility with legacy code, use
HashMap. If you need concurrent access, use
ConcurrentHashMap.
-Property Map:
+Property map is a map structure of a special type. It has
3 characteristics:
Ok False
-Generic methods:
-Wildcard:? Use in variable reference in generic:
+Stream.iterate():UnaryOperator<T> interface
-Stream.ofNullable
- Iterable ->stream
-map(): Function
-Spliterator<>:
+spliterator(): create Spliteartor
+trySplit(): split the 1st half go to the result and the
remain half remain with original one.
+forEachRemaning():
-collect(),reduce()
-Not reduce methods but useful:
+findFirst(): often useful when combined with filter
+orElseThrow()
-Consume an optional value:
-ifPresent(Consumer):
-ifPresentOrElse(Consumer,Runnable): take one action if
the Optional has a value and another action if it doesn’t
+isPresent(), isEmpty()
-Create optional values:
Optional.of(result) and Optional.empty()
+Optional.of(null)->throw Exception
->Optional.ofNullable(obj): returns Optional.of(obj) if
obj is not null and Optional.empty() otherwise.
-Optional<Int/Long/Double>:
+getAs<Int/Long/Double>
+Collecters.toSet():
+ Collectors.toCollection(Constructor):
+Collectors.joining():
+Delimit between elements:
+summarizing(Int/Long/Double): return
wa(Int/Long/Double)SummaryStatistics: getCount(),
getSum(), getAverage(), getMax(), getMin()
+ groupingByConcurrent()
- partitioningBy(): Predicate.
+Collectors.counting():
+Collectors.summing(Int/Long/Double):To<>Function
+Collectors.averagingDouble/Int/Long(): To<>Function
+Collectors.maxBy, minBy: Comparator
Function
-Collectors.mapping():Function +Collector constructor
+flapMapping():
+Collectors.summarizingInt/Long/Double:To<>Function
+Collector.filtering:Predicate+Collector Constructor
5.3.11 Reduction Operation
-reduce(BinaryOperator): return Optional
-mapToInt/Long/Double(): To<>Function
-Unicode text:
+The basic methods:
8.2 I/O usually seen
-InputStream:
+
+readAllBytes()
-OutputStream
+
+
+transferTo(): transfer all byte from I to O
+available(): number of bytes available to read
-RandomAccessFile
+Constructor: File+String
+implement both DataInput + DataOutput
+Modes: "r", "rw", "rws", and "rwd". If file doesn’t exist:
r:throw exception, others: attempt to create file
+write/readUTF(): UTF-8
+File pointer: seek(), getFilePointer()
-FileReader/FileWriter:
+Constructor: File, String
-System.in:
+a variable of java.lang.System
+The standard input stream:This stream is already open
and ready to supply input data.
+Can’t be reassigned to any other stream directly: must
use InputStream.setIn()
8.2 Serialization
-Object must implement Serializable and serial number
-ObjectOutputStream:
-ObjectInputStream:
8.3 Files
8.4.1 Paths
-path format: start with / or c:
-Paths.get
+getName(int):
When one thread locks, no other thread can get past the
lock() until it unlock
+tryLock()=check free+lock()
+Declare lock as private + final is a good way.
+ReadWriteLock interface: a pair of Locks: Read Lock
(multiple threads read simultaneously as long as no
thread writing) and WriteLock(one thread write to the
resource, and no thread (including readers) can access)
ReentrantReadWriteLock
+readLock().lock()/unlock()
+writeLock().lock()/unlock()
7.3.2 Condition Objects
-Condition object: manage threads that have acquired a
lock but can’t do useful work
-newCondition():
-await(): thread is deactivated, give up the lock + enter a
wait set until another thread signalAll()
-signallAll(): reactivates all threads waiting, remove from
wait set, acquire the lock and continue
+singal(): unblock a single thread randomly. If no other
thread call signal() again -> deadlocks.
-Simple structure:
-wait(),notifyAll(),notify():
-Can use synchronized static method
-Synchronized methods ends with check exception->lock
is released automatically.
7.3.4 Synchronized Blocks
7.3.6 Atomic
-Atomicity: operations that are performed as a single,
indivisible step ->thread-safe
->guarantee that correct vale is computed and returned
even multiple threads access.
-Final atomic can use mutator and must initialize
-Atomic<Long/Integer/Boolean>
+addAndGet(), decrementAndGet(), compareAndSet()
7.3.7 Deadlocks
-All threads get blocked
-Compile:
-Run:
+ --module-path = -p: directories contain modular jars or
specific modular or non-modular jar
+--module= -m: File class
+-classpath:
-Package:
: file .jar in mods.
6.3.2 Module keywords
-exports(package): indicate a module intends for those
packages to be used by Java code outside the module
Update module:
0.7 IO API
0.7.1 Serialization
0.8 Modules
-Basic
+Modules benefits: improve security + maintainability
-Migration to Modular App
-Services in Modular App
0.9 JDBC
0.11 Localization
-DateFormat + NumberFormat