Summary Sun® Certified Programmer For Java 6 Study Guide - Katherine Sierra and Bert Bates
Summary Sun® Certified Programmer For Java 6 Study Guide - Katherine Sierra and Bert Bates
Frits 1 of 52 30-01-11
Chapter 1 – Declarations and Access Control..............................................................................................3
Chapter 2 – Object Orientation.....................................................................................................................10
Chapter 3 – Assignments..............................................................................................................................13
Chapter 4 – Operators...................................................................................................................................20
Chapter 5 – Flow control, Exceptions and Assertions................................................................................21
Chapter 6 – Strings I/O Formatting and Parsing.........................................................................................25
Chapter 7 – Generics and Collections.........................................................................................................32
Chapter 8 – Inner Classes.............................................................................................................................42
Chapter 9 – Threads......................................................................................................................................45
Chapter 10 – Development............................................................................................................................47
Frits 2 of 52 30-01-11
Chapter 1 – Declarations and Access Control
Identifiers
• Identifiers must start with a letter, a currency character($), or a connecting character (_).
Identifiers can’t start with a number
• After the first character, identifiers can contain any combination of letters, $’s, _’s or numbers
• No limit of the number of characters of an identifier
• You can’t use a Java keyword as an identifier
• Identifiers are case sensitive
Java Keywords:
JavaBean
The three most important features of a JavaBean are the set of properties it exposes, the set of
methods it allows other components to call, and the set of events it fires. Basically properties are
named attributes associated with a bean that can be read or written by calling appropriate methods on
the bean. The methods a Java Bean exports are just normal Java methods which can be called from
other components or from a scripting environment. Events provide a way for one component to
notify other components that something interesting has happened.
1) If the property is not a boolean, the getter method’s prefix must be get.
2) If the property is a boolean, the getter method’s prefix is either get of is.
3) The setter method’s prefix must be set.
4) To complete the name of the getter of setter, change the first letter of the property name to
uppercase, and then append it to the appropriate prefix (get, is, or set)
5) Setter methods must be marked public, with a void return type and an argument that
represents the property type
Getter method signatures must be marked public, take no arguments, and have a return type
that matches the argument type of the setter method for that property
1) Listener method used to “register” a listener with an event source must use the prefix add,
followed by the listener type. For example, addActionListener(ActionListener l) is a valid
name for a method that an event source will have to follow others to register for
ActionEvents
XxxEvent addXxxListener
2) Listener method names used to remove (“unregister”) a listener must use the prefix remove,
Frits 3 of 52 30-01-11
followed by the listener type. removeActionListener(ActionListener l)
XxxEvent removeXxxListener
3) The type of listener to be added of removed must be passed as the argument to the method.
1) There can be only one public class per source code file
2) Comments can appear at the beginning or end of any line in the source code file
3) If there is a public class in a file, the name of the file must match the name of the public class.
4) Package statement must be the first statement in the source code file.
5) Import statement between the package statement and the class declaration
6) Import & Package statement apply to all classes in the file
7) A file can have more than one nonpublic class
8) Files with no public classes can have a name that does not match any of the classes in the
file
Class Modifiers
Acces modifiers:
1) public
2) protected (only Inner Classes)
3) private (only Inner Classes)
Frits 4 of 52 30-01-11
Interface:
• All methods are by default public abstract although it doesn’t have be mentioned
• All variables are public, static and final by default
• Because interface methods are abstract, they cannot be marked final, strictfp or native
• An interface can extend one or more other interfaces
• An interface can extend extend anything but another interface
• An interface cannot implement another interface or class
• An interface must be declared with the keyword interface
• Interface types can be used polymorphically
• A constant is declared by public static final but the keywords don’t have to appear in the interface-
file
example:
--------------------------
package foo;
public class Parent {
protected String pa = "vader";
protected String getPa() {
return pa;
}
protected void setPa(String pa) {
this.pa = pa;
}
}
---------------------------
package foo;
public class Child extends Parent {}
---------------------------
package baa;
import foo.Child;
Frits 5 of 52 30-01-11
}
---------------------------
final
• final methods: cannot be overridden in a subclass
• final arguments of methods: cannot be changed (reassigned) a new value inside the method
• final class: cannot be sub-classed
• final member variable: cannot be reassigned a new value and has to be initialized when an
instance is created and before the constructor completes.
abstract
• abstract method is a method that has been declared but not implemented
• In there is one abstract method then the class has to be declared abstract
• The first concrete subclass must implement all abstract methods of the super-class
• An abstract method ends in a semicolon instead of curly braces
• If an abstract class extends another abstract class it doesn’t have to define or implement the
abstract methods
• A combination of abstract and final is not possible (although an abstract class can have a final
non-abstract method)
• A combination of abstract and private is not possible -> abstract means it has to be overridden,
private means it is not possible to override because it is not visible
synchronized
• The method can only be accessed by one thread at a time
• It can be combined with the 4 access modifiers (public, default, private, protected)
native
• the method is implemented in a platform dependent code (often C)
• the body must contain a semicolon (= not implemented)
strictfp
• forces floating points to adhere to the IEEE 754 standard
• only for classes and methods, not variables
static
• will create a class variable or a class method that is independent of any instances created for the
class
• a static instance variable is not possible: because it will be of the class not of the instance
transient Variable
• It is skipped by the JVM when serializing the object
volatile Variable
• Tells the JVM that the thread accessing the variable has to reconcile its own copy of the variable
with the master copy in memory
Variable Declarations
1) char
2) boolean
3) byte
Frits 6 of 52 30-01-11
4) short
5) int
6) long
7) double
8) float
Declaring an Array
• int[] key
• int key[]
• never include a size when declaring an Array
Frits 7 of 52 30-01-11
Enums
• Enums can have instance variables, methods and constructors
• An enum has to start with the declaration of values
• A constructor of an enum cannot access a non-final static field
• The compiler doesn’t add a no-argument constructor, if there is another constructor
• An enum has a values() method returning an array with values
• An enum has an ordinal() method returning its position in the enum declaration.
• An enum has an valueOf methode to convert a String to the corresponding enum value.
• Enums can have constructors but can never be invoked directly
• Enum constructor can only be private or default
• The constructor can have more than one argument
• Enum constructors can be overloaded
• Look out for the semicolon “ ;” if after the constants there is more code (variables, methods,
constructors)
• An enum value cannot be a string (e.g. enum Bla {“a”, “b”} is not possible)
• The values of an enum can be considered as constants (public final static).
• A value of an enum is not a String or an int (see example: BIG is of type CoffeeSize)
Frits 8 of 52 30-01-11
Enum can be declared in it’s own file (CoffeeSize.java):
public enum CoffeeSize { BIG, HUGE, OVERWHELMING };
Frits 9 of 52 30-01-11
Chapter 2 – Object Orientation
Reference Variables
• A reference variable can be of only one type, and once declared, can never be changed
• A reference is a variable, so it can be reassigned to different objects (unless declared final)
• A reference variable’s type determines the methods that can be invoked on the object the variable
is referencing (this is known at compile time)
• A reference variable can refer to any object of the same type as the declared reference, or it can
refer to a subtype of the declared type (passing the IS-A test)
• A reference variable can be declared as a class type or as an interface type. If the reference
variable is declared as an interface type, it can reference any object of any class that implements
the interface (passing the IS-A test)
Overloaded methods
Frits 10 of 52 30-01-11
Which method is called
• Which overridden version of the method to call is decided at runtime based on the object type.
• Which overloaded version of the method to call is based on the reference type of the argument
passed at compile time
Implementing an Interface
• Provide concrete implementations for all the methods from the declared interface
• Follow all the rules for legal overrides
• Declare no checked exceptions on implementation methods other than those declared by the
interface method, or subclasses of those declared by the interface method.
• Maintain the signature of the interface method, and maintain the same return type (or a subtype).
• If the implementing class is abstract, then the methods don’t have to appear in that class but in
the first concrete class in the inheritance tree
• Downcasting: casting down the inheritance tree (explicitly declare the type)
• Upcasting: casting up the inheritance tree (implicitly: you don’t have to type in the cast)
• You can override a method and change the return type as long as the return type is a subclass of
the one declared in the overridden method
1) You can return null in method with an object reference return type
2) An array is a legal return type
3) In a method with a primitive return type, you can return any value or variable that can be
implicitly converted to the declared type
4) In a method with a primitive return type, you can return any value or variable that can be
explicitly cast to the declared return type
5) You must not return anything from a method with a void return type
6) In a method with an object reference return type, you can return any object type that can
be implicitly cast to the declared return type
Constructors
Frits 11 of 52 30-01-11
3) Constructors must not have a return type
4) It’s legal to have a method with the same name as the class
5) If you don’t type a constructor into you class code, a default constructor will be
automatically be generated by the compiler
6) The default constructor is always a no-argument constructor
7) If you want a no-argument constructor and you have typed any other constructor(s) into
your class code, the compiler won’t provide the no-argument constructor
8) Every constructor has, as its first statement, either a call to an overloaded constructor
(this() ) or a call to the super-class constructor (super())
9) If you create a constructor, and you do not have an explicit call to super() or an explicit call
to this(), the compiler will insert a no-argument call to super() . (if there is no no-argument
constructor in the super-class, a compile error will be generated).
10) A call to super() can be either a no-argument call or can include arguments passed to the
super constructor
11) A no-argument constructor is not necessarily the default constructor, although the default
constructor is always a no-argument constructor
12) You cannot make a call to an instance method, or access an instance variable, until after
the super constructor runs
13) Only static variables and methods can be accessed as part of the call to super() or this().
14) Abstract classes have constructors, and those constructors are always called when a
concrete subclass is instantiated
15) Interfaces do not have constructors.
16) The only way a constructor can be invoked is from within another constructor.
• Coupling: is the degree that one class knows about another (loose coupling is better, use the API)
• Cohesion: used to indicate the degree to which a class has a single, well focused purpose (high
cohesion is better, easier to maintain: less frequently changed)
Frits 12 of 52 30-01-11
Chapter 3 – Assignments
Primitive assignments
• Octal literals begin with a ‘0’: example: int nine = 011; (decimal 9)
• Hexadecimal literals begin with a ‘0X’ or ‘0x’ example: int fteen = 0xf; (decimal 15)
• Floating point by default doubles, if float: example: float f = 34.45544F;
• Chars, Unicode (16 bits) example: char N = ‘\u004E’;
• Chars 0 to 65000, compile error without cast example: char c = (char) 70000;
Casting
Implicit cast
When you are widening a conversion: from a byte to an int
Explicit cast
When you are narrowing a conversion: from a double to a float
- Adding two bytes can’t be assigned to a byte without a cast. The result of a calculation with
operands of type smaller then int will be promoted to an int, that is why the cast is necessary.
byte a = 10;
byte b = 2;
byte c = (byte) (a + b); // you have to put the explicit cast
Scope of variables
1) Static variables have the longest scope; they are created when the class is loaded, and they
survive as long as the class stays loaded in the JVM
2) Instance variables are the next most long-lived; they are created when a new instance is created,
and they live until the instance is removed
3) Local variables are the next; they live as long as the method remains on the stack
4) Block variables live only as long as the code block is executing
Frits 13 of 52 30-01-11
Default values for Primitive types and Reference types and Static variables
Array elements are always initialized with default values like instance variables
Static member variables are also initialized with default values like instance variables
Pass-By-Value
The called method can’t change the caller’s variable (it gets its own copy)
1. when the variable is a primitive , the method gets its local copy and it can’t change the
original variable (primitive)
2. when the variable is a reference , the method can’t reassign the original reference variable
(although it can change the contents of the object referred to)
Arrays
Declaring:
1) int[] key;
2) int key [];
Initializing
1) An array with primitives: its elements are always with default values (0, 0.0, false, ‘\u0000’)
2) Declaring constructing and initializing at once: int[] [] myList = {{5,2,4,7}, {9,2}, {3,4}};
Init Blocks
Frits 14 of 52 30-01-11
constructors code:
example:
public class Parent {
static {
System.out.println("Staticblock Parent ");
}
{ System.out.println("Initblock Parent "); }
public Parent() {
System.out.println("Constructor Parent ");
}
static {
System.out.println("Staticblock Parent 2");
}
}
class Child extends Parent {
static {
System.out.println("Staticblock Child ");
}
{ System.out.println("Initblock Child "); }
public Child() {
this("A");
System.out.println("Constructor Child ");
}
public Child(String a){
System.out.println("Constructor Child " + a);
}
public static void main(String args[]) {
new Child();
}
{ System.out.println("Initblock Child 2"); }
}
Output:
Staticblock Parent
Staticblock Parent 2
Staticblock Child
Initblock Parent
Constructor Parent
Initblock Child
Initblock Child 2
Constructor Child A
Constructor Child
Wrapper Classes
Frits 15 of 52 30-01-11
Wrapper Methods
To save memory two instances of the following wrapper objects will always be == when their
primitive values are the same:
Integer i3= 10;
Integer i4= 10;
if (i3==i4) {
System.out.println("Same");
}
This will print Same
Watch out: this is not the case if you create the objects yourself
Integer i3=new Integer(10);
Integer i4=new Integer(10);
if (i3==i4) {
System.out.println("Same");
}
This won’t print anything
Autoboxing
Autoboxing: the java compiler automatically does boxing and unboxing where necessary
Frits 16 of 52 30-01-11
Widening
The JVM tries to make a match, but if the match can’t be made it looks for the method with the
smallest argument that is wider than the parameter.
example:
public void increase (int i){}
public void increase (long i){}
Frits 17 of 52 30-01-11
Widening an Boxing is not allowed
example:
public void increase (Long i){}
Frits 18 of 52 30-01-11
Rules widening and boxing
Garbage collector
1) Forcing it System.gc();
2) Runtime.getRuntime().gc();
3) Strings are never gc-ed as they are in a String-pool
Object.finalize()
- For any given object finalize() will be called only once (at most) by the garbage collector
- Calling finalize() can actually result in saving an object from deletion
- There is no guarantee that the method will ever run
- Exceptions during execution of the method are swallowed
Garbage Collection
An object is eligible for garbage collection when no live thread can access it.
This happens when
• a reference variable that refers to the object is set to null.
• a reference variable is reassigned to another object.
• objects created in a method (and not returned by the method) after the method finishes
• islands of isolation, there is no reference to the island of objects
Frits 19 of 52 30-01-11
Chapter 4 – Operators
- There are six relational operators: <, <=, >, >=, !=, ==
- The instanceof operator is for object references, for interfaces if any of the superclasses
implements the interface
- The | of & always evaluate both operands
- The ^ is the exclusive or : only true if exactly one of the operands evaluate true
- String Concatenator: if one of the operands is String it will concatenate the operands
System.out.println(4 + 5 + “ “); // prints 9, + is left associative
System.out.println(4 + “ ” + 5); // prints 45
Frits 20 of 52 30-01-11
Chapter 5 – Flow control, Exceptions and Assertions
Flow Control
if
if (booleanExpression) statement1
else if (booleanExpression) statement2
..
else statement3
switch
switch (expression) {
case constant1: code block
case constant2: code block
default: code block
}
Loops
for
Frits 21 of 52 30-01-11
System.out.println(i + “not allowed”); // i is out of scope!!
example2:
int i;
for (i = 0; i < 5 ;i++) System.out.println(“ja”);
System.out.println(i + “allowed”); // i is in scope!!
- Enhanced loop is for arrays and collections:
for (declaration ; expression)
example:
void playSongs(Collection<Song> songs) {
for ( Iterator< Song > i = songs.iterator(); i.hasNext(); )
i.next().play();
}
can be rewritten like this:
void playSongs(Collection<Song> songs) {
for ( Song s:songs )
s.play();
}
- break: stops the entire loop
- continue: go to the next iteration
- Labelled statements: continue and break statements must be inside a loop that has the same
label name; otherwise the code won’t compile
Exceptions
try {
// do stuff
} catch (someException) {
// do exception handling
} finally {
// do clean up
}
Frits 22 of 52 30-01-11
StackOverflowError method recurses to deeply JVM
NoClassDefFoundError JVM can’t find a .class file JVM
IllegalArgumentException method gets an argument formatted Programmatically
differently then the method expects
IllegalStateException state of the environment doesn’t match Programmatically
the operation being attempted. e.g.
Scanner that has been closed
NumberFormatException thrown when a string is not convertable Programmatically
to a number
AssertionError thrown when the statement’s boolean Programmatically
test returns false
Assertion
- if you use assert as an Identifier then you have to tell the compiler:
- javac –source 1.3 bla/TestJava.class -> it will issue warnings that assert is used as a
keyword
- javac –source 1.4 bla/TestJava.class -> it will issue errors (assert is a keyword)
Frits 23 of 52 30-01-11
- javac bla/TestJava.class -> it will issue errors (assert is a keyword)
- javac –source 1.5 bla/TestJava.class -> it will issue errors (assert is a keyword)
- javac –source 5 bla/TestJava.class -> it will issue errors (assert is a keyword)
- if you use assert as an Keyword in java 1.3
- javac –source 1.3 bla/TestJava.class -> it will issue errors (keyword doesn’t exist in
1.3)
Enabling assertions
Frits 24 of 52 30-01-11
Chapter 6 – Strings I/O Formatting and Parsing
Strings
- Are immutable e.g. String x = “abcdef”; x = x.concat(“g”); will create a new String “abcdefg” and
the reference to the original Strings are lost.
- String s = new String(“abc”); will create two objects : a String object in (non-pool) memory and a
literal in the pool-memory
Methods on Strings
substring(int a, int b) a – starting index (zero based ), b – ending index (non zero based)
example:
public static void main(String args[]) {
String string = "substring";
// index 0(s) 1(u) 2(b) 3(s) 4(t) 5(r) 6(i) 7(n) 8(g)
System.out.println(string.substring(1,4)); // prints ”ubs”
}
String x = “test”;
System.out.println(x.length); // compile error
- Use the classes when there is a lot of string manipulations (e.g. File I/O)
- Stringbuffer’s methods are thread safe
- Same API
- substring(a,b) returns a string so it cannot be used inside a chain
Methods:
public synchronized StringBuffer append(String s) will update the value of the object (takes also
other types like int, float…)
public StringBuilder delete(int start, int end) will remove substring from start to end -> both
zero-based
public StringBuilder insert(int offset, String s) insert string in object at offset (zero-based)
public synchronized StringBuffer reverse() reverses the value of the StringBuffer object
Frits 25 of 52 30-01-11
public String toString() returns the value of the StringBuffer object
Frits 26 of 52 30-01-11
Console
java.io.Console Description
public String readLine() Reads a single line of text from the console.
public String readLine(String fmt, Object... args) Provides a formatted prompt, then reads a single
line of text from the console.
public char[] readPassword(String fmt, Object... Provides a formatted prompt, then reads a
args) password or passphrase from the console with
echoing disabled.
public char[] readPassword(String fmt, Object... Provides a formatted prompt, then reads a
args) password or passphrase from the console with
echoing disabled.
public Console format(String fmt, Object... args) Writes a formatted string to this console's output
stream using the specified format string and
arguments.
public Console printf(String format, Object... args) A convenience method to write a formatted string
to this console's output stream using the specified
format string and arguments.
public PrintWriter writer() Retrieves the unique PrintWriter object associated
with this console.
public Reader reader() Retrieves the unique Reader object associated
with this console.
public void flush() Flushes the console and forces any buffered
output to be written immediately.
Serialization
example:
import java.io.*
Frits 27 of 52 30-01-11
public class SerializeCat {
To add extra functionality to the (default) serialization method, use the following methods:
private void writeObject (ObjectOutputStream oo)
private void readObject (ObjectInputStream oi)
Don’t close the ObjectOutputStream in those methods!
Date
Default constructor and a constructor with a long (number of miliseconds since 1970)
Calendar
No constructor, but a factorymethod
c.getInstance()
c.getInstance(Locale l)
Dateformat
No constructor, but a factorymethod
df.getInstance()
df.getInstance(Locale l)
df.getDateInstance()
Frits 28 of 52 30-01-11
df.getDateInstance(Style) // Style is for instance DateFormat.SHORT
df.getDateInstance(Style s, Locale l)
df.getDateInstance(Locale l)
df.getTimeInstance()
df.getTimeInstance(Locale l)
Locale
Constructor Locale (String Language, String Country)
Constructor Locale (String Language)
NumberFormat
No constructor, but a factorymethod
nf.getInstance()
nf.getInstance(Locale l)
nf.getCurrencyInstance()
nf.getCurrencyInstance(Locale l)
A regex search runs from left to right and once a character has been used in a match it can’t be
reused . example: “aba” in “abababa” has two matches: 0 4
MetaCharacters
\d a digit
\s whitespace character
\w a word character (numbers, letters or “_”)
Quantifiers
+ One or more [1-n]
* Zero or more [0-n]
? Zero or one [0-1]
Frits 29 of 52 30-01-11
^ Negate
. Any character
example:
source: “1 a12 234b”
pattern: \d+
output:
01
3 12
6 234
Greedy or reluctant
Greedy Reluctant
? ?? zero or once
* *? zero or more
+ +? one or more
example:
source “yyxx.xyxx”
pattern “.”
output: 0 1 2 3 4 5 6 7 8
source “yyxx.xyxx”
pattern “\\.” // not the metacharacter . but it searches for a “.”
output: 4
} while (token!=null);
output:
1 token: ab
2 token: ab
3 token: ab
4 token: ba
5 token: null
Tokenizing
String.split() – returns String array
example:
String [] token = “ab ab ab, abc, a”.split(“,”);
for (String a: token) {
System.out.println(“>” + a + “<”);
}
output:
>ab ab ab<
> abc<
Frits 30 of 52 30-01-11
> a<
example:
boolean b, b2;
int i;
String hits = " ";
String toBeScanned = "1 true 34 hi";
Scanner s2 = new Scanner(toBeScanned);
format string:
%[arg_index$][flags][width][.precision]conversion
flags (5)
“-” left justify
“+” include a sign (+ or -) with this argument
“0” pad this argument with zeroes
“,” use locale-specific grouping separators (i.e. the comma in 123,345)
“(“ enclose negative numbers in parentheses
conversion (5)
b boolean
c char
d integer
f floating point
s string
Example:
int i1 = -123;
int i2 = 12345;
Frits 31 of 52 30-01-11
Chapter 7 – Generics and Collections
Hashing
1) Whenever it is invoked on the same object more than once during an execution of a Java
application, the hascode() method must consistently return the same integer, provided no no
information used in the equals() comparisons on the object is modified.
2) If two objects are equal according to the equals (object) method, then calling the hashcode()
method on each of the two objects must produce the same integer result.
3) It is not required that if two objects are considered unequal according to the equals() method,
then calling the hascode() method on each of the two objects must produce the distinct integer
results
Frits 32 of 52 30-01-11
Collections
Sorted – The order in the collection is determined according to some rule or rules known as the sort
order. A sorted collection uses the compareTo() method during insertion
Sorted Collections
TreeMap By natural order or custom comparison rules (uses compareTo() method)
TreeSet By natural order or custom comparison rules (uses compareTo() method)
PriorityQueue By to-do order
Ordered Collections
LinkedHashMap By insertion order or last access order
LinkedHashSet By insertion order
ArrayList By index
Vector By index
LinkedList By index
Unordered Collections
HashMap
Hashtable
HashSet
Frits 33 of 52 30-01-11
11 Classes & 9 Interfaces & 2 Utility Classes
Frits 34 of 52 30-01-11
When you override equals you must take an object as an argument
When you override compareTo you should take the object type you are sorting (object is allowed):
example:
class DVDinfo implements Comparable<DVDInfo>{
public int compareTo (DVDInfo d){}
}
java.lang.Comparable java.util.Comparator
int thisObject.compareTo(anotherObject) int compare(thisObject, anotherObject)
You must modify the class whose instances you You build a seperate class from the class whose
want to sort instances you want to sort
One sort sequence Many sort sequences (by creating many
comparators)
Implemented frequently in the API by: String, Meant to be implemented to sort instances of
Wrapper Classes, Date, Calendar... third-party classes
Frits 35 of 52 30-01-11
Generic Iterator (no cast required)
java.util.Arrays Description
static List asList(T[]) Convert an array to a list (and bind them)
static int binarySearch(Object[], key) Search a sorted array for a given value, return an
static int binarySearch(primitive[], key) index or an insertion point
static int binarySearch(T[], key, Comparator) Search a Comparator-sorted array
static boolean equals(Object[], Object[]) Compare two arrays and determine if their
static boolean equals(primitive[], primitive[]) contents are equal
public static void sort(Object[]) Sort the elements of an array by natural order
public static void sort(primitive[])
public static void sort(T[], Comparator) Sort the elements of an array using a Comparator
public static String toString(Object[]) Create a string containing the elements of an
public static String toString(primitive[]) array
java.util.Collections Description
static int binarySearch(List, key) Search a sorted list for a given value return an
static int binarySearch(List, key, Comparator) index or an insertion point
static void reverse(List) Reverse the order of the elements of the list
static Comparator reverseOrder() Return a Comparator that sorts the reverse of the
static Comparator reverseOrder(Comparator) collection’s current sort sequence
static void sort(List) Sort a List by natural order or by Comparator
static void sort(List, Comparator)
Frits 36 of 52 30-01-11
Method Overview for PriorityQueue
Method Description
offer() Add an object to the queue
peek() Retrieves the element at the head of the queue
poll() Retrieves and removes the element at the head of the queue
Method Description
Comparator<? super E> comparator() Returns the comparator used to order the elements in this
set, or null if this set uses the natural ordering of its
elements.
E first() Returns the first (lowest) element currently in this set.
E last() Returns the last (highest) element currently in this set.
SortedSet<E> headSet(E toElement) Returns a view of the portion of this set whose elements are
strictly less than toElement.
SortedSet<E> tailSet(E fromElement) Returns a view of the portion of this set whose elements are
greater than or equal to fromElement.
SortedSet<E> subSet(E fromElement, Returns a view of the portion of this set whose elements
E toElement) range from fromElement, inclusive, to toElement, exclusive.
example:
public class SortedSetMap {
private NavigableSet<String> alphaLijst = new TreeSet<String>();
public SortedSetMap(){
fillLijst();
}
public NavigableSet<String> getAlphaLijst() {
return alphaLijst;
}
public void setAlphaLijst(NavigableSet<String> alphaLijst) {
this.alphaLijst = alphaLijst;
}
private void fillLijst (){
alphaLijst.add("E");
alphaLijst.add("A");
alphaLijst.add("B");
alphaLijst.add("D");
alphaLijst.add("F");
}
}
Frits 37 of 52 30-01-11
Method Description
Iterator<E> descendingIterator() Returns an iterator over the elements in descending order
NavigableSet<E> descendingSet() Returns a reverse order view of the elements in this set
E ceiling(E e) Returns the least element in this set greater than or equal to the
given element, or null if there is no such element.
E higher(E e) Returns the least element in this set strictly greater than the
given element, or null if there is no such element.
E lower(E e) Returns the greatest element in this set strictly less than the
given element, or null if there is no such element.
E floor(E e) Returns the greatest element in this set less than or equal to the
given element, or null if there is no such element.
E pollFirst() Retrieves and removes the first (lowest) element, or returns null
if this set is empty.
E pollLast() Retrieves and removes the last (highest) element, or returns null
if this set is empty.
NavigableSet<E> headSet(E Returns a view of the portion of this set whose elements are less
toElement, boolean inclusive) than (or equal to, if inclusive is true) toElement
NavigableSet<E> tailSet(E Returns a view of the portion of this set whose elements are
fromElement, boolean inclusive) greater than (or equal to, if inclusive is true) fromElement
NavigableSet<E> subSet(E Returns a view of the portion of this set whose elements range
fromElement, boolean from fromElement to toElement.
fromInclusive, E toElement,
boolean toInclusive)
Method Description
NavigableMap<K,V> descendingMap() Returns a reverse order view of the mappings contained in
this map
Frits 38 of 52 30-01-11
fromKey, boolean inclusive) greater than (or equal to, if inclusive is true) fromKey
SortedMap<K,V> subMap(K fromKey, Returns a view of the portion of this map whose keys range
K toKey) from fromKey, inclusive, to toKey, exclusive.
firstEntry Map.Entry<K,V> firstEntry() Returns a key-value mapping associated with the least key in
this map, or null if the map is empty.
Map.Entry<K,V> pollFirstEntry() Removes and returns a key-value mapping associated with
the least key in this map, or null if the map is empty.
Map.Entry<K,V> lastEntry() Returns a key-value mapping associated with the greatest
key in this map, or null if the map is empty.
Map.Entry<K,V> pollLastEntry() Removes and returns a key-value mapping associated with
the greatest key in this map, or null if the map is empty.
K floorKey(K key) Returns the greatest key less than or equal to the given key,
or null if there is no such key.
K ceilingKey(K key) Returns the least key greater than or equal to the given key,
or null if there is no such key.
K higherKey(K key) Returns the least key strictly greater than the given key, or
null if there is no such key.
K lowerKey(K key) Returns the greatest key strictly less than the given key, or
null if there is no such key.
Map.Entry<K,V> floorEntry(K key) Returns a key-value mapping associated with the greatest
key less than or equal to the given key, or null if there is no
such key.
Map.Entry<K,V> ceilingEntry(K key) Returns a key-value mapping associated with the least key
greater than or equal to the given key, or null if there is no
such key.
Map.Entry<K,V> higherEntry(K key) Returns a key-value mapping associated with the least key
strictly greater than the given key, or null if there is no such
key.
Map.Entry<K,V> lowerEntry(K key) Returns a key-value mapping associated with the greatest
key strictly less than the given key, or null if there is no such
key.
Generic Types
Generic Collection
List<String> myList = new ArrayList <String>()
- If you add anything to a typed collection other than the generic type you will get a compile error
- If you remove something from the collection, you don’t need a cast
- With arrays there is a runtime Exception – ArrayStoreException if you put the wrong thing in an
array
A generic Iterator
List<Transaction> myList;
Iteractor <Transaction> i = myList.iterator();
Frits 39 of 52 30-01-11
A generic Comparator
public class CompareTransaction implements Comparator <Transaction> {
public int compare (Transaction t1, Transaction t2){
}
}
You are able to put subtypes of the generic type into a generic collection:
List<Animal> myAnimal = new ArrayList<Animal>()
myAnimal.add(new Dog());
myAnimal.add(new Cat());
lijst can be assigned a collection that is a subtype of List and typed for Animal or anything that
extends Animal, but nothing will be added to the collection.
lijst can be assigned any List with a generic type that is of type Dog or a supertype of Dog.
Frits 40 of 52 30-01-11
AnimalDoctorGeneric doc = new AnimalDoctorGeneric();
List<Animal> myList = new ArrayList<Animal>();
myList.add(new Dog());
doc.addAnimal(myList);
}
}
Generic Declarations
Frits 41 of 52 30-01-11
Chapter 8 – Inner Classes
example:
class MyOuter {
private int x = 7;
class MyInner {
public void seeOuter() {
System.out.println(“Outer x is: “ + x);
} // end method seeOuter
} // end class MyInner
} // end class MyOuter
Instantiating from within the outer class (via a method on the outer instance):
class MyOuter {
private int x = 7;
class MyInner {
public void seeOuter() {
System.out.println(“Outer x is: “ + x);
} // end method seeOuter
} // end class MyInner
class MyInner {
public void seeOuter() {
System.out.println(“Outer x is: “ + x);
} // end method seeOuter
} // end class MyInner
} // end class MyOuter
Inner.Outer.java
public class InnerOuter {
Frits 42 of 52 30-01-11
MyOuter.MyInner in = out.new MyInner();
MyOuter.MyInner inOneLine = new MyOuter().new MyInner();
in.seeOuter();
inOneLine.seeOuter():
}
Referencing the Inner or Outer instance from within the inner class
class MyOuter {
private int x = 7;
class MyInner {
public void seeOuter() {
System.out.println(“Outer x is: “ + x);
System.out.println(“Inner reference is: “ + this);
System.out.println(“Outer reference is: “ + MyOuter.this);
example:
class MyOuter {
private int x = 7;
void doStuff() {
class MyInner {
public void seeOuter() {
System.out.println(“Outer x is: “ + x);
} // end class MyInner
} // end of doStuff()
• Method Local Inner Class cannot use (non-final) local variables of the method (stack versus
heap)
• Method Local Inner Class can use final local variables
• A Method Local Inner Class defined in a static method has only access to static members
Frits 43 of 52 30-01-11
example flavor one:
class Popcorn {
public void pop() {
System.out.println(“popcorn”);
}
}
class Food {
Popcorn p = new Popcorn () {
public void pop() {
System.out.println(“anonymous popcorn”);
}
}; // close with SEMICOLLON
}
• The Popcorn reference variable refers not to an instance of Popcorn, but to an instance of an
anonymous (unnamed) subclass of Popcorn .
example:
class BigOuter {
static class Nest { void go() { System.out.println(“hi”); } }
}
class Broom {
static class B2 { void goB2() { System.out.println(“hi2”); } }
public static void main (String[] args) {
BigOuter.Nest n = new BigOuter.Nest();
n.go();
B2 b2 = new B2();
b2.go();
}
}
Frits 44 of 52 30-01-11
Chapter 9 – Threads
1) sleep() (Static)
2) yield() (Static)
• make the current running thread go back to Runnable and let other threads with equal priority do
their job
3) join()
• Blocks the current running thread until this one (the one joining) has finished.
• If called from the main() method it will block main() until the one joining is finished.
4) setPriority()
5) start()
• starts a thread
6) interrupt()
• Calling interrupt on a thread will cause an interruptedException only if the thread on which it is
called is blocked because of :
• wait()
• join()
• sleep()
Deamon Thread
• A thread is either a user thread or a deamon thread. t.setDeamon(true); creates a deamon thread
• steDeamon has to be called before the thread is started
• The JVM exits if all running threads are deamon threads
Frits 45 of 52 30-01-11
Methods of the Object class
States of a Thread
Synchronizing Code
Locking
• Threads calling non-static synchronized methods in the same class will only block each other if
they are invoked using the same instance. They lock on the ‘this’ instance, so if called on different
instances they will get two different locks which do not interfere with each other
• Threads calling static synchronized methods in the same class will always lock each other
• A static synchronized method and a non-static synchronized method will never block each other
(one on a object-instance and one on the class-instance)
Thread Safe
• Watch out with class that has thread-safe methods: each individual method is thread-safe but
calling two methods in a row aren’t
Frits 46 of 52 30-01-11
Chapter 10 – Development
Java’s compiler
example:
package collectionutils;
public class Java6Console {}
java -D
java -DcmdProp=cmdVal is adding an extra system property. (use the getProperty to get it)
java -DcmdProp=cmdVal TestProps x q is adding a system property and passing arguments x and 1
to TestProps
System.getProperty(“FLAG”); // returns the value of the system property
System.getProperty(“FLAG”, “false”); // returns the value of the system prop. and if it doesn’t exist
false
Valid main() declarations:
• static public void main(String[] args)
• public static main void(String... x)
• public static main void(String bla_bla[])
Frits 47 of 52 30-01-11
Java search algorithm
Both java and javac use the same basic search algorithm:
• They both have the same list of places (directories) they search, to look for classes.
• They both search through this list of directories in the same order.
• As soon as they find the class they're looking for, they stop searching for that class.
• In the case that their search lists contain two or more files with the same name, the first file found
will be the file that is used.
• The first place they look is in the directories that contain the classes that come standard with
J2SE.
• The second place they look is in the directories defined by classpaths.
• Classpaths should be thought of as "class search paths " They are lists of directories in which
classes might be found.
• There are two places where classpaths can be declared:
• A classpath can be declared as an operating system environment variable . The classpath
declared here is used by default, whenever java or javac are invoked.
• A classpath can be declared as a command-line option for either java or javac. Classpaths
declared as command-line options override the classpath declared as an environment variable ,
but they persist only for the length of the invocation.
fqn = collectionutils.Java6Console
In order to run the Java6Console it has to have the package root dir as a subdir.
Frits 48 of 52 30-01-11
• dirA, then no directories are searched
If the command is java -cp .:dirA:dirA/dirB/dirC and the current dir is:
• (root), then (root), dirA and dirC are searched
• dirA, then only dirA is searched (because of the “.”, meaning current dir)
If the command is java -cp /dirA:/dirA/dirB/dirC and the current dir is:
• (root), the path is absolute so dirA and dirC are searched
Frits 49 of 52 30-01-11
• dirA, the path is absolute so dirA and dirC are searched
Jar files
create a jar file: jar -cf MyJar.jar myApp (it will take the myApp dir and all subdirs)
read a jar file jar -tf MyJar.jar
example (TestProps uses the class TestJar)
(root)\development\TestProps.java
package development;
import jarpack.TestJar;
public class TestProps {
public static void main(String[] args) {
TestJar tj = new TestJar();
System.out.println(tj.getDateAsString());
}
}
(root)\jarpack\TestJar.java
package jarpack;
import java.text.DateFormat;
import java.util.Date;
public class TestJar {
public String getDateAsString(){
DateFormat df = DateFormat.getDateInstance();
return df.format(new Date());
}
}
Frits 50 of 52 30-01-11
compile TestJar: javac -cp . jarpack\TestJar.java
Remove the files in the jarpack directory (just for the sake of the example)
Frits 51 of 52 30-01-11
(leaving out classpath entry to d.jar gives a compile error)
Static Imports
Frits 52 of 52 30-01-11