-
Chapter 1: Declaration, Access Control
-
Identifier/JavaBeans
- Legal Identifiers: start with letter, $, _
- Keywords
-
Sun's Java Code Conventions
- Class Name
- Method
- Variable
- Constant
-
JavaBeans Standards
- get/set method, public
- boolean: is/get
- event/listener, addActionListener()
-
Class Declaration
-
Source File
- one public class per source file
- comments are anywhere
- public class name matches the file name
- package should before import
-
Modifier
- Access: public, protected, private, default(package level)
-
Non-Access: strictfp, final, abstract
- strictfp: conform to IEEE 754 floating point
- final: cannot be subclassed, java.lang.String
- abstract: can never be instantiated, is to be extended
- cannot combine these two modifier
-
Interface Declaration
- Methods are implictly public and abstract
- Method cannot be static, final, strictfp or native
- Variables defined must be public, static and final
- Extends from 1 or more interfaces, not implements
- Cannot extend anything but interface
-
Class Member
-
Access modifier
- public: all other classes, regardless of the package they belong to, can access
- private: only the class which private member is declared
-
protected/default
- subclass can see protected member only through inheritance
- Local variables
-
Nonaccess member modifier
- final method
- final arguments
- abstract method
- synchronized method
- native method
- strictfp method
- variable argument list method
- Constractor
-
variable
- primitive
- range
- reference
- local variable: always on the stack, rather than a heap
-
enum
- cannot declare enum in a method
- neither String nor int
- special kind of class
- outside class must NOT static, final, abstract, protected or private
- ; is optional
-
Wrong subject: 6, 8 and 9
- wrong again: 8
-
Chapter 2: Object Orientation
- Topic
-
Is-A
- Cannot extend more than one class
- Has-A
-
Overriding
- Argument list should exactly match
- Return type should the same as or a subtype of
- Access level can't be more restrictive
- Can throw runtime exception
- Cannot throw checked exception
- Can throw narrower/fewer exceptions
- Cannot override final/static method
-
Overloading
- must change the argument list
- can change the return type
- can change the access modifier
- can declare new/broader checked exception
-
Reference Casting
- downcasting
- upcasting
-
Implement interface
- A class can implement more than one interface
- interface self extend another interface
-
Return Type
- Covariant returns in overriding return type which can be a sub class
- Return value
-
Constructor and Instantiation
- every class MUST have a constructor
-
Constructor Chaining
-
Horse h = new Horse()
- Animal()
- Object()
-
Rules
- any access modifier
- match the class name
- no return type
- same name method doesn't make it constructor
- default constructor will be automatically generated if no constructor was typed
- default constructor ALWAYS a no-arg constructor
- once one constructor is typed, no default will be generated
- every constructor first either call this() or super()
- cannot call directly the constructor
- abstract has while interface hasn't
-
default constructor
- same access modifier as the class
-
Static variables & Method
- static method cannot access a non-static variable
- static method cannot access a non-static method
- static method cannot be overridden
-
Cohesion
- The degree to which methods in a class are related and work together to provide well-bounded behaviour
-
Chapter 3: Assignments
-
Literals Values
- 'c', false, 23.3232
-
int
-
decimal
- no prefix
-
octal
- place 0 in front of the number
-
hexadecimal
- Ox
- long: place a suffix L/l
-
floating-point
- suffix F/f/D/d
- boolean
-
character
- unicode:\u
- 16bit: 65535=2^16-1
- String
-
Assignments
-
primitive casting
- narrowing a primitive truncates the high order bits
- variable scope
- floating-point implicitly doubles
- literal integers are implicitly ints
-
Uninitialized / Unassigned
-
instance variable
- object reference: null
- byte, short, int, long: 0
- float, double : 0.0
- boolean: false
- char : '\u0000'
- array
-
local
- primitive
- object
- always MUST be initialized or a compiler error
-
assign reference to another
- copy,bit pattern
-
Passing Object Reference Variable
- a copy of the reference variable
- pass-by-value sematics
-
Array
- declare
-
construct
- one dimension
- mulitidimensional
-
anonymous array
- new int[] {1,2,3,4}
-
assignment
- primitive
-
object reference
- IS-A
-
Initialization block
- static init
-
instance init
- after super-constructor
- before the constructor
- can be more than one
- run in order --> top-down
-
Wrapper
- Boolean:boolean
- Byte:byte
- Character:char
- Double:double
- Float:float
- Integer:int
- Long:long
- Short:short
-
utitilies
-
valueOf()
- take a string return a wrapped object, throw NumberFormatException
-
parseXXX()
- take a string return primitive, throw NumberFormatException
-
xxxValue()
- no argument return primitive
-
autoboxing
-
==
- Boolean
- Byte
- Character from \u0000 to \u007f
- Short/Integer from -128 to 127
- ALWAYS be == when their primitive values are the same
-
condition
- wherever u can normally use a primitive or wrapped object
- immutable
-
Overloading
-
boxing
- widening
- autoboxing
-
var-args
- widening
- var-args
-
boxing vs var-args
-
var-args is more loose
- so boxing beats var-args
- widening reference variables
-
widening + boxing
- CANNOT widen then box
- CAN box then widen
-
Garbage Collection
- heap
-
when
- can ask but no guarantees
-
how
- mark/sweep algorithm
- reference counting
-
when an object is eligible for gc
- nulling
- reassign
- isolaating
-
forcing gc
-
request: System.gc()
- java.lang.System
- java.lang.Runtime
-
finalize()
- before object is deleted by gc
- will be called only once(at most) by gc
- call finalize() can actually result in saving an object from deletion
-
Wrong Exercises: 1, 3, 5, 8, 10, 11, 12 and 14
- wrong again: 11, 12
-
Chapter 4: Operators
-
Assignment
-
primitive
- size matters
- implicit casting
- explicit casting
- reference
- compound assignment
-
Relational
- > >= < <=
-
== !=
- primitive
- reference
- enum
- instanceof
-
Arithmetic
- + - * /
- remainder: %
- String concatenation: +
- increment/decrement: ++ --
-
Conditional
- ?:
-
Logical
- bitwise
-
short-circuit
- &&
- ||
-
logical (not short-circuit)
- &
- |
- ^ (XOR)
- !
-
Wrong Exercises: 3, 6 and 8
- wrong again: N/A
-
Chapter 5: Flow Control, Exceptions, Assertions
-
Flow Control
- if else
-
switch
- char, byte, short, int, enum
-
case: compile time constant
- same type as switch expression
- only check for equality
- won't allow more than one case using the same value
- wrapped variables aren't considered as compile time constant
-
break
- case evaluated top-down
- first match case is the execution entry point
- ends untils break found or switch statement ends
- default
- while
- do while
- for
-
ehanced for
- for(declaration: expression)
-
break, continue
- unlabeled
- labeled
-
Exception
- try...catch
-
finally
- even there's a return in try block
-
define
- subclass of java.lang.Exception
-
Hierarchy
-
Object
- Throwable
- Error
- ...
- Exception
- RuntimeException
- ...
- ...
-
handling
- 8
-
match
- first looking at the catch clauses for the type
- if can't find, search the supertype of the exceptions
-
declaration
- method must either handle all checked exceptions by catch clause, or
- list each unhandled checked exception as thrown exception
- RuntimeException and Error are exempt
- rethrowing
-
override
- can throw same exception
- narrower exception
- no exception
- runtime exception
-
Common Exception and Error
- NullPointerException
- NumberFormatException
- ...
- StackOverflowError
- AssertionError
- ...
-
Assertion
- test ur assumptions during development
- but evaporates when deployed
- assert (boolean)[:string]
-
enable assertions
-
compile
- 1.4
- javac -source 1.4 \w+\.java
- 5.0
-
running
- java -ea
- java -enableassertion
-
disable
- java -da
- java -disableassertion
-
selective enabling and disabling
- java -ea -da:<packagename|classname>
-
appropriately use
- NOT use to validate arguments to a public method
- DO use to validate arguments to a private
- NOT validate command-line argument
- DO use wherever u consider are never, ever gonna happen
- NOT use that can cause side-effect
-
Wrong Exercises: 3, 7, 8, 13 and 15
- wrong again: 3, 8, 13
-
Chapter 6: Strings, I/O, Formatting, Parsing
-
String
- Immutable
- charAt, concat, equalsIgnoreCase, etc.
- StringBuffer/StringBuilder
-
I/O
- File
- FileReader
- BufferedReader
- FileWriter
- BufferedWriter
- PrintWriter
- wrap
- delete() cannot purge a non-empty directory
- renameTo() can operate directory even if it's not empty
-
Serialization
- ObjectOutput/InputStream
-
Object Graphs
- all field need to be serializable
- transient
- private void writeObject
- private void readObject
-
Inheritance
- Superclass is NOT serializeable
- statics
-
Dates, Numbers, Currency
-
java.util.Date
- 1 trillion milliseconds = 31 2/3 years
-
Calendar
- abstract class
- static factory method
- add()
- roll()
-
DateFormat
- abstract class
-
overloaded factory method
- getInstance()
- getDateInstance()
- format()
-
parse()
- ParseException
-
Locale
- Locale(String language)
- Locale(String language, String country)
-
NumberFormat
- abstract
-
overloaded static factory method
- getInstance()
- getCurrencyInstance()
-
Currency
- getInstance
-
Parsing, Tokenizing, Formatting
-
Regex
- metacharacters
- quantifiers
- escape character
-
Tokenizing
- split()
-
Formatting
- %[arg_index$][flags][width][.precision]convertion
- arg_index
-
flags
- -: left justify
- +: include a sign
- 0: pad with zeros
- ;: use locale-specifc separators
- (: enclose negative number in ()
- width
- precision
-
conversion
- b: boolean
- return true for any non-null or non-boolean argument
- c: char
- d: integer
- f: floating point
- s: string
-
Chapter 7: Generic & Collections
-
Class methods
- toString()
-
equals()
- reflexive
- symmetric
- transitive
- consitent
-
hashCode()
- a.equals(b) -> a.hashCode()==b.hashCode()
- a.hashCode()!=b.hashCode() -> a.equals(b) == false
- transient variable may cause fail
- public method
-
Collections
-
<<interface>> java.util.Collection
-
<<interface>>List
- ArrayList
- Vector
- LinkedList
- get(int index), indexOf(int index), add(int index, Object obj), etc.
- Iterator: hasNext(), next()
-
<<interface>> Set
- SortedSet
- HashSet
- LinkedHashSet
- TreeSet
-
<<interface>> Queue
- PriorityQueue
- offer(), poll(), peak()
- toArray()
-
<<interface>>Map
- SortedMap
- HashMap
- Hashtable
- TreeMap
- LinkedHashMap
-
Ordered & Sorted
- alphabetically
- ascending
- implements Comparable
- Comparator
-
utility
-
java.util.Collections
- sort()
- Comparable: compareTo()
- Comparator:compare()
- binarySearch()
- void reverse()
- reverseOrder()
- return a Comparator that sorts in reverse
-
java.util.Arrays
- binarySearch()
- sort()
- asList(T[])
-
Generic
- MUST be the exactly type in generic when initialize a generic collection
-
Methods
- method(List<? extends Base> parameter)
- method(List<? super Child> parameter)
- method(List<?> list)
- method(List<Object> list)
- ? means many possibilities
- only for reference declarations
- different
-
Class
- class SomeGeneric<T>
- class SomeGeneric<T extends Base>
- http://www.javaprepare.com/notes/collectn.html
-
Generic Methods
- public <T> void method(T t)
- public <T extends Number> void method(T t)
-
Chapter 8: Inner Class
-
inner class
-
Regular
- Static
- Method-local
- Anonymous
-
Instantiating
- Within the outer class
- Outside the outer class instance
-
Reference
- this
- Outer.this
-
Modifier
- final
- abstract
- public
- private
- protected
- static
- strictfp
-
method-local inner class
- can be ONLY instantiated only with the method
- cannot use the local variable of the method
- unless the local variables are final
- can access enclosing class private member
-
anonymous inner class
-
Plain-old
-
Flavor I
- subclass
-
Flavor II
- implementer
-
Argument-defined
- take care of the semicolon
-
static nested class
- not an inner class
- requires both outer and nested class names
- cannot access non-static members
-
Chapter 9: Threads
-
define
-
Extends java.lang.Thread
-
constructor
- Thread()
- Thread(Runnable target)
- Thread(Runnable target, String name)
- Thread(String name)
- Implements Runnable
- Thread class implements Runnable interface
-
Starting Thread
- t.start()
- A thread done when its target run() completes
- Once it has been started, it can never be started again
- Scheduler
-
States
-
New
- before start() invoked, not alive
- Runnable
- Running
- Waiting / blocked / sleeping
- Dead
-
Priorities
- 1~10
- if not explicitly set, the same as the created thread
- NEVER rely on it to guarantee the correctness
-
yield()
- allow other threads of the same priority to get their turn
-
Synchronization
- methods and blocks
- sleep doesn't release the lock
- each object has just one lock
- static method can be synchronized
-
When cannot get lock
- static synchronized always block each other
- method and lock status
- methods that access changeable fields need to be synchronized
-
Thread-Safe Class
- Collections.synchronizedList()
- Deadlock
-
Interaction
-
wait(), notify(), notifyAll()
- belong to java.lang.Object
- for a thread to call wait(), notify(), it has to acquire the lock
- wait() gives up the lock immediately
-
Wrong Exercise:2, 5, 12, 13, 16 and 17
- wrong again: 12, 16, 17
-
Chapter 10: Development
-
compiling
-
javac [option] [source files]
-
-d
- if dest dir not existed, a compiler error occurs
- would create the directory
-
launching
-
java [options] class [args]
-
system properties
- -Da=b
-
search other classes
- first, standard J2SE
- then, classpath
- packages
- relative/absolute path
-
jar files
- jar -cf
- .../jre/lib/ext
-
static imports
- import static java.lang.System.out
- SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055).chm
- SCJP_guide_exercise.txt