Docstoc

SCJP 5

Document Sample
SCJP 5 Powered By Docstoc
					SCJP 5.0 Study Guide:                        Louis Botterill                    31-03-2008


     1.    Basics: ........................................................................................................................................................................................................................................ 1
     2.    Enums ......................................................................................................................................................................................................................................... 2
     3.    Nested / Inner Classes:................................................................................................................................................................................................................ 2
     4.    Boxing: ....................................................................................................................................................................................................................................... 2
     5.    Asserts ........................................................................................................................................................................................................................................ 3
     6.    File I/O ....................................................................................................................................................................................................................................... 3
     7.    Serialization ................................................................................................................................................................................................................................ 3
     8.    Dates, Numbers and Currency .................................................................................................................................................................................................... 4
     9.    Regex .......................................................................................................................................................................................................................................... 4
     10.   Collections: ................................................................................................................................................................................................................................. 5
     11.   Sorting ........................................................................................................................................................................................................................................ 7
     12.   Generics ...................................................................................................................................................................................................................................... 8
     13.   Threads ....................................................................................................................................................................................................................................... 8
     14.   Development............................................................................................................................................................................................................................... 9



1.         Basics:
Identifiers, begin with letter, underscore or $, after than they can contain numbers too.
Java beans: getX, setX, isX, add, remove.

Types:

Object, has important methods such as:

boolean equals(Object obj)          // polymorphic, override this – equals must compare like type objects
void finalize()        // called only ever once, before gc (and it‘s implementation can prevent gc from happening!)
int hashCode()         // should implement for objects as hash keys, worst case it can return a constant value
final void notify()    // notify one (first) waiting thread
final void notifyAll() // notify all waiting threads
final void wait()      // wait on object lock via notify
String toString()

Scope:

public - all
protected – same package + inherited
default – same package
private – none!

class, public or default scope only
class, 0-1 public class matching file name, any number of non-public (default) classes – no file name restrictions
single abstract method means whole class must be marked as abstract

interface constants are always public static final (but these can be omitted (or included in any order) as this is the only option!)
interfaces can extend other interfaces (note, never implement!)

Constructors:

Default no-arg constructor provided if you don‘t provide any constructors.
Constructors only directly invoked by other constructors (or by new keyword).
Can‘t call super and this in the same constructor.
First statement must be a call to either this() [an overloaded constructor] or super(), compiler always adds call to super() as 1st line unless you specify it.
Instance variables only available after call to super returns (super is 1 st line).
Never inherited, therefore never overridden – only ever overloaded.
A private constructor means no default arg constructor can be invoked; even a subclass that attempts to call this (implicitly or explicitly) will fail! i.e. can‘t create object
unless other constructors are provided and invoked explicitly.

Special keywords:

transient – applied to instance variables only, means skip the variable when serialising the object.
volatile – applied to a variable only, means the value may change


Overloading:

Covariant returns in java 5.0 (e.g. return values can be subtypes (pass an is-a test))
Can‘t reduce the access modifier
Can‘t throw new or wider exceptions (can ‗not declare‘ an exception (narrower scope!))

Overriding:


Signature matching


Conversions:

try
{
       int i1 = Integer.parseInt("123");

       Integer i2 = Integer.valueOf("123");
    //Long l = Integer.valueOf("123");                           // can't do this! Integer is not a Long
}
catch (NumberFormatException ex)
{
    ex.printStackTrace();
}

int i3 = (new Integer(123)).intValue();




2.          Enums
Can be top level or within a class (but not a method!)

enum MyEnums
{
    bread(1),
    cheese(2),
    milk(3), coal(6);

      final int value;

      MyEnums(int v)
      {
          value = v;
      }

      public int getValue()
      {
          return value;
      }
}



3.          Nested / Inner Classes:
4 types (1 nested and 3 inner):

Inner class:
Declared inside another class
Can be marked with access modifies and abstract or final
Shares relationship with enclosing class instance, has access to all outer classes members (including private!)
From within the outer class, can instantiate normally as per MyInner mi = new MyInner();
From outside the outer class, can instantiate using: MyOuter mo = new MyOuter(); MyInner mi = new mo.MyInner();
In inner class, this refers to inner class instance, can reference outer class instance using MyOuter.this;

Method-Local Inner class:
Declared in a method
Can only be abstract or final (not public, private etc)
Must be instantiated – within the same method, after it is declared
Can not use variables declared within method or parameters unless they are final

Anonymous Inner class:
A class with no name declared in a statement that either subclasses a named class or implements an interface
The only methods that can be called on an anonymous inner class are those belonging to the reference variable‘s type (e.g. superclass or interface)
Extends one class or implements one interface (can‘t do more than one thing)

Static nested Classes:
Inner classes marked with static keyword
It‘s a top level nested class, not an inner class
Does not share any relationship with outer class. Don‘t need instance of outer class to create it.
User Outer.Inner syntax to instantiate, e.g. MyOuter.MyNested mn = new MyOuter.MyNested();
Can not access non-static members of outer class, can not get outer this reference as you can with Inner classes



4.          Boxing:
* Can implicitly convert from primitive to wrapper – watch out!

Wrappers can not be cast to other wrappers (i.e. do not pass an ―is a‖ test) – Integer is-not-a Short

i.e. can‘t do

Short short1 = new Short(100);

Cannot find symbol : constructor Short(int) or Short(Integer)

But this is fine

Short short1 = new Short((short)100);
Or
Long long1 = (Long)(long)myShortObj; // involves unboxing, conversion, reboxing…
5.         Asserts
assert Expression1 ;

assert if assertion enabled and expression1 evaluates to false

assert Expression1 : Expression2 ;

as above but evaluate expression2 (not void!) as the message detail for the assertion

An assertion error is a java.lang.AssertionError, a type of java.lang.Error which in turn is a type of java.lang.Throwable

Must be source level 1.4 or higher

Enable assertions with -enableassertions, or –ea - disable with –disableassertions or -da

Enable for specific packages / classes

java -ea:com.wombat.fruitbat... -da:com.wombat.fruitbat.Brickbat BatTutor
source mode 1.3 (default) — the compiler accepts programs that use assert as an identifier, but issues warnings. In this mode, programs are not permitted to use the
assert statement.
source mode 1.4 — the compiler generates an error message if the program uses assert as an identifier. In this mode, programs are permitted to use the assert statement.


6.         File I/O
Main classes:

File – abstract representation of file and path names (not an actual file!) –
 File(String pathAndFileName), File(path, filename), file.exists(), file.createNewFile(), file.delete(), file.isDirectory(), file.list(), file.mkdir(), file.renameTo()

FileReader – read characters from a file – FileReader(File), fileReader.read()
BufferedReader – Buffers up date, provides higher level methods like readLine(), construct like new BufferedReader(new FileReader(file))
FileWriter – as per FileReader – fileWriter.write(―some lovely string‖); fileWriter.flush(), fileWriter.close();
BufferedWriter

PrintWriter – Enhanced in Java5 – constructors to build from file or string. Has format(), printf(), append()

NB: Always remember IOExceptions can be thrown!

NB: New File does not create the file but a new FileWriter, PrintWriter or FileOutputStream on a File will create it – except if the directory doesn‘t exist ->
IOException: No such file or directory

NB: Streams read and write bytes, Readers and writers read and write characters. All file I/O exam questions are about characters, streams are used elsewhere – e.g.
serialization.



7.         Serialization
Main classes:

java.io.DataInputStream
java.io.DataOutputStream
java.io.FileImputStream
java.io.FileOutputStream
java.io.ObjectInputStream
java.io.ObjectOutputStream


ObjectOutputStream.writeObject(obj)
Type obj = (type)ObjectInputStream.readObject();

Classes must implement serializable

Use transient to mark a variable as not to be included in default serialisation, for example if it‘s not marked as serializable and can not be modified (final or in a library)

Then override writeObject and readObject to perform your own serialisation for transients

public void writeObject(ObjectOutputStream os)
{
        try
        {
                os.defaultWriteObject();
                os.writeInt(myTransient.getInt());
        }
        catch (Exception e) {}
}

public void readObject(ObjectInputStream is)
{
        try
            {
                        is.defaultReadObject();
                        myTransient = new MyTransient(os.readInt());
            }
            catch (Exception e) {}
}


defaultReadObject and defaultWriteObject are default implementations available when an object is marked as serializable

NB. If a superclass is marked serializable, all subclasses are serializable whether marked explicitly or not (all pass an is-a test), but unless you can see all the code it‘s
hard to know.

NB. Classes marked as serializable do not run their constructor when being deserialized. However, if a superclass is not serializable and a subclass is, the superclasses
contructor (and all subsequent constructors) will be run, the serializable subclass will still _not_ have its constructor called.

NB: serialisation is not for statics!



8.          Dates, Numbers and Currency
Own Locale:

Date d = new Date();
Date.toString(); // date and time (your locale)

Calendar c = Calendar.getInstance();
c.add(), c.roll() …

Locales:

Locale loc = new Locale();
Locale loc = new Locale(language);
Locale loc = new Locale(language, country);

Calendar c = Calendar.getInstance(loc);

Formatting dates in different locales:

DateFormat.getInstance(); // Get a default date/time formatter that uses the SHORT style for both the date and
the time.
DateFormat.getDateInstance(); // Gets the date formatter with the default formatting style for the default
locale.
DateFormat.getDateInstance(style);
DateFormat df = DateFormat.getDateInstance(style, loc); // style – DateFormat.SHORT, DateFormat.MEDIUM,
DateFormat.LONG, DateFormat.FULL

String dateString = df.format(date);

Format numbers / currency:

Locale loc = new Locale(…);
NumberFormat nf = NumberFormat.getInstance(loc);

Or

NumberFormat nf = NumberFormat.getCurrencyInstance(loc);

String s = nf.format(some number);




9.          Regex
NB: all regex \ metacharacters must be escaped as \\ in Java strings!

Example code:
java.util.regex.*

Pattern p = new Pattern(―ab‖); the regex expression
Matcher m = p.matcher(―alsdjajslda‖); // the source to match on

while (m.find())
{
  System.out.println(m.start() + ― ‖ + s.group());
}

start = start index of match (0 based), group = the matched group of characters

Meta-characters:

    char         type                                Example
    \d           digit                               ―\d‖ ―A12b‖            Starts 1 2
    \s           whitespace                          ―\s‖ ―a bc d‖          Starts 1 4
    \w           word (letter, digit, _)             ―\w‖ ―1 e 3f‖          Starts 0 2 45
 [abc]          Char match in range abc              ―[abc]‖ ―adc‖            Starts 0 2
 [a-f]          Char match a through f inc.          ―[a-f]‖ ―gfc‖            Starts 1 2
 [a-fA-F]       a through f and A through F
 +              One or more                          ―\d+‖ ―1 a12 b234‖       Groups 1 12 234
 *              Zero or more
 ?              Zero or one
 .              Any character                        ―a.c‖ ―ac abc a c‖       3 abc, 7 a c
 ^              Negate the character                 [^abc] = not ab or c



Example: find hex characters of the form 0x1ab2Ef or 0X2Efga etc

0[xX]([0-9a-fA-F])+

means find (0 x or X) and then (0-9 or a-f or A-F) 1 or more times

NB: Greedy (default for ? * and +) means search right to the end then work backwards…

e.g.

source yyxxxyxx
pattern .*xx (any char zero or more times followed by xx)

searches and matches on the LAST xx not the first XX and greedily returns yyxxxyxx

The dot . means any character, to actually specify a literal dot, we escape it to be \. (in a Java string literal that needs to be \\.)

String has a .split(regexpattern) method that produces a String[] array of the matched patterns.

Tokenising - Scanner

e.g. new Scanner(―some message to tokenise‖);

Has methods like:

hasNext() – test for next token (of any type)
nextInt() – returns all tokens as string and move forward

boolean hasNextInt() – test for next int token
int nextInt() – get next int token and move forward

can also find tokens using regex

token = s.findInLine(―some regex expr‖)

NB: Default scanner tokenising character is whitespace.

Printf

System.out.printf uses the following format string construction

%[arg_index$][flags][width][.precision]conversion char

Flags:

"-" Left justify this argument
"+" Include a sign (+ or -) with this argument
"0" Pad this argument with zeroes
"," Use locale-specific grouping separators (i.e., the comma in 123,456)
"(" Enclose negative numbers in parentheses


Conversion codes:

b   boolean
c   char
d   integer
f   floating point
s   string



10.         Collections:
Code to interfaces where possible, e.g. where the type on the right passes an ―is a‖ test for the thing on the left:

List<Integer> = new ArrayList<Integer>();

Java.util.Arrays has various sort methods

Java.util.Collections has sort methods

To use objects as keys in hash maps (HashSet, LinkedHashSet, HashMap, Hashtable, LinkedHashMap)
Override equals to provide a meaningful comparison of objects. Override hash code so that hash codes are typically different for different objects but always the same
for objects that are equal.

Iterating – can use enhanced for loop or iterators

hasNext (check if there is a next) and next (get next item)




                                                               Collection
                                                               <interface>




                          Set                                                         List                          Queue
                      <interface>                                                 <interface>                     <interface>




        HashSet                   SortedSet
        <class>                  <interface>




     LinkedHashSet                  TreeSet                   ArrayList             Vector            LinkedList           PriorityQueue
        <class>                     <class>                    <class>              <class>            <class>                <class>


                       Object                                                        Map
                       <class>                                                    <interface>



                                                                                                    SortedMap
                                                                                                    <interface>
            Arrays               Collections
            <class>               <class>

                                                              Hashtable                  HashMap                   TreeMap
                                                               <class>                    <class>                   <class>



                                                                                     LinkedHashMap
                                                                                         <class>


Main Classes:

Class java.util.Arrays:

Main methods:

static list asList(T[]);
static int binarySearch(Object[], key);
static int binarySearch(primitive[], key);
static int binarySearch(T[], key, comparator);
static Boolean equals(Object[], Object[]);
static Boolean equals(primitive[], primitive[]);
static void sort(Object[]);
static void sort(primitive[]);
static void sort(T[], Comparator);


Class java.util.Collections:

static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key)
static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)

static <t> Comparator<T> reverseOrder()

Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

static <t> Comparator<T> reverseOrder(Comparator<T> cmp)

Returns a comparator that imposes the reverse ordering of the specified comparator.

static <T extends Comparable<? Super T>> void sort(List<T> list)

Sorts the specified list into ascending order, according to the natural ordering of its elements.
static <T> void sort(List<T> list, Comparator<? super T> c)

Sorts the specified list according to the order induced by the specified comparator.

Remember, must always sort before searching!

Interfaces:

Collection – defines: add, addAll, clear, contains, isEmpty, iterator, remove, removeAll, size, toArray etc
Implements - Iterable
Implemented By – BlockingQueue, List, Queue, Set, SortedSet etc

List – defines: add, get, set, remove, indexOf, remove all, toArray, size etc
Implements -
Implemented by - ArrayList, LinkedList, Stack, Vector etc

Queue – defines: element, offer, peek, poll, remove
Implements - Collection, Iterable
Implemented By - AbstractQueue, ArrayBlockingQueue, ConcurrentLinkedQueue, DelayQueue, LinkedBlockingQueue, LinkedList, PriorityBlockingQueue,
PriorityQueue, SynchronuousQueue

Set – defines: add, addAll, clear, contains, remove, removeAll, size, toArray etc
Implements – Collection, Iterable
Implemented By – HashSet, LinkedHashSet, TreeSet etc

Map – defines: clear, containsKey, containsValue, get(Object key), keySet, put(Object key, Object value), putAll, remove, size, values etc
Implements –
Implemented By – HashMap, Hashtable, LinkedHashMap, TreeMap etc

SortedSet – defines: comparator, first, headset, last, subset, tailSet
Implements – Collection, Iterable
Implemented By - TreeSet

NB: Map interface does not extend the Collection interface


General-Purpose Implementations - The primary implementations of the collection interfaces.

HashSet - Hash table implementation of the Set interface. The best all-around implementation of the Set interface.
TreeSet Red-black tree implementation of the SortedSet interface.
LinkedHashSet - Hash table and linked list implementation of the Set interface. An insertion-ordered Set implementation that runs nearly as fast as HashSet.
ArrayList - Resizable-array implementation of the List interface. (Essentially an unsynchronized Vector.) The best all-around implementation of the List
interface.
LinkedList - Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are
frequently inserted or deleted within the list. Can be used as a double-ended queue (deque). Also implements the Queue interface. When accessed via the Queue
interface, LinkedList behaves as a FIFO queue.
PriorityQueue - Heap implementation of an unbounded priority queue.
HashMap - Hash table implementation of the Map interface. (Essentially an unsynchronized Hashtable that supports null keys and values.) The best all-around
implementation of the Map interface.
TreeMap Red-black tree implementation of the SortedMap interface.
LinkedHashMap - Hash table and linked list implementation of the Map interface. An insertion-ordered Map implementation that runs nearly as fast as HashMap.
Also useful for building caches (see removeEldestEntry(Map.Entry) ).

NB: TreeSet and TreeMap implement the SortedSet interface and provide sorted insertion (default or supplied comparator). If you add an object that doesn‘t provide
compareTo you will get a ClassCastException at runtime!

Map (Interface)
Object get(Object key)
Object put(Object key, Object value)
boolean containsKey(Object key)
int size()



11.           Sorting
NB: To be searched, an array or List must first be sorted. To be sorted (and thus searched) a List‘s elements must be comparable

Define sorting/comparison for a type using:

x implements Comparible<T>
{
   public int compareTo(T t)
   {
…
   }
}

e.g.
Collections.sort(List, Comparator)

Comparator is an interface, used to provide a custom comparison implementation for sorting:

x implements Comparator
{
public int compare(Object o1, Object o2)
}

or

x implements Comparator<t>
{
public int compare(T t1, T t2) {…}
}


java.util.Collections and java.util.Arrays both provide:

a sort() method which can sort in natural order or use overloaded method that takes a comparator.
A binarySearch method to search a pre-sorted array or List

Collections.reverse() reverses the order of the elements in a List
Collections.reverseOrder() provides a comparator that sorts in reverse

Lists and Sets have toArray to create arrays



12.           Generics
Although with arrays (no generics) you can do

Object[] list = new JButton[4];

For generics we can do:

List<T1> = new ArrayList<T1>();

But T1 must match, you can not do anything that looks like the array declaration above, like:

List<Object> = new ArrayList<MyObject>(); // can‘t do this!

ArrayList<T> can contain any T, or subclass of T

Mixing new generic and older non generic code can cause compile time warnings (at run time the two are the same anyway) but the code will compile and run – it may
cause run time exceptions if wrong types are added/expected etc (class cast exceptions etc)

e.g. pass generic List<String> into a non-generic method void foo(List aList) will create a compiler warning – “potentially unsafe operation”.


void add(List<Dog> d) can take a List of type Dog ONLY

void add(List<? Extends Dog> can take anything is-a Dog, Dog and subclasses of Dog

When using wildcard syntax, the collection can be accessed but not modified

List<?> means any type (any type extends object) – is the same as List<? extends object>

Conventions:

T is for type e.g. List<E>
E is for element e.g. add(E e)

NB: Arrays of generic types are only allowed, if the values of the type variable is the unbounded wildcard.




13.           Threads
Thread

void run()
void start()
void stop()
static void yield()
static void sleep(long ms) throws InterruptedException
final static void join() throws InterruptedException
final static void setPriority(int priority)

+ from object

final void wait() InterruptedException
final void notify()
final void notifyAll()


States – New, Runnable, Running, Waiting/blocked/sleeping, dead

Priorities:

Thread.MIN_PRIORITY (1)
Thread.NORM_PRIORITY (5)
Thread.MAX_PRIORITY (10)


Two ways to make a thread, extends Thread or implements Runnable

Chass MyThread extends Thread…

MyThead t = new MyThread();

Or

MyRunnable class implements Runnable

MyRunnable r = new MyRunnable();

Thread t = new Thread(r);


Synchronisation:

synchronized – methods, on blocks


Thread goes to sleep holding its lock

Thread can acquire more than one lock

Thread tries to get lock, thread becomes blocked on object lock

Static and non-static synchronized methods (or blocks on instance and class.class) will not block each other.


wait, notify and notifyAll

A call to an objects wait/notify must be within synchronized code on the object in question! Or you will get a compilation error along the lines of:

java.lang.IllegalMonitorStateException: current thread not owner

i.e. a thread can‘t invoke wait/notify without owning the objects lock first!

wait releases the lock (gained when entering the synchronized method/block) and waits to gain it again, in the blocked/waiting state waiting for the other thread to call
notify/notifyAll

When wait is called, the lock is released immediately, however when notify is called the lock isn‘t given up until it moves out of the synchronized code that contains it




14.           Development
javac

-d option, directory for classes

NB: this will throw an error if the specified directory does not exist. Directories below the directory given will contain the compiled classes, as defined in their package
structure.


java

-da disable assertions
-ea enable assertions
-D property value e.g. –DmyProperty=Value or –DmyProperty=‖some value with spaces‖

java.util.Properties

Properties p = System.getProperties();
p.setProperties(―myProperty‖, ―myValue‖);
p.list(System.out);

main()

static void main method can use var args, the following signatures are all valid for main:

static public void main(String[] args);
public static void main(String… stringVarArgsArray);
static public void main(String stringArray[])


classpaths:

-classpath, -cp e.g. –classpath .:
/com:/stuff

when searching, the first found match is used (stops looking once a match is found).

Search order
1. Java platform classes
2. Directories specified in the classpath

Declare classpaths in operating system environment or on the command line.

NB: only the final directory of a classpath path is searched, e.g. /my/lovely/path would _only_ search the path directory.

Jar files:

Include in the classpath by specifying the jar file explicitly – such as: javac –classpath folder/myApp.jar Stuff.java

Static imports (import static):

Can import methods and variables of a class into the current namespace: e.g.

import static java.lang.System.out
import static java.lang.Integer.*;

would give access to out.println and MAX_VALUE (public static const from the Integer class) directly.

NB: static import is a syntax error!

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:55
posted:4/17/2010
language:English
pages:10