SCJP 5.0 Study Notes

 

Note:  Please feel free to modify, improve, circulate, and repost these notes at will. –  Dave Allen

 

Collections Framework (only Maps, Iterators do not extend java.io.Collection Interface)

Collection interface

add(E)

addAll(Collection<e>)

remove(Object)

removeAll(Collection<?>)

contains(Object)

size()

iterator()

isEmpty()

Object[] toArray() – returns Object array, must cast – e.g. String[] str = (String[]) myCollection.toArray();

T[] toArry(T[] a) – returns typecast array – syntax: String[] str = myCollection.toArray(new String[0]);

Map interface,

SortedMap interface extends Map

put(keyObject, valueObject) – inserts key/value pair, will overwrite duplicate keyObject values

keySet() – returns set of keys

values() – returns collection of values

get(Object), remove(Object), size(), clear()

entrySet() – returns set of Map.Entry type (key/value pair)

Map.Entry – a key/value pair, has getKey() and getValue() methods

 

Maps care about unique identifiers

There is no add() method; Don’t have to override equals(Object) method to compile, but necessary to find objects

HashMap

 

Hashtable

synchronized version of HashMap

TreeMap

Can have null values, but NO null keys

LinkedHashMap (extends Hashmap)

maintains insertion order, slower updates, faster iteration than HashMap, order remains same if replacing duplicate key, can have null keys or values

Set interface, SortedSet interface extends Set

boolean add() – if element already exists, returns false and element not added

Sets care about uniqueness

HashSet

 

LinkedHashSet (extends HashSet)

fastest iteration through items without duplicates (a Set) that maintains insertion order

TreeSet<T>

new TreeSet(), new TreeSet(Collection<E>), new TreeSet<T>(Comparator<? super E>)

List interface

Lists care about the index

ArrayList

fastest iteration through items with duplicates

Vector

synchronized version of ArrayList; slower

LinkedList

addFirst(), getFirst()

 

doubly linked, ideal for implementing a stack or maintaining an ordered sequence of objects when they are frequently inserted and removed from the middle of the sequence

Queu interface

peek() – returns highest priority entry without removing it

poll() – returns highest priority entry and removes it

offer() – adds entry

PriorityQue

 

Collections

Collections.sort(Collection)

Collections.sort(Collection, Comparator)

Collections.binarySearch(collectionName, pattern) – must be sorted first

Collections.binarySearch(collectionName, pattern, Comparator) – must be sorted first

Collections.reverse() – reverses order of elements in List, doesn’t have to be sorted first

Collections.reverserOrder() – returns Comparator that sorts in reverse, must b sorted first

Arrays

Arrays.sort(arrayToSort)

Arrays.binarySearch(arrayName, pattern), Arrays.binarySearch(collectionName, pattern, Comparator) – returns int index

Arrays.asList(arrayName) – returns List, changes to either returned list or original array will be reflected in the other

Comparable interface

int compareTo(SpecificObjectType)

returns     negative int if this < Obj2

                0 if Objects are equal

                positive int if this > Obj2

Comparator class

int compare(SpecificObjectType1, SpecificObjectType2) – returns int with same meaning as above – substitute “SpecificObjectType1” for “this”

Iterator

boolean hasNext()

next() – returns type Object which must be cast if no generic type is specified for iterator, even if Collection that called iterator() method has generics, like List<Integer>

 

Can use generics syntax to avoid explicit casting, e.g. Iterator<Dog> = dogs.iterator();

 

 


Dates

java.util.Date

new Date() – date Object with current date

new Date(long millis) – millis since Jan 1, 1970

 

getTime() – returns long

setTime(long millis)

 

internally stored as primitive long which is milliseconds between date and Jan 1, 1970

Calendar

Calendar.getInstance() – gets default Calendar (almost always GregorianCalendar) with current time

Calendar.getInstance(Locale)

 

add(intField, intAmount) – adds or decrements field.  intAmount can be negative

roll(intField, intAmount) – larger parts of date will not be incremented/decremented, only the field specified

set(intField, intValue)

get(intField) – e.g. calendarInstance.get(Calendar.MONTH);

set() – various other set methods

setTime(Date)

getTime() – returns Date object, useful for passing to DateFormat

setTimeInMillis(long millis)

getTimeInMillis() – returns long

compareTo(Calendar)

 

NO new Calendar(), only instantiated using getInstance(), months are 0-based (January is 0)

java.text.

NumberFormat

NumberFormat.getInstance(), NumberFormat.getInstance(Locale) – e.g. NumberFormat.getInstance(Locale.US);

NumberFormat.getNumberInstace(), NumberFormat.getNumberInstanceLocale() – same as getInstance()?

NumberFormat.getCurrencyInstance(), NumberFormat.getCurrencyInstance(Locale)

 

format(long), format(double) – takes various numbers to be formatted, returns String

parse(String) – takes a String (must be formatted correctly to locale), returns a Number – e.g. parse(“$5,075”);

setParseIntegerOnly(boolean) – whether to format and display digits after decimal.

getMaximumFractionDigits(), getMinimumFractionDigits – get number of decimal places

setMaximumFractionDigits(int), setMinimumFractionDigits – set number of decimal places

get/setMinimum/MaximumIntegerDigits()

 

Should only instantiated using getInstance()

java.text. DateFormat

getInstance() – returns DateFormat with default Locale, sometimes SHORT style

getDateInstance() (has defaults, sometimes MEDIUM style),getDateInstance(styleConstant), getDateInstance(styleConstant, Locale)

parse(String) – converts String to a Date

format(Date) – returns String with formatted Date

 

String format for each style

possible default format – 0/8/01 7:46 PM

DateFormat.SHORT –  9/8/01

DateFormat.MEDIUM – Sep 8, 2001

DateFormat.LONG – September 8, 2001

DateFormat.FULL – Saturday, September 8, 2001

 

There is no format(Calendar) method.  Calendar must convert to Date first(using yourCalendar.getTime()), then use format(Date)

DateFormat’s Locale can only be set at instantiation using getInstance() – NO new DateFormat()

java.util.Locale

Locale.getDefault() – returns default Locale

new Locale(stringLanguage)

new Locale(stringLanguage, stringCountry) – e.g. new Locale(“it”, “IT”)

 

setDefault(Locale)

getDisplayLanguage() – returns String of Language

getDisplayLanguage(Locale) – displays language using language of Locale passed in

getDisplayCountry() – returns String code

getDisplayCountry(Locale) – displays language using language of Locale passed in)

Locale.getAvailableLocales() – returns an array of Locales installed

 

used in Scanner, DateFormat, NumberFormat

 


String Stuff

String

new String(), new String(StringBuilder/Buffer)

new String(“StringLiteral”)

new String(ExistingStringObject) will create a new String object different than ExistingStringObject

 

length()

charAt(int)

concat(String)

equalsIgnoreCase(String)

substring(intIndex)

substring(startIntIndex, endIntIndexExclusive)

replace(char/stringRegex, char/stringReplacement)

replaceAll(char/stringRegex, char/stringReplacement)

replaceFirst(stringRegex, stringReplacement)

split(regex) – returns String array of tokens, good for just small amount of data

split(regex, IntLengthOfArrayReturned)

toLowerCase()

toUpperCase()

trim() – remove whitespace off ends

toString() – returns a new String object

 

indexOf(char/String)

indexOf(char/String, startingIntIndex)

lastIndex(char/String, startingIntIndex)

lastIndex(char/String, startingIntIndex)

contains(charSequence)

matches(regex) – returns boolean indicating if regex matches string

boolean startsWith(String)

boolean startsWith(String, offsetIndex)

String format(“formattingString”, args) – returns String formatted to specs

String format(Locale, “formattingString”, args)

 

All methods return a String, do no alter original String

NO insert() method (this is in StringBuilder/StringBuffer)

NO length member variable (this is for array)

StringBuilder/ StringBuffer

append(xxx) – can append almost any char related type

delete(intStartIndex, intEndIndexExclusive)

deleteCharAt()

insert(intOffset, String)

reverse()

toString()

length()

substring(startIndexInclusive)

substring(startIndex, endIndexProbablyExclusive)

 

lastIndexOf(String)

lastIndexOf(String, startSearchIndex)

replace(intStart, intEnd, String)

setCharAt()

 

StringBuffer is synchronized and slower.

StringBuilder is not synchronized and faster

equals() method is not overridden, so it compares references, not meaningful values – same as ==

java.util.

Scanner

new Scanner(File), new Scanner(stringToSearchOrTokenize)

 

useDelimiter(String) – can be regex

useLocal(Locale)

hasNext(), hasNextInt(), hasNextFloat(), hasNextXxx() – for all primitives EXCEPT char

next(), nextInt(), nextFloat(), nextXxx – for all primitives EXCEPT char

Scanner.close() – static method that should be used after done with file

findInLine(regexString) – returns String found

 

match() – returns MatchResult

matchResult.groupCount() – method in MatchResult (not Scanner)

matchResult.group(groupCountIndexInt) – method in MatchResult (not Scanner)

 

Mostly used for tokenizing, but can also find regexes using findInLine()

Default delimiter is whitespace

java.util.regex.

Pattern

Pattern.compile(regex) – returns new Pattern

matcher(CharSequence) – returns new Matcher

split(regex) – returns String array of matching patterns found in the CharSequence

Pattern.matches(regex, stringtoSearch) – returns Boolean indicating if string matches regex

 

/d             digits

/s             whitespace

/w            word character (letters, digits, or underscores)

 [af]         a or f

 [a-f]        a, b, c, d, e, f

 [a-dA-D]                A,a,B,b,C,c,D,d

.               any character

+              greedy one or more (e.g. /d+ means one or more digits)

*              greedy zero or more (e.g. filename/d*)

?              greedy zero or more occurrences(e.g. /d?)

^              not (e.g. [^abc] excludes abc)

 

String pattern = “\\d” creates string regex with \d.  String pattern = “\\.” creates string regex with .

java.util.regex.

Matcher

find() – returns boolean indicating a match’s existence, advances to next index that matches, left to right

start() – returns starting index

group() – returns string that matches

 

Probably Not on Exam

replaceAll(stringReplacement)

replaceFirst(stringReplacement)

appendReplacement(StringBuffer, stringReplacement) --

appendTail(StringBuffer) – to be used after appendReplacement

java.util.

Formatter

new Formatter(), new Formatter(Appendable, Locale) – Appendable can be StringBuilder/StringBuffer,

BufferedWriter, FileWriter, but NOT String

 

format(“formattingString”, args) – returns formatted String

 

Serialization (package java.io, classes must implement Serializable to be serialized)

FileOutputStream

new FileOutputStream(stringFileName)

new FileOutputStream(File)

ObjectOutputStream

defaultWriteObject()

writeObject(Object)

writeInt(int), writeFloat(float), writeXxx(xxx)

FileInputStream

new FileInputStream(stringFileName)

new FileInputStream(File)

ObjectInputStream

defaultReadObject()

readObject() – returns Object, must be cast before use

readInt(), readFloat(), readXxx()

 

Serialization Notes

·     For custom serialization, must have methods (EXACTLY as shown except parameter names):

                --private void writeObject(ObjectOutputStream oos), call oos.defaultWriteObject() before trying to do anything else in method

                --private void readObject(ObjectInputStream ois), call ois.defaultReadObject() before trying to do anything else in method

·     If a superclass implements Serializable all subclasses do automatically

·     If an object within a object to be serialized is not serializable, code will compile, but a RuntimeException will be thrown

·     An object is serializable even if superclass is not.  However, the first superclass in the hierarchy that does not implement Serializable must have a no-arg constructor (that will get called).  If this is violated, readObject() will produce a java.io.InvalidClassException

·     The (no-arg?) contructor of every non-serializable superclass will run when an object is deserialized.  However, the deserialized objects’ constructor does not run when it is deserialized.

·     Deserialization order is FIFO

·     Only member (instance) variables are serialized

·     Static and transient member variables are not serialized

·     If a non-serializable element is present in a class you are trying to serialize, the code will compile but there will be a runtime exception upon attempt to serialize

·     Filter Streams – another name for streams that wrap (get chained to) other streams


IO Stuff (java.io package)

File – can be file or directory

new File(pathNameAndFileString)

new File(pathNameDirString, childPathNameString), new File(File pathname, fileORDirFileString)

 

createNewFile() – creates file if doesn’t yet exist, links to existing file, actually creates file on hard drive

mkdir()

exists() – returns boolean

isDirectory(), isFile() – returns boolean

delete() – can only delete directories if they are empty

list(), list(FilenameFilter) – returns String array

renameTo(File) – directory does not have to be empty to rename

listFiles(), listFiles(FilenameFilter) – returns File array

getName() – returns String

getPath()

canRead()

 

NO method to change working directory

FileReader

read()

 

No method for reading line at a time, almost always wrapped with BufferedReader

BufferedReader

read(), readline()

 

Usually wraps around FileReader, No method new BufferredReader(File)

FileWriter

new FileWriter(File)

new FileWriter(File, appendToEndBoolean) – instead of overwriting

new FileWriter(fileNameString)

new FileWriter(fileNameString, appendToEndBoolean) – no overwrite

 

write()

flush()

close()

 

Almost always wrapped by (chained to) BufferedWriter

BufferedWriter

write()

newline()

flush()

close()

 

Usually wraps around FileWriter

PrintWriter

newPrintWriter(File), new PrintWriter(stringFileName), new PrintWriter(Writer), new PrintWriter(OutputStream)
 
write()
format()/printf()
print()/println()
flush(), close()
 
Often wraps around BufferedWriter:
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));

will buffer the PrintWriter's output to the file

FilenameFiler interface

accepts(directoryFile, nameString) – returns boolean indicating whether to file passes through filter or not
 
used by File’s list(FilenameFilter) and listFiles(FilenameFilter) methods

DataInputStream/

DataOutputStream

Not on exam despite what Sun objectives say– don’t study

 

 

 


Other APIs in java.lang

Thread

new Thread(), new Thread(stringName), new Thread(runnableTarget), new Thread(runnableTarget, stringName)

 

Thread.MIN_PRIORITY – usually 1

Thread.NORM_PRIORITY – usually 5

Thread.MAX_PRIORITY – usually 10

 

run() – can be overridden to make new thread, but not recommended

start() – causes thread to move to alive state (available to run)

isAlive() – returns boolean

Thread.sleep(long millis) – throws InterreptedException

join(), join(longMaxTimeToWaitInMillis) – throws InterruptedException

Thread.yield() – usually shouldn’t be used, but should return current thread back to runnable thread pool if other threads with same or higher priority exist

setName(String)

Thread.currentThread().getName()

setPriority(int1-10)

int getPriority()

 

getState()

boolean holdsLock()

Object

wait(), wait(longMaxTimeToWaitInMillis), wait(longMaxTimeToWaitInMillis, intNanosMoreToWait) – throws InterruptedException

notify()

notifyAll()

public boolean equals(mustBeObjectNotSubtype)

public int hashCode()

public String toString()

java.lang.Math

Math.random()

Math.round()

Math.ceil() -- Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.

Math.floor() -- Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.

Math.round()

Math.sqrt()

Math.max(number, number)

Math.min(number, number)

java.lang.Enum

ordinal() – prints position (zero-based), similar to index for an array

                e.g. enumName.ordinal();

 

Enums in case statement should NOT use class prefix, but everywhere else should have prefix (e.g. Grade.A), unless enum is in the same class

java.lang.System

System.out.println()

System.out.print()

System.out.format/printf(“string with %below”, argsToString)

System.exit(intStatus)

System.getenv() – returns Map of all environment variables

System.getenv(stringEnvironmentVariable) – returns value for specified environment variable

 

System.getProperty(stringKey)

System.getProperties() – returns Property object (subclass of Hashtable) containing all properties

System.setProperties(stringKey, stringValue)

System.setProperties(PropertyObject)

System.gc() – same as Runtime.getRuntime().gc() – requests (but may not obtain) garbage collection

 

For Formatting with format()/printf()

%[arg_index$][flags][width][.precision]conversionCharacter

                       -,+,0,,,(                                  b,c,d,f,s,S

- Left justify                                                                           b boolean

+ Include sign                                                                          c char

0 Pad with zeros                                                                     d integer (digit)

, Use locale-specific grouping separators                               f float

( negatives in parentheses                                                       s string

                                                                                                S CAPITALIZE the string

%illigitChar results in java.util.UnknownFormatConversionException

Wrong format results in IllegalFormatConversionException

Can have more arguments than conversions, but more conversions than arguments results in java.util.Missing FormatArgumentException

You can’t use an int literal argument for %f

 


Primitives, WrappersAssignments, Autoboxing

·     new XXX(String), new XXX(primitive) -- wrapper class constructors all take corresponding primitives or strings as arguments (e.g. new Long(“12”) or new Long(12))

·     XXX.valueof(String),  XXX.valueOf(String, intRadixBase) – static method returns XXX wrapper type

·     parseXxx(String) – static method returns primitive of type Xxx

·     xxxValue -- converts wrapper to any primitive xxx type, truncates and does NOT round

·     table on p. 233

·     integer literals are always interpreted as int types by the JVM, number literals with decimals are interpreted as doubles

·     byte – 8 bits, short – 16 bits, int – 32 bits, long – 64 bits, float – 32 bits, double – 64 bits, char – 16 bits (but can’t fit into a short because it has a bigger positive range than short since there are no negatives)

·     no static member can use a generic type parameter declared by the enclosing class

·     Calling run() method will not create a separate thread, and Thread.currentThread().getName() of the thread in run() will be “main”

·     Variables and classes can’t be synchronized, but instance methods, static methods, and any code block within a method (enclose in {}) can be synchronized

·     Conditional operators (==, <, >) have higher precedence than assignment operators, so “if (b = x == y)” can be a legal statement

·     Wrappers with values over 127 are unique, so “new Integer(130) == new Integer(130)” returns false, but “new Integer(120)” == new Integer(120)” returns true

·     WrapperClass.equals(AnyOtherClass) = false, String.equals(anyNonString) = false, StringBuffer.equals(AnyOtherObjectRef) = false (StringBuffer does not override equals method)

·     0 % 4 = 0

·     new Boolean(“anyMessage”); will create a Boolean with false

·     Trying to unbox a null will result in a NullPointerException

·     if there are multiple ++x incrementors in a compound expression, each is incremented before that part of the expression?

·     For Boolean bool = new Boolean(“TRUE”), in both if (bool) and if (bool == true), bool is unboxed automatically

·     Number, StringBuffer/StringBuilder DO NOT override equals() and hashCode() and inherit these from Object (so .equals() for different objects with the same values evaluates to false)

·     For array instantiation, array size must be specified (INCORRECT – in myArray[] = new int[])

·     Vararg methods CAN be invoked with 0 or more arguments

·     Integer can be boxed to int and vice-versa