Shared Flashcard Set


SCJP Certification Notes
Notecards for studying for the SCJP (Sun Certified Java Programmer) Certification
Computer Science

Additional Computer Science Flashcards




Class Access Modifiers

Public-Seen by all classes in all packages


Default-Seen only by classes in the same package

Class Non-Access Modifiers

Abstract-Can't instantiate, must extend.


Strictfp-Conforms IEEE 754 standards for floating point numbers.


Final-Class cannot be extended


Interface-Must be implemented. Can't be instantiated.


Member Access Modifiers

Public-Can be accessed by any member of any class in any package.


Default- Can only be accessed by the members of classes and subclasses in the same package


Protected-Same as default, but can additionally be accessed by a subclass in a different package. Once inherited by out of package class, is private to all other classes in that package.


Private-Can only be accessed by members in its own class.

Member Non-Access Modifiers

Abstract- Must be implemented by the first concrete class to extend the abstract class it's a member of.


Strictfp- aheres to IEEE 754 for floating point numbers


Final- methods cant be overridden, vars are constants


Volatile- can only be applied to instance variables


Native- implemented in native code (usually C) and end in ";" just like abstract method.


Transient- will be skipped during serialization. only applied to instance variables


Synchronized- Only allows one thread to run it at a time.


Static- is a class variable


Var-args- an arg of varying lenght. must be last param in method. can only have one per method.


Primitive Types

byte - 8-bit signed integer

char - 16-bit Unicode character

short - 16-bit signed integer

int - 32-bit signed integer

long - 64-bit signed integer

float - single-precision 32-bit IEEE 754 floating point

double - double-precision 64-bit IEEE 754 floating point

boolean - true and false


Overriding Methods
  • Arg list must be same
  • Return type must be same or subtype
  • Access level can't be more restrictive
  • Can't throw new or broader exceptions
  • CAN throw unchecked exceptions
  • Cannot override a final method
  • Cannot override a static method
Overloading Methods
  • Arg list MUST be different
  • CAN change return type
  • CAN change access modifer to more restrictive
  • CAN throw new or broader exceptions
  • can overload in different classes by inheritence
Polymorphism with Overriding and Overloading

When method is overridden, it's chosen based on the actual object.

When method is overloaded, it's chosen based on the ref varible.

  • If a class that extends another class, calls a method it has overloaded from the class it extends, it will be overridden. (use object)
  • Otherwise it will be overloaded. (use ref var)
  • are their own type
  • values are constants
  • can have constructors
  • can have methods
  • can have constant specific class blocks that provide an area for overriding the general methods in the enum for a specific constant
  • if you have a constructor, methods, or any other content outside the basic enum, you must use a semicolon after the last element (or the closing brace on the constant specific class block if the last element has one.
Downcasting Reference Variables
  • You have to down cast when you want to use a wider reference variable but invoke a narrower object's method that isn't in the reference variable's definition.
  • You downcast by creating a new ref var of the same type as the object you're trying to use, and then setting it equal to the original ref var... you must use an implicit cast to let the comipler know you doing it.
  • syntax example
    • Dog d = (Dog)animal;
  • the cast will cause a compile time error if the compiler can tell the cast is wrong, but if the cast is possible, it has to trust us and can cause a runtime error.
Upcasting Reference Variables
  • is implicit, so no cast is required
  • syntax example:
    • Animal a = new Dog();
  • can use any access modifier
  • first call is always this() or super()
  • this() and super() can only call static methods or variables
  • abstract class constructors are called when a concrete class instantiates them
  • interfaces have no constructor
  • can only be invoked by other constructors
  • if super() has args, you have to supply no arg constructors to create objects witout args or your code wont compile.
  • can be accessed directly through the class name
  • can also be accessed by any object of the class
  • can be reDEFINED in a subclass but NOT overridden
Coupling and Cohesion
  • Cohesion - the amount of focus on one particular task a class has.
  • Coupling - the extent one class knows about another class.
  • The desired scenario is
Stack and Heap
  • Instance variables live on the heap
  • Local variables live on the stack
Primitive Casting
  • assiging numbers to a primitive directly will not require cast unless its over the max value
    • byte b = 120; <-ok
  • assigning numbers to Wrappers is also ok if you don't invoke the constructor with new()


  • the result of anything that is int-sized or smaller always is cast to an int
  • casting from smaller to larger (byte to int) is implicit
  • casting from larger to smaller(int to byte) is explicit
  • Compound assignment operators (+=, -=, *=, /=) contain an implicit cast.
  • Casting a float as an int loses all digits after the decimal without rounding.
  • Casting to smaller means you truncate all the bits from the larger value out of the smaller bits that don't fit
    • if you are left with a "sign" bit turned on, you must perform 2's compliment conversion by flipping all bits, adding 1 to the result, and then attach negative sign.
Variable Scope
  • Static - 1st longest: created when class is loaded in the JVM
  • Instance 2nd longest: created when new instance is created and lives until instance is removed.
  • Local 3rd longest: created in a method and lives until method completes.
  • Block 4th longest: created in a block and live until block completes

Local method variables still live, but are out of scope in a nested method.

Passing Variables into Methods
  • Passed by copy.
  • Primitives don't preserve changes b/c they are copys of the value.
  • References DO preserve changes b/c they are copys of the address.
  • brackets can go on either side of the variable
    • int []myInt  or  int myInt[]
  • size goes in instantiation not in the declaration
  • the compiler only requires the first dimension of a multi-dimensional array to be given a size at instantiation
    • you must instantiate new arrays for the remaining dimensions before using them or you'll get a NullPointerException.
  • primitive array elements can be any primitive that IMPLICITLY converts
  • reference array elements can be any subtype
  • the actual type of primitive array cannot be substituted like the elements can.
  • the actual type of REFERENCE arrays CAN be referenced by supertypes.
  • to initialize an array on the same line it's declared
    • to the right of the equals sign open a brace, put in comma delimitied values, close the brace, add semicolon.
Order of Execution- Object overloading, Primitive overloading, Classes
  • Object Overloading
    • exact signature first.
    • closest of inheritence args
    • var args always last.
  • Primitive Overloading
    • exact signature first
    • widening if possible
    • boxing if possible
    • var args always last
  • Class Loading
    • static initialization block
    • main()
    • super constructor
    • instance intialization block
    • constructor
Wrapper Classes - (Basics)
  • Byte
  • Character
  • Short
  • Integer
  • Long
  • Float
  • Double
  • Boolean

Wrapper objects are immutable

All have 2 constructors

  • one takes a primitive
  • one takes a String representing the primitive


Wrapper Classes - (Methods)
  • toString() - returns String
  1. instance.toString() - ALL
  2. Wrapper.toString(prim p) - ALL
  3. Wrapper.toString(prim p, radix r) - LONG & INTEGER
  • xxxValue() - returns primitive
  1. instance.xxxValue() - ALL
  • parseXxx() - returns primitive
  1. Wrapper.parseXxx(String s) - ALL BUT CHARACTER
  2. Wrapper.parseXxx(String s, radix r) - NON-FLOATING POINT NUMERIC
  • valueOf() - returns Wrapper
  1. Wrapper.valueOf(String s) - ALL
  2. Wrapper.valueOf(prim p) - ALL
  3. Wrapper.valueOf(String s, radix r) - NON-FLOATING POINT NUMERIC
== and equals() with Boxing
  • primitives
    • == checks to see if 2 things have the same memory address (are literally the same thing)
  • objects
    • == checks to see if 2 objects have the same memory address (are literally the same thing)
      • for some wrappers will find 2 like wrappers == if they contain the same primitive IF YOU DON'T INVOKE THE CONSTRUCTOR WITH NEW()
        • Byte
        • Char (\u000 to \u007f)
        • Short and Integer -128 to 127
      • when used to compare a prim to a wrapper, wrapper will be unboxed to compare primitives
    • equals() checks for meaningful equality which is defined by overriding equals()
Garbage Collection
  • Only concerned with the heap
  • when it runs, it looks for objects no longer reachable by active thread and removes them
  • JVM decides when it runs
  • you can ask JVM to run GC-> System.gc(); but it's not guaranteed to run
  • When counting the number of object created, don’t forget to include any addition object that get created as member variables in a class, for example a member array, or member variable that’s a wrapper, as wrappers are objects.
Switch Statements


case constant1: code block

optional break

case constant2: code block

optional break

optional default: code block


  • expression must be enum or implicitly widen to int
  • constant can't be larger than the type of expression (3000 for a byte for example)
  • constant must be a COMPILE-TIME constant
    • have to declare and initalize on same line to be compile-time constant(final int a = 0;)
  • each case must be different (compile time error)
  • boxing is legal-you can switch a Wrapped primitive
  • you don't have to use braces for code blocks
For Loops

for(expressions; true/false; expressions)


  • none have to be filled in
  • if all blank, is an infinite loop
  • separate multple expressions with commas
  • unlabled break exits entire loop
  • unlabled continue skips current iteration
  • infinite loop won't throw stackOverflowException if nothing is added to the stack, duh
Labeled Statements


  • must be placed just before statement being labeled
  • usually used to direct break() or continue() in nested loops
Exceptions (Basics)

Checked (Compile-Time)

UnChecked (Run-Time)


try{}catch(Exception e){}finally{}

  • catch can be omited if finally follows immediately follows try
  • finally runs after catch wether there's an exception thrown or not
  • can't put wider excpetions after narrower exceptions-compile time exception
  • a method must declare, aka throw(), any exceptions it doesn't catch itself
Exceptions (By Name)
  • ArrayIndexOutOfBoundsException - unChecked
  • ClassCastException - unChecked
  • IllegalArgumentException - unChecked
  • IllegalStateException - unChecked
  • NullPointerException - unChecked
  • NumberFormatException- unChecked
  • AssertionError
  • ExceptionInitializerError
  • StackOverflowError
  • NoClassDefFoundError

2 Types

  • Really Simple
    • makes the assertion and then throws the AssertionError
    • assert(x<y);
  • Simple
    • also passes a value to the stack trace to provide a string that prints further info about the error.
    • assert(x<y): "x = " + x;

Java Command Flags

  • -ea: enable assertions
  • -da: disable assertions
  • no args - works on everything
  • package name - works on package and subs
  • class name - works on class

Don't Use Assertions To

  • validate args to a public method
  • validate command-line args
  • that can cause side affects

  • Immutable
  • shortcut method (String s = "jason";) only makes 1 object, the new string object "jason".
  • standard method String s = new String("jason"); makes 2 objects, "jason" and the new string object.


  • charAt(int i)-char at i
  • concat(String s)-appends s to calling string and returns new String
  • equalsIgnoreCase(String s)-determines equality of calling String and s and returns boolean
  • length()-returns number of chars in calling String
  • replace(char c1, char c2)-replaces the occurances of c1 with c2 and returns new String
  • substring(int i, int i2)-returns a substring from i (inclusive) to i1 (exlusive)
  • toString()-returns String
  • toLowerCase()-retruns lowercase of calling String
  • toUpperCase()-returns uppercase of calling String
  • trim()-removes whitespace from end of String and returns new String
StringBuilder and StringBuffer
  • mutable
  • equals() is not overridden
  • StringBuffer is faster b/c it's methods are not synchronized.


  • append(String s)-updates the calling object by adding s to the end
  • delete(int i)-removes substring from caller.
  • insert(int i, String s)-inserts s at i (inclusive) into caller
  • reverse()-reverses characters in caller
  • toString()-returns String in caller
File I/O - (Basics)

must import*;


  • File- not used to read or write data
    • make new empty files or directories
    • delete files
    • search for files or directories
    • constructor 1 takes a String to look for a file name and create a file object that either refers to nothing or to the file that exists with the String as the name
    • constructor 2 takes a directory(file) and a string to create a new file name in the subdirectory provided
  • FileReader- low level methods for reading files
    • usually wrapped in BufferdReader
    • read single characters
    • read whole stream of characters
    • read fixed number of characters
    • constructor takes File obj
  • BufferedReader- wrapper for lower level classes
    • constructor takes Reader
  • FileWriter-low level methods for writing characters to files
    • usually wrapped in BufferedWriter or PrintWriter
    • write characters or Strings
    • constructor takes File obj and creates actual file
  • BufferedWriter- wrapper for lower level classes
    • wite large chunks to a file at once
    • provide methods for writing characters easier 
  • PrintWriter- newest wrapper class
    • constructor takes any Writer
  • Console- new to Java 6
    • read input from the console
    • write formatted output to console
File I/O - (Methods - File)

Important Methods



  • createNewFile()-creates new file in the directory  (if provided) with name in the reference, unless it already exists, then that file is assigned to calling ref...returns boolean
  • exists()-returns boolean for if file or dir of ref exists
  • delete()-deletes file or dir
    • can't delete a dir thats not empty
  • isDirectory()-returns boolean if directory exists
  • isFile()-returns boolean if file exists
  • list()-returns String[] of files and dirs in ref
  • mkdir()-makes dir from name in ref and returns boolean
  • renameTo(File f)-renames files and dirs
    • you CAN rename a non-empty dir
    • must pass a new File object with the name you want to the current object to rename it.
File I/O - (Methods - Writers)


  • write(char[] c)-writes c to the calling obj's file
  • flush()-flushes the buffer
  • close()-closes the file


  • all same methods as FileWriter...
  • newLine()-writes a newline char to the line


  • all same methods as FileWriter...
  • print(String s)-writes s to file
  • println(String s)-writes s to file plus a newline char
  • format(String formatString, Object args)-formats args according to formatString and prints to file
  • printf()-same as format()
File I/O - (Methods - Readers)



  • read(char[] c)-reads contents of calling obj file into c
  • close()-closes the file


  • same as FileReader...
  • readLine()-reads line of text from file and returns it as a String
File I/O - (Methods - Console)


  • constructor
    • Console c = System.console();
  • readLine([String formatString, arg])-prints optional formated prompt and reads line of user input from screen and returns it as a String
  • readPassword([String formatString, arg])-prints optional formated prompt and reads line of user input from screen into char[] and returns it.
  • saves an object's state to a file so that it can be rebuilt later.
  • instance variables only
  • class of object being serialized MUST implement Serializable interface
  • any states inherited from superclass that ISNT serializable will be reset to intial values when super() runs
  • when serializing arrays, every element must be Serializable, or the serialization will fail


  • all throw checked exceptions
  • FileOutputStream(String filePath)
  • ObjectOutputStream(FileOutputStream fos)
    • writeObject(Object o)- writes the state of the object into the file passed to fos
  • FileInputStream(String filePath)
  • ObjectInputStream(FileInputStream fis)
    • readObject()- reads the state of the object read in from fis
    • must be explicitely cast back to it's type into a new ref variable.
Serialization - (Transients)

Any objects that are members of an object being serizalized, must themselves implement Serializable or they won't be saved.


Rebuilding these objects requires 2 specific methods be overloaded in the main object being serialized.


Both methods throw checked exceptions!


  • private void writeObject(ObjectOuputStream oos
    • oos.defaultWriteObject()-does initial write
    • oos.writeXxx(ref.getterMethod())-does manual write
    • oos.writeObject(getterMethod())-writes object as Object to oos
  •  private void readObject(ObjectInputStream ois)
    • ois.defaultReadObject()-deos initial write
    • ref = new Object(ois.readXxx())-does manual write
    • ref = new Object((Cast)ois.readObject())-
    • reads in an object written to the oos, and casts it to the appropriate type for the constructor


Dates, Numbers, and Currency - (java.util package)


  • mostly deprecated
  • instantiation
    • Date d1 = new Date()
    • Date d2 - new Date(long milisecondsSince010170)
  • methods
    • String s = d1.toString()
      • returns String containing current date and time


  • instantiation
    • Calendar c = Calendar.getInstance()
      • creates a new Date and wraps in Calendar object
    • Calendar c = Calendar.getInstance(Locale loc)
      • creates a new Date and wraps in Calendar object with loc
  • methods
    • Date d = c.getTime()
      • returns the wrapped Date
    • c.setTime(Date d)
      • sets the wrapped date to d
    • c.set(int yyyy, int mm, int dd)
      • sets wrapped date (mm is inclusive)
    • c.add(CalendarConst const, int num)
      • adds or subracts const units by num
    • c.roll(CalendarConst const, int num)
      • same as add() but doesn't roll the values larger than it forward as the onces below it cycle



  • used as arg in constructors for DateFormat & NumberFormat
  • formats dates, numbers, currency for specific locales
  • instantiation
    • Locale myLocale = Locale.getDefault()
    • Locale myLocale= new Locale([language],[[country]])
      • can't have country without language in constructor
  • getDisplayCountry([Locale l])-returns a String with the name of country
    • no arg displays in the language of default Locale
    • l displays in the language contained in l
  • getDisplayLanguage([Locale l])-same as getDisplayCountry but with language instead of country
Dates, Numbers, and Currency - (java.text package)



  • format dates
  • styles
    • DateFormat.SHORT- 01/01/11
    • DateFormat.MEDIUM -Jan 1, 2011 - (default)
    • DateFormat.LONG - January 1, 2011
    • DateFormat.FULL - Monday, January 1, 2011
  • instantiation
    • DateFormat df = DateFormat.getInstance()
    • DateFormat df = DateFormat.getDateInstance()
    • DateFormat df = DateFormat.getDateInstance(style)
    • DateFormat df = DateFormat.getDateInstance(style, locale)
  • methods
    • String s = df.format(Date d)
      • returns String of d formatted
    • Date d = df.parse(String s) - throws ParseException()
      • takes String in form of DateFormat and returns a Date


  • format numbers
  • instantiation
    • nf = NumberFormat.getInstance()
    • nf = NumberFormat.getInstance(Locale loc)
    • nf = NumberFormat.getNumberInstance()
    • nf = NumberFormat.getNumberInstance(Locale loc)
    • nf = NumberFormat.getCurrencyInstance()
    • nf = NumberFormat.getCurrencyInstance(Locale loc)
  • format()- just like DateFormat
    • if there are more than the default # of fractional digits, format() will round... not truncate
  • getMaximumFractionDigits()-returns the default number of fractional digits used by default by format
  • setMaximumFractionDigits(int i)-sets the number used to i
  • parse(String s)-takes a String in a NumberFormat and returns a Number
    • setParseIntegerOnly(boolean b)-sets the object to parse (or not to parse) only the integers in a float or double.
Parsing, Tokenizing - (Regex)

represents a pattern to be used as a search for a token in a String by Matcher or Scanner

  • if you put characters into a string, that's the pattern
    • "abcde" - searches for any occurance of "abcde"

metacharacters can be used to represent patterns for searching

  • \d - digits
  • \s - whitespace characters
  • \w - word character (letters, digits, or _)
  • .   - any character
  • [abc] - specific characters (a or b or c)
  • [a-x] - specific range of characters (a-x)
  • [a-fA-f] specific ranges of characters (a-f or A-F)
  • + - one or more (greedy)
  • * - zero or more (greedy)
  • ? - zero or one (greedy)
Parsing, Tokenizing, - (Classes)


  • holds representation of the regex to be used by Matcher
  • instantiation
    • Pattern p = Pattern.compile(String regexExpression)



  • invokes the regex engine to perform matching operations
  • instantiation
    • Matcher m = p.matcher(String youAreSearching)
  • methods
    • boolean b = m.find()
      • searches then returns wether regexExpression is found in youAreSearching
    • int i = m.start()
      • returns the index for the found regexExpression
    • String s =
      • returns the found String that matches regexExpression stored in Pattern



  • does more advanced token extraction than Pattern/Matcher methodology
  • instantiation
    • Scanner s = new Scanner(String source)
    • Scanner s = new Scanner(File source)
    • Scanner s = new Scanner(Stream source)
  • methods
    • String s = s.findInLine(String pattern)
      • checks for pattern and returns it
    • boolean b = s.hasNext()
      • checks for a String in next position
    • String s =
      • returns next String
    • boolean b = s.hasNextXxx()
      • checks for a Xxx in next position
    • Xxx x = s.nextXxx()
      • returns next Xxx
    • void s.useDelimiter(String regex)
      • set delimiter

String Splitter

  • String[] sArray = myString.split(String regexDelimiter)
String Formatting

format string syntax

  • %[arg_index$][flags][width][.precision]conversion char
    • % - always starts (required)
    • [arg_index$]-int indicating the order of printing for args
    • [flags]
      • left justify
      • + include a sign
      • 0 pad with zeros
      • , use locale specific grouping separators
      • ( enclose negatives in parenthesis
    • [width] - int indicating max number of characters to print
    • [.precision]- int num of digits after decimal to print
    • conversion char - type of arg to format (required)
  • methods
    • format(String formatString, args)
    • printf(String formatString, args)
Overriding equals() and hashCode()

If you override equals, you are SUPPOSED to override hashCode


  • equals()
    • public boolean equals(Object o){}
    • if 2 objects are equal() they must have same hashCode()
  • hashCode()
    • public int hashCode(){}
    • if 2 objects have the same hashCode() they don't have to be equal();
Collections - (Basics)

Generally hold objects, not primitives.  (primitives are autoboxed)


  • Ordered- Collection maintains some order with regard to when the items where added to it
  • Sorted- Collection puts items added to it in some natural sorted order.
    • Comparable()-compare objects for sorting with access to the object's class
    • Comparator()-compare objects for sorting w/o access to the object's class
  • List
  • Set
  • Map
  • Queue
  • Collections
  • Arrays
Collections - (List)
  • Extends Collection
  • Ordered (by index)
  • Unsorted
  • methods
    • Object = get(int index)
    • int = indexOf(Object o)    -1 if its not found
    • boolean add([index i], Object o)- adds o at index i or to the end of the List
    • int = size()
    • address = iterator()- returns first element in the List
    • Object[] = toArray()
    • a[] = toArray(Array a)
    • boolean = contains(Object o)
    • int = remove(int index) non 1 means fail
    • boolean = remove(Object value)
  • types
    • ArrayList-fastest random access
    • Vector-same as ArrayList, but synchronized & slower
    • LinkedList-elements are all linked to one another
      • implements Queue interface


  • Iterator
    • implementation
      • Iterator<ListType> i = myList.iterator();
    • methods
      • hasNext()-returns true if List has at least one more element
      • next()-returns the next Object and moves forward
Collections - (Set)

Extends Collection

Doesn't allow duplicates


  • methods
    • boolean = add(Object o)
    • boolean = contains(Object o)
    • address = iterator()- returns first element in the Set
    • int = size()
    • Object[] = toArray()
    • a[] = toArray(Array a)
  • HashSet
    • unorderd
    • unsorted
  • LinkedHashSet
    • ordered - order of insertion
    • unsorted
  • TreeSet
    • ordered
    • sorted - ascending natural order
    • members must be mutually comparable
    • methods for searching (NavigableSet)
      • lower()-returns element lower than given element
      • floor()-same as lower but includes equal to
      • higher()-returns element higher than given element
      • ceiling()-same as higher but includes equal to
      • pollFirst()-returns and removes first key/value
      • pollLast()-returns and removes last key/value
      • descendingSet()-returns Set in reverse order
Collections - (Map)

Doesn't extend Collection

Stores things with a unique ID (key)


  • any Object used as a key must override equals() and hashCode()
  • instantiation
    • Map<Object, Object> myMap = new HashMap<Object, Object>()
  • methods
    • void = put(Object key, Object value)
    • Object = get(Object key)
    • boolean = containsKey(Object key)
    • boolean = containsValue(Object key)
    • Set = keySet() - returns keys in map
    • value = remove(key) removes key/value from map
    • int = size()
  • HashMap
    • unordered
    • unsorted
    • allows mutliple null values and one null key
  • LinkedHashMap
    • ordered
    • unsorted
  • Hashtable
    • synchronized version of HashMap
    • cannot have any null values
  • TreeMap
    • ordered
    • sorted in natural ascending order
    • methods for searching (NavigableMap)
      • lowerKey()-return element less than given element
      • floorKey()-same as lower but includes equal to
      • higherKey()-return element higher than given elemnt
      • ceilingKey()-same ans higher but includes equal to
      • pollFirstEntry()-returns and removes first key/value
      • pollLastEntry()-returns and removes last key/value
      • descendingMap()-returns map in reverse order
Collections - (Queue)

Extends Collection

Usually FIFO


  • PriorityQueue - for Queuing without FIFO
  • sorts by natural order or a Comparator
  • methods
    • offer()- adds element to the PriorityQueue
    • poll()- returns & removes highest element from PriorityQueue
    • peek()- same as poll but without removal
Collections - (Collections Utility Class)

Has nothing to do with the Collection Class

Contains utility methods for working with Collections


  • methods
    • int = binarySearch(list, key)
    • int = binarySearch(list, key, comparator)
    • void = reverseList(list)
    • Comparator = reverseOrder()
    • Comparator = reverseOrder(comparator)
Collections - (Arrays Utility Class)

Has nothing to do with Array class

Contains utility methods for working with arrays


  •    methods
    • Array = asList(Array a)
    • void = sort(Obj[] o)
    • void = sort(Obj[] o, Comparator)
    • void = sort(prim[] p)
    • int = binarySearch(Obj[] o, key) must be sorted array
    • int = binarySearch(Obj[] o, key, Comparator).
    • int = binarySearch(prim[] p, key) must be sorted array
    • boolean = equals(Obj[] o1, Obj[] o2)
    • boolean = equals(prim[] p1, prim[] p2)
    • String = toString(Obj[] o)
    • String = toString(prim[] p)
Collections - (Backed Collections)

Creates a copy of a portion of a NavigableSet or NavigableMap

Copy and original are linked



  • SortedSet = subSet(start, [boolean], end, [boolean])
    • without boolean args, start is inclusive and end is exclusive. (if you pass one boolean, you must pass both)
  • SortedSet = headSet(end, [boolean])
    • default boolean is false, and is exclusive.
  • SortedSet = tailSet(start, [boolean])
    • default boolean is true, and is inclusive.


  • SortedMap = subMap(start, [boolean], end, [boolean])
  • SortedMap = headMap(end, [boolean])
  • SortedMap = tailMap(start, [boolean])

Generics - (Basics)
  • Used primarily for making "type safe" collections that can be checked for accuracy at compile time
  • The compiler will allow you to send a type safe Collection into a legacy, "non-type-safe" method
    • if the method alters the collection, theres a warning
    • if it doesn't, there is not
  • "Typing" doesn't exist at runtime.
  • polymorphism
    • doesn't apply to generic types
      • You CANNOT send a type <Dog> ArrayList to a method expecting a type <Animal>List
      • You can still add an object of the subtype of the generic type once successfully in the method

Generics - (Exceptions)

There is a workaround for sending generic subtypes into a method.


when not adding to the collection

  • use the wildcard symbol: "?" in the method signature
    • public void printAnimal(List<? extends Animal> a)


when you ARE adding to the collection

  • use wildcard AND super in the method signature
    • public void addAnimal(List<? super Dog> a)

declaring a method that takes anything that implements a certain interface

  • use wildcard and EXTENDS, not implements
    • public void doIt(List<? extends Serializable> a)
Generics - (Creating Generic Class)

Allows you to process many "types" of objects in a member collection without having to subclass for each type.


  • add <T> to the class definition
  • add <T> to the member Collection
  • add the member Collection to the constructor
  • build a getter method that returns T
  • build add method for Collection of type T
  • you may use more than one type in class definition(T, X)
  • wild card allowed in class def, but use T instead of ?
Generics - (Creating Generic Methods)

Allows you to process many "types" of objects in a passed collection without having to know the type of Collection.


  • add <T> after the access modifier in the method
  • create a Collection that holds type T
  • process it how you see fit.
  • wild card allowed in class def, but use T instead of ?
Inner Classes - (Basics)
  • Regular - is just a class defined inside another class
  • Method-Local - is just a class defined inside a method of another class
    • same method must instantiate an object of the class
  • Anonymous type 1 - creates a subclass of another class on the fly without giving that subclass a name
    • ClassName refOfSubclass = new ClassName(){methods to override};
  • Anonymous type 2 - creates an implementer of an interface on the fly without giving that implementer a name
    • InterfaceName refOfImplmenter = new InterfaceName(){methods to implement};
  • Anonymous arg defined - creates an implementer of an interfcace on the fly without giving that implementer a name, but does it inside a method that takes a type of that interface as an arg
    • Class c = new Class();
    • c.doIt(new InterfaceHere(){methods to implment});
  • Static - not really an inner class... just a static class that's scope is defined inside another class
Inner Classes - (Regular)
  • no static declarations period
  • from inside the inner class you can instantiate it like any other class
  • from outside the outer class (or inside the outer class but in a static method) you can only instantiate it through an outer class object
  • to reference the outer class' instance use Outer.this
  • to reference the outer class' instance
Inner Classes - (Method Local)
  • method must instantiate an object of the inner class to use it.
  • can't use the local variables of the method it's in, unless the local variables are marked as final so that they don't fall off the stack after the method is complete.
  • same access modifiers as a local variable.
  • if its declared in a static method it can only access the static members of it's outer class.
Inner Classes - (Anonymous)
Declared without any type at all

Regular Type 1
  • creates an anonymous subclass of another class
  • can define non overloaded methods, but can't use them because the ref variable is of the super of the anonymous inner class and can't see the more specialized methods.
  • syntax
    • class MainClass{
      • SubClass sc = new Subclass(){
        • void doIt(){
          • System.out.println("done");
        • }
      • };
    • }
Regular Type 2
  • same as type 1 only it implements an interface instead of creating a subclass.
Argument Defined
  • same as type1 or type2 except its created as an argument inside a method call.
  • class Food{
    • Chef c = new Chef();
      • c.cook(new Cookable(){
        • public void cookIt();
      • )};
    • }
  • }

Inner Classes - (Static)
  • not really an "inner" class, b/c it's really just a regular static class that's scope is nested within its outer class.
  • doesn't have access to instance variables and non-static methods b/c it's marked static
  • because it's marked static, doesn't have the implicit access relationship the other types of inner classes have.
  • can only be accessed from its outer class or an outer class object
  • Access from the outter class
    • Standard syntax: Inner i = new Inner()
  • Access from the inner class
    • Must go through enclosing class: Outer.Inner i = new Outer.Inner();
Threads - (Basics)

Individual, lightweight threads of execution with their own stack.

Very little is guaranteed from the JVM regarding threads.

The order of execution of multiple threads is NEVER guaranteed.


5 States

  • new - start() has not run yet
  • runnable - start() has run, but run() has not (considered alive)
  • running - run() has started but not completed
  • waiting/blocking/sleeping - taken out of runnable state by the JVM, but elligable to return.
    • wating - code tells the thread to wait for some event.
    • blocking - waiting on input from a stream for example
    • sleeping - code tells thread to sleep for some amt of time
  • dead - run() has completed

Thread object still exists and can run all its methods except start() even after its actual thread of execution is dead.

Threads - (Instantiation)

2 Ways to Instantiate

  • Extend java.lang.Thread
    • Rare since you don't usually require additional functionality
    • can overload run() but start() only runs original run()
    • calling run() explicitly works but wont' start a new thread
  • Implement Runnable Interface
      • MyRunnable r = new Runnable();
      • Thread t = new Thread(r);
    • The same Runnable can be passed to multiple Thread objects, which will each execute it separately.
  • Important Constructors
    • Thread()
    • Thread(Runnable target)
    • Thread(Runnable target, String name)
    • Thread(String name)
Threads - (Methods)
  • start()-thread moves to runnable state and will execute run() as soon as it has a chance
  • yield()-sends currently running thread from running to runnable, but doesn't guarantee it wont just immediately jump back into running
  • sleep(long mil)- currently running thread sleeps for mil milliseconds
    • throws checked exception
  • setPriority(int newPriority)- set priority of a thread for running once its runnable
    • thread takes priority of whatever thread created it
    • JVM might consolidate priorities
    • default priority is 5
  • join()- force currently executing thread to wait for calling thread to finish
  • run()-starts the new thread of excecution
  • currentThread()-returns currently running thread
  • getName()- return String with name of thread running that Runnable's run method
  • setName(String s)- set the name of thread running that Runnable's run method to s
  • getID()-returns the positive, unique, long, number that represents the thread throughout it's life
  • All Objects in Java have the following methods
    • wait()-causes a thread to give up it's lock and "wait" for a notify() from another object.
    • notify()-notify a thread (which one depends on the JVM) wait()ing on a lock that it's now available
    • notifyAll()-notify a thread (which one depends on the JVM) wait()ing on a lock that it's now available
Synchronization - (Basics)

Synchronization prevents any other threads from interacting with data while another thread is inside the method (even if it's sleeping)


To synchronize data, make the access private and synchronize the method changing the data


Key Points

  • only methods or blocks can be synchronized
  • each object has one lock
  • a class can have both synchronized and unsynchronized methods
  • a thread can have more than one lock
  • if a thread sleeps, it holds any locks it has
  • threads calling non-static synch'd methods in the same class only block if they are calling for the same object.
  • threads calling static synch'd methods in the same class ALWAYS block, b/c it's on a class basis, not object basis.
  • threads calling static and non-static synch'd methods will never block one another, b/c static is Class ref, and non-static is a "this" ref
  • when two threads are waiting on each other to release their locks on one another, that creates deadlock.
Synchronization - (Blocks)


  • synchronizing a block in a non-static method
    • private synchronized doIt(){
      • ...
      • synchronize(this){
        • ...
      • }
    • }
  • synchronizing a block in a static method
    • private static synchronized doIt(){
      • ...
      • synchronized(MyClass.class){
        • ...
      • }
    • }
Development - (Properties)

Retrieving and Setting System Properties

  • Properties p = System.getProperties();
    • p.list(System.out);
  • String s = System.setProperty("MyProp", "MyValue");
  • String s = System.getProperty("MyProp");
Development (JAR)
  • Creates a manifest from the top of the package directory
    • jar -cfm MyJar.jar Manifest.txt com/jason/*.class com/jason/Math/*.class


  • jar file can now be run from any directory
    • java -jar MyJar.jar
Development - (Static Imports)

You can import a class' static members


  • import static java.lang.System.out;
    • changes System.out.println to out.println
  • import static java.lang.Integer.*;
    • changes Integer.toHexString(42) to toHexString(42)


If two static classes have same named members, you'll get a compile time error, b/c it won't know which one to choose.

Supporting users have an ad free experience!