Skip to content

Instantly share code, notes, and snippets.

@IngmarBoddington
Last active January 24, 2016 19:51
Show Gist options
  • Save IngmarBoddington/3fdf510c9bc8ad206b38 to your computer and use it in GitHub Desktop.
Save IngmarBoddington/3fdf510c9bc8ad206b38 to your computer and use it in GitHub Desktop.
Notes for Java OCA Exam | Full Java 7 APi docs: http://docs.oracle.com/javase/7/docs/api/ | Tools: http://docs.oracle.com/javase/7/docs/technotes/tools/ | Get .jars here: https://oss.sonatype.org | Notation: <value>, [<optional value>]
Packages
========
- Encapsulate classes within a namespace
- Generally these take a reverse domain name format ending with class name (when fully qualified), e.g. com.company.classname
- Should map to directory structure and use reverse domain, e.g. root/com/company/classname
- java.lang is imported by default
- lowercase (though class name can have caps), underscores should be used for spaces
- java.* (core) and javax.* (standard extensions) are reserved
- It is better to be explicit when importing, rather than being implicit (using wildcards)
- 209 packages in Java SE 7 API
- Zero or one package delcarations per class, must be on first line
package <package>;
import [static] <package / class>; //e.g. import com.company.class or com.company.*
- Import a package, includes in source file at compilcation time
- Must be before class definition (and after any package statements)
- Static states to import only static members (Since 1.7)
Basic / Common Packages
=======================
Java AWT API / java.awt
- Subpackages: java.awt.color, java.awt.datatransfer, java.awt.dnd, java.awt.event, java.awt.font, java.awt.geom, java.awt.im, java.awt.im.spi, java.awt.image, java.awt.image.renderable, java.awt.print
- Paint basic graphics and images (heavyweight)
- Operating system dependant
- Superceded by Swing, but Focus subsystem still heavily used
Java Swing API / javax.swing
- Subpackages: javax.swing.border, javax.swing.colorchooser, javax.swing.event, javax.swing.filechooser, javax.swing.plaf, javax.swing.plaf.basic, javax.swing.plaf.metal, javax.swing.plaf.multi, javax.swing.plaf.nimbus, javax.swing.plaf.synth, javax.swing.table, javax.swing.text, javax.swing.text.html, javax.swing.text.html.parser, javax.swing.text.rtf, javax.swing.tree, javax.swing.undo
- Create lightweight GUI components
- Platform independant
- Many classes have same name as AWT but prefixed with a 'J'
Java Basic I/O / java.io
- Data streams, Files
Java Networking API / java.net
- Networking functionality
Java Utilities API / java.util
- Subpackages: java.util.concurrent, java.util.concurrent.atomic, java.util.concurrent.locks, java.util.jar, java.util.logging, java.util.prefs, java.util.regex, java.util.spi, java.util.zip
- Collections framework, event model, date/time functions
Java Language / java.lang
- Core classes and interfaces
Naming Conventions
==================
Identifiers Must
- Start with letter, $ or _, followed by letters, $, or _, or numbers
- Can't use a keyword
- Case sensitive
- Class - Cap, then camelcase, Noun - e.g. MonkeyWrench
- Interface - Cap, then camelcase, Adjective ending with able / ible if a capability else noun - e.g. Swingable
- Method - Lower, then camelcase, Verb generally - e.g. swingBat
- Instance / static variables - Lower, then camelcase, Noun - e.g. batWeight
- Parameters / local variables - lower then camelcase, Single words, acronyms, abbr. - e.g. dos (degree of swing), or localVar
- Generic type - Single uppercase letter, Normally T - e.g. T- e.g. BAT_WEIGHT
- Enumeration - Upper, then camel (set objects should be uppercase), Noun - e.g. enum Name {OBJECT_1, OBJECT_2}
- Package - All lower, reverse domain name (underscores, no spaces) - e.g. com.company.app
Standard Symbols
================
( ) Parentheses - General
{ } Braces - Code blocks / arrays initialization
[ ] Box Brackets - Array types / array initialization
< > Angle Brackets - Enclose generics
; Semicolon - EOL
, Comma - general seperator
. Period - Package name seperator, method selection
: Colon - loop labels
' ' Single Quotes - Character definition
" " Double Quotes - String definition
// Single line Comment
/* */ Multi line comment
/** */ Javadoc comment
Classes / Objects
=========================
- Encapsulate data and code
- Each class may extend up to one super class
- Each class may implement zero or more interfaces
- File and classname must match to compile (e.g. MyClass should be in MyClass.java)
- Objects which can be created are defined by classes, contains primitives, objects and methods
- Objects have no default value (must be instantiated to use else NullPointerException will be thrown)
- No fixed size in memory
- Instansiation, by use of new JVM allocated space
- Lives as long as another object has a reference to it (otherwise can be garbage collected)
//Create an instance of a class
<Type> <variableName> = new <Type>([<params>]);
//Define a class
[<accessModifiers] class <ClassIdentifier> [extends <SuperClassIdentifier>] [implements inteface1, ...] {
[data members]
[constructors]
[methods]
}
//Main method declaration (run by default) - can be overridden
public static void main(String[] args) {
}
//General method signature:
[<accessModifier>> [static] [<returnType>] <MethodName>([<ParameterList>]) {
}
- Parameters must have their type
- 0 to 255 parameters
- Can be primitive, object or enum
- Methods can return one or zero variables
- void for return type if there is no return expected (but can use return;)
- Must use return <variable> if not void
- Return must be primitive or object
- Can be assigned in calling code or ignored
- Use . to call methods on objects or static methods on classes
- Methods can be overridden, same name but different parameter lists (by number or types)
- Call parameter list (types and count) determines called method
- Overriding with same signature results in compiler error
Contructor methods
- Used to initialize an object, passed parameters from new call
- Every class must have at least once constructor
- Can be overloaded
- All objects have an implicit constructor if one not defined (overridden by defined constructors)
- Inserted at compile time, no args
- Shares name of class
- No return specified (including void)
- If no access modifier, then same as class
this
- Used to refer to current object instance
- this() can be used to call constructor of current class, on first line of a method
- Can only be used in a contructor
this.<instanceVariable> //Without this same name arguments in methods will override
this.method(<variableList>)
super
- Refers to current objects parent class
- User defined constructors can call super on 1st line (only, else compilation error)
- Default contructor calls super()
- If no super call in constructor, parent will be autocalled with super() (can lead to issues if there isnt one with no args to to override)
- Can be used in general methods to access parent methods
super.methodName(<parameters>)
this(<variableList>) //Calls contructor of current object
static
- Method or class variable belongs to class not instance
- Call using ClassName, not variable name (Classname.method())
- Unable to use this or super in static methods
- All instances of a class have access to it's class variables
contants
- Static value
- Cannot change
- declare as final to make constant
<accessModifier> static final <type> <variableName> = <expresions>
Inheritance
===========
- Reuse general classes to make more specific versions
- Reduce duplication, help maintenance
- More specific classes inherit all non-private instance variables and methods
- If overriding variable, remember to override methods using the variable to access
- A (child) class can only extend a single class (the base / superclass)
- Use same name and parameter list in child class to override super method
- Can still call parent method using the super keyword
class <className> extends <className> {
/* Body */
}
Abstract Classes
================
- Abtract classes must be extended, cannot be instantiated
- Concrete classes are regular class that can be instantiated
- May contain abstract methods (and implemented methods) (abstract methods can only exist in an abstract class)
- Can extend another abstract class without implementing methods
- Concrete child classes must implement all abstract methods (or compile error)
<accessModifier> abstract class <className> {
<accessModifier> abstract <returnType> <methodname>();
... more concrete or abstract methods
/* Body */
}
Interfaces
==========
- Define required set of functionalities of implementing class (all public my default, no need for modifier)
- A class can implement any number of interfaces
- Equilvalent of an abstract class with only abstract methods
- Concrete class must implement all methods in implemented interface (else compiler error)
- An abstract class which implements an interface does not need to define methods (but sub-concrete classes do)
- Use 'implements' and comma list, rather than 'extends'
- May extend other (multiple) interfaces (using extends)
- Can redeclare interface implementation in inherited class (though redundant)
- Can be declared as abstract (though redundant)
<accessModifier> interface <interfaceName> {
<accessModifier> <returnType> <methodName>(<variableList>);
...
}
Encapsulation / Access Modifiers
================================
- Encapsulation allows hiding of variables and methods (information hiding)
- Generally hide the implementation details but expose a public interface / Generally restrict access as much as possible to protect data
- A well encapsulated class as a clear single purpose
Access Modifiers (3 + default)
- private, access only in current class
- default (when none is specified), package-private, access only from code in the same package
- protected, access only in current class, package or subclasses
- public, no restrictions to access
- Compiler error if attempting access outside of restrictions
- Interface implementing methods must be public
//Use public setter and getter methods to give access to private variables
get<VariableName> or set<VariableName> (or is<VariableName> for get of boolean)
Polymorphism
============
- When an object can take the form / place of another
- A more specific version of an object can take the place of it's general form
- is-a relationship, e.g. adult extends human therefor adult is-a human
- Must only use common functionality
- Or objects which obey an interface can be used in common fashion
- Must only use functionality defined by the interface
- Can delcare an object as it's interface or a superclass but can then only use the functionality defined by that type
- Does not work for instance vars (just methods)
Casting
=======
- Casting can be used to use a more general as a more specific object (rather than the other way around as above)
- Primitives must be explicitly cast to be used as a less precise type (else done implicitly)
- When precision is lost, truncation of data occurs (most significant bits for whole numbers, decimal for floats / doubles)
- Primitives and wrapper classes can be explicitly casted but generally done implcitly
- Classes can be cast as more general type, but lose access to specific functionality
- And back again
(Class)<varName>
((Class)<varName>).<method> //inline
- Can only cast class to to instantiated class or superclass of it (else runtime exception)
Arrays / ArrayList
==================
- Hold a fixed number of a type of primitives or objects values
- Access (get or set) by an (zero based) index
- Using an index out of bounds will cause runtime exception
- Size cannot be changed once set, unless re-initialize
- Must use new to instantiate as considered objects (built in)
- Elements initially set to null, or zero in the case of primitive arrays
- Can put sqare brackets after variableName but less common
- Get length with .length variable (not method!)
<type>[] <identifier>; //No size int in declare statements
<type>[] <identifier> = new <type>[<size>];
<type> <identifier>[] = new <type>[<size>];
<type>[] <identifier> = new <type>[<size>]{<value>,...}; //Initialize with values, must be with declaration
<type>[] <identifier> = {<value>...}; //Initialize with values, must be with declaration
<type>[][] <identifier> = new <type>[<size>][[<size>]];
Boolean []ba[]; is valid (2 dimensional array)
- Multidimensional array, up to 256 deep
- Sub-arrays do not have to be same length (use initialise with values)
- Size does not have to be declared in sub arrays
e.g.
int[] ints = new int[2];
int[0] = 5;
int[1] = 7;
System.out.println(int[1]);
public static void arraycopy(Object <sourceArray>, int <srcPosition>, Object <destinationArray>, int <destPosition>, int <length>)
- Copies specified number and position of elements from one array to another
ArrayList is an (more) oo representation of an array
- Use in place of simple arrays unless memory / or speed is an issue etc
- From java.util, a collection class, List implementation
- Store objects or enums (no primitives - will be autoboxed if used)
- Can change in size
- Default contructor creates ArrayList with capacity of 10 elements
- Exception if element is out of bounds
- Zero-indexed
- Expensive to resize, (set initially if known size)
ArrayList<Type> <variableName> = new ArrayList<Type>([<size>]);
public int size()
- Return size of ArrayList (not the capacity!)
public void ensureCapacity(int <minCapacity>)
- Increases capacity
public void add(<value>)
- Adds element to ArrayList
public void add(<position>, <value>)
- Adds element to ArrayList at given position
- Other elements will move down to make room
public E remove(int <index>)
public boolean remove(Object <object>)
- Removes elements, moves elements to shorten size
Enumerations
============
Set of values, variable of type must equal a CONSTANT from the set
- Values don't have to be uppercase but should be
enum <identifier(Type)> = {<VALUE>, <VALUE>...}
e.g.
enum Name = {BLAH, WEEE};
Name variable = Name.BLAH
Literals
========
- Actual values, not variables
- Characters, decimal, hexadecimal, octal, Unicode (in all primitives but bools) as well as bools
- Can use underscores to format numbers whole numbers (not at start / end) (since 1.7)
Class Relationship Types
========================
- Direct Association - "has a", weak relationship, association
- Composition Association - "composed of", strong relationship, composition, life cycle management
- Agrregation Association - "part of", weak relationship, association
- Temporary Association - "dependancy of", weak relationship, association, e.g. return value
Multiplicities
- One-to-one - Association + Composition
- One-to-many - Association + Composition
- Many-to-many - Association
Navagability is where an object accessess another through it's methods, uni or bi directional
JDK Tools
========
javac [options] <name.java>
- Compile java file (creates bytecode file with .class extension in same directoy as default)
- location of output will use package structure
- Options
-d <location> = Specify location for output
java <name> [<args>] // Interpret / run compiled java
Use -D for runtime arguments
Use -cp / -classpath for location of required class definitions
Control Statements
==================
- All of these statements will work without curly braces if only one statement per condition / loop (On same line or on next line)
Expressions (Statements which are evaluated)
- Conditional (evaluate to boolean or Boolean which will be unboxed)
- Assignment (Assign a value to a variable)
- Iteration (evaluate to boolean or Boolean which will be unboxed)
; Can be used to represent a null statement (does nothing)
{ } encapsulate blocks of code (within control or otherwise)
Transfer of controls statements
- continue - exit for, enhanced for, switch, do, do while loop
- break - exit for, enhanced for, switch, do, do while statement
- return <expression> - return to calling code with given expression result
- Returned value must be of type delcared in method signature
If statements
- Optional else statement
- Assignment in condition will test result of assignment (compile error if not bool)
- Expressions in condition must evaluate to boolean (or error)
- Booleans are ok instead of booleans (unboxed)
if (<condition>) {
<statement>
...
} [else {
<statement>
...
}]
If then statements
- Assignment in condition will test result of assignment
- Expressions in condition must evaluate to boolean (or error)
- Booleans are ok instead of booleans (unboxed)
if (<condition>) {
<statement>
...
} else if (<condition>) {
<statement>
...
}
If then else statement
- Assignment in condition will test result of assignment
- Expressions in condition must evaluate to boolean (or error)
- Booleans are ok instead of booleans (unboxed)
if (<condition>) {
<statement>
...
} else if (<condition>) {
<statement>
...
} else {
<statement>
...
}
Switch statements
- Can use byte, int, short, char, Byte, Short, Integer, Character and String (post 1.7) + Enum
- Object types will unbox into primitive types on the fly
- Default instead of case for unmatched values, can be in any position
- Missing break statements will cause next case to execute
- Duplicate switch statements causes compiler error
switch (<var>) {
case <value>:
<statment>
break;
.....
}
For Loop
- Can declare variable outside of initialization to give extra scope (otherwise limited to inside loop)
- Use break to terminate, continue to skip to next
for (<initialisation>, <comparison>, <increment>) {
<statement>
...
}
Enhanced For Loop
- (for each, for in)
- Works for arrays, collections or objects implementing the iterable interface
- Use break to terminate, continue to skip to next
- The type in the intialisation must be valid for the type returned from the list
- The same or a primitive of same kind
for (<initialisation> : <variable>) {
<statement>
}
While loops
- Repeats whilst condition holds (is true)
while (<condition>) {
<statement>
...
}
Do while loops
- Statements will execute at least once
- Repeats whilst condition holds (is true)
do {
<statements>
...
} while (<condition>)
Labelled statements
- Don't use these if can be avoided
- Allow named statement to be acted on by continue or break transfer of control statements
e.g.
sillyLabel:
while (true) {
while (true) {
break sillyLabel:
}
}
Operators
=========
Assignment
- Type of value must be valid in respects to type of variable
<type> <variableName> = <value>;
Compound assignement
- Add or subtract from current value
- Type of value must be valid in respects to type of variable
<variableName> += <value>;
<variableName> -= <value>;
Basic arithmetic operators
<variableName> = <value> + <value>;
<variableName> = <value> - <value>;
<variableName> = <value> / <value>;
<variableName> = <value> * <value>;
<variableName> = <value> % <value>;
Prefix / postfix increment and decrement
- Prefix adds or minuses one before any other evaludation of an expression
- Postfix adds or minuses one after any other evaludation of an expression
++<variable>
--<variable>
<variable>++
<variable>--
Warning: - checker = checker++; vs checker = ++checker; (first does not increment)
y = ++x - add one to x, then assign to y
y = x++ - Assign x to y, then increment x
Basic relational operators
- Used to compare integers, floats and characters
- Evaluate to boolean
> More than
< Less than
>= More than or equal to
<= Less than or equal to
Equality operators
- For numbers, characters and Booleans
- Must evaluate to a Boolean
== Equal to
!= Not equal to
For reference variables, each side of operand must be the same reference to be equal
When comparing numbers of different types
- Check if only one is a double, if so convert other into a double
- (else) Check if one is a float, if so convert other into a float
- (else) Check if one is a long, if so convert other into a long
- (else) Convert both to int
Logical operators
- Must be boolean operands
&& / AND
|| / OR
- AND will not evaluate second operand if first is false
- OR will not evaluate seconf operand if first is true
- Using "Boolean operators" & / | will cause both to always be evaluated
Logical negation operator
- Reverses boolean (must be boolean or compiler error)
- Can be stacked (e.g. !!!!True gives True)
!
Bitwise
- << Shift left
- >> Shift right
- >>> Unsigned shift left
(<<< is not valid)
String concatenation
- Glues Strings together
String <variableName> = "<characters>" + "<characters>"
Left association rules apply in mixed use of + (concatenation and addition)
e.g. <numbericValue> + <numericValue> + <String> - numbers will be added and then concatentated
e.g. <String> + <numericValue> + <numericValue> - All will be concatenated (parantheses can be used to override)
Operator precedence
- Operators with a higher precedence are evaluated before those with a lower precedence
- Association determines which operand will be evaulated first
- Operator precedence can be overridden using parentheses
1. [ ] Array Index (left to right)
1. ( ) Method call (left to right)
1. . Member access (left to right)
2. ++, -- Postfix increment / decrement (right to left)
3. ++, -- Prefix increment / decrement (right to left)
3. ! Boolean not (right to left)
3. ~ Bitwise not (right to left)
4. (type) Case (right to left)
4. new Object creation (right to left)
5. *, /, % Multiplication, division and modules (left to right)
6. +, - Addition and subtraction (left to right)
6. + String concatentation (left to right)
7. <, <=, >, >= Logical operators (left to right)
7. instanceof Reference test (left to right)
8. ==, != Equality oeprators (left to right)
9. & Bitwise / Boolean AND (?)
10. | Bitwise / Boolean XOR (left to right)
11. ^ Bitwise / Boolean OR (left to right)
12. && Logical AND (left to right)
13. || Logical OR (left to right)
14. ? : Teneray operator (right to left)
15. =, += ... Assignment operators (right to left)
Types / Casting
===============
primitives - set size in memory and in range of possible values
- Faster use in calculations
- No encapsualted values or data
- Each must be set to be used with a method (or compilation error) (intance variables are intialised to defaults)
- byte
- 8-bit two's complement non-floating point integer
- Signed
- Default 0
- -128 to 127
- byte byte = 1; //Implicitly cast from int to byte
- short
- 16-bit two's complement non-floating point integer
- Signed
- Default 0
- -32,768 to 32,767
- short short = 1; //Implicitly cast from int to short
- int
- Default type for whole numbers
- 32-bit two's complement non-floating point integer
- Signed
- Default 0
- -2,147,483,648 to 2,147,483,647
- bytes, shorts and chars can be implicitly cast (but not longs, floats, doubles)
- long
- 64-bit two's complement non-floating point integer
- Signed
- Default 0L (or 0l)
- L or l used to differentiate from an int
- -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
- bytes, shorts, ints and chars can be implicitly cast (but not floats, doubles)
- float
- 32-bit
- 1.4e^-45 to 3.4e^38
- Default 0.0F (or 0.0f)
- F or f used to differentiate
- bytes, shorts, ints, longs and chars can be implicitly cast (but not doubles)
- Imprecise (especially at larger values)
- double
- default type for decimal numbers
- 64-bit
- 5e^-324 to 1.8e^308
- Default 0.0D (or 0.0f)
- D or d used to differentiate
- bytes, shorts, ints, longs, floats and chars can be implicitly cast
- Imprecise (especially at larger values), double precision of float
- char
- 16-bit Unicode character
- Unsigned
- Default 0
- \u0000 to \uffff, 0 to 65,535
- char declarations accept int, hex, oct, characters and unicode
- Single quotes around character to define
- Single quote literal must be escaped
- boolean
- true or false (default false)
- 1 bit value (size may differ)
Declare (body of class, instance variable, default 0 or false)
<type> <varName>;
Declare and set
<type> <varName> = <value>;
0x<int> - hexadecimal
0<int> - octal
0b<int> / 0B<int> Binary literals
(<type>) value //Explicit cast
- Primitives can be cast to a different type where there is no loss of precision implicitly
(else) if explicit cast can be used but precision will be lost
- Floats and doubles to int types would be truncated (not rounded)
- Objects variables cannot store objects of a different type
- Cast ints to floats in division else result will be truncated
- If cast is attempted to incompatible type, exception will be thrown
Each primitive has an associated wrapper object
- Byte, Short, Integer, Long, Float, Double, Boolean, Character
- Can be used interchangably (generally)
- Will be converted to primitves (unboxing)
- Primitives will be converted to wrapper class (autoboxing)
- Generally primitives should be used where possible as faster calculations and less memory
- Number types generally have methods for
<type>Value()
- These tend to have MAX_VALUE contant for max size
booleans must be in lower case (true|false)
floats can be flagged with D, d, f, F postfixes or (double) and (float) explicit casts
longs can be flagged with L or l postfixes
Variables
==================
- Objects are copied by reference, held in reference variables (where the variable stores the objects address)
- primitives are copied by value
- Local Variables in scope of in which delcared { -> } or in for statements
- Generally try to minimise scope of variables
- Not defaulted, must be intialised
- Method Parameter = values passed to method
- Instance Variables = Class level variables
- Defaulted
- If same name method and instance variable, method takes precedence
- Specify instance variable with this. qualifier
- Can declare / initialize multiple on same line:
<type> <varName>, <varName>;
Common Objects
==============
Strings represent 16-bit unicode character strings, declare using double quotes
- Immutable objects, values do not change (but can be overwritten)
- For mutable strings use StringBuilder
- For mutable thread safe strings use StringBuffer
- CharSequence is an interface for Strings, StringBuffer or StringBuilder object
- Runtime error if an index is specified out of range
String <variableName> = "<characters>";
String <variableName> = new String(); //Empty string
String <variableName> = new String(""); //Empty string
String <variableName> = new String("<characters>");
Characters within strings are zero indexed
public boolean equals(String <String>)
public boolean equalsIgnoreCase(String <String>)
- Case sensitive / case insensitive string matching
- Returns true if given String in String
public char charAt(int <int>)
- returns character at given index
public int indexOf(char <char)
public int indexOf(char <char>, int <fromIndex>)
public int indexOf(String <str>)
public int indexOf(String <str>, int <fromIndex>)
- returns index of search character or string
- specifying fromIndex skips characters before this place in index of string
- returns -1 if not found
public int length()
- returns length of string
- without parentheses on arrays returns size of array
public String concat(String <string>)
- Concatenates given string onto existing string
public String replace(char <target>, char <replacement>)
public String replace(CharSequence <target>, CharSequence <replacement>)
- Replace all matches of target with replacement
public boolean startsWith(String <prefix>, int <offset>)
public boolean startsWith(String <prefix>)
- Returns true if String starts with prefix
- Else false
public boolean endsWith(String <suffix>)
- Returns true if String ends with suffix
- Else false
public String substring(int <beginIndex>)
public String substring(int <beingIndex>, int <endIndex>)
- Returns substring of String from/to given indexes
public String trim()
- Removes whitespace from ends of String (\u0020)
public String toLowerCase()
public String toLowerCase(Locale <locale>)
public String toUpperCase()
public String toUpperCase(Locale <locale>)
- Returns the String in upper / lower case
int String compareTo(String <string>)
- lexicographically compares Strings, 0 if equal, < 0 if arg higher, > 0 if lower
public Boolean matches(String <regex>)
- Tests String against regex
StringBuilder - For mutable strings use StringBuilder
- Methods with extend length beyond currently cpacity increases capacity
new StringBuilder();
new StringBuilder(CharSequence <charSequence>);
new StringBuilder(int <capacity>);
new StringBuilder(String <string>);
- Created with a default capacity of 16
- Creating with CharSequence or String makes an initial capacity of the string length + 16
public StringBuilder append(Object <object>)
public StringBuilder append(String <string>)
public StringBuilder append(StringBuffer <stringBuffer>)
public StringBuilder append(CharSequence <charSequence>)
public StringBuilder append(CharSequence <charSequence>, int <startIndex>, int <endIndex>)
public StringBuilder append(char[] <characterArray>)
public StringBuilder append(char[] <characterArray>, int <offset>, int <length>)
public StringBuilder append(boolean <boolean>)
public StringBuilder append(char <character>)
public StringBuilder append(int <int>)
public StringBuilder append(long <long>)
public StringBuilder append(float <float>)
public StringBuilder append(double <double>)
- All parameter types are simply added as literals
- floats and doubles will have (.0) of int given but specified as type
- Specifying start and end index with string (CharSequence) with append only those characters from the string
- Specifying ofset and length with character array will only append only those characters from string representation
public StringBuilder insert(int <index>, char[] <stringArray>, int <offset>, int <len>)
public StringBuilder insert(int <offset>, Object <obj>)
public StringBuilder insert(int <offset>, String <string>)
public StringBuilder insert(int <offset>, char[] <string>)
public StringBuilder insert(int <offset>, CharSequence <chars>)
public StringBuilder insert(int <offset>, CharSequence <chars>, int <start>, int <end>)
public StringBuilder insert(int <offset>, boolean <boolean>)
public StringBuilder insert(int <offset>, char <char>)
public StringBuilder insert(int <offset>, int <int>)
public StringBuilder insert(int <offset>, float <float>)
public StringBuilder insert(int <offset>, double <double>)
- Specifying start and end index with string (CharSequence) with append only those characters from the string
public StringBuilder delete(int <start>, int <end>)
- Deletes character in specified range
public StringBuilder deleteCharAt(int <index>)
- Deletes character at given index from string
public StringBuilder reverse()
- Reverses characters in string
BigDecimal should be used for currency (not floats or doubles due to precision)
- Slower than primitive but more accurate
- Can store as much as memory allows
BigInteger should be used for integers which are or may grow larger than the limit of a long
- Can store as much as memory allows
All objects!
- All objects extend the standard Object class (including user defined objects)
- Methods can be chained (assuming correct return types)
- Standard methods must be overridden to alter behaviour
toString - returns string representation of object
- Automatically invokes when object is used in a String context (e.g. System.out.println(object);
equals
- When comparing strings should use equals, compares string of characters
- Compare Comparable (Strings, Wrappers ++) or same reference
- Strings are not comparable with StringBuffer / String Builder
==
- Should use == for same references and primitives
- Checks if same instance of an object
hashCode
HashMap
- Key, value store
HashMap<<keyType>, <valueType>> <varName> = new HashMap<<keyType>, <valueType>>;
put(<key>, <value>)
//Add
Math
- Mainly static maths functions
Double Math.sqrt(x)
Exceptions
==========
- Exceptions are thrown when a program violates the semantic contraints of the language
- Interrupts normal flow of program
- Exceptions and Errors extend Throwable object
- Throwable objects implement Serializable
- More specific exceptions extend Exception
- Errors and RuntimeExceptions are unchecked all others are checked
- Checked exceptions are checked at compile time
- Unchecked exceptions occur at runtime
- Unchecked exceptions / errors not generally caught
- Unchecked Exceptions
- RuntimeExcepVtion - Error due to running code
- NumberFormatException - String converted to number was in incorrect format
- Arithmetic Exception - throw by divide by zero ++
- IllegalArgumentException
- ArrayIndexOutOfBoundsException
- IndexOutOfBoundsException
- IllegalStateException - Call made when object in incorrect state
- ClassCastException - WHen attempting to cast an object to a subclass of which is not an instance
- NullPointerException
- Checked Exceptions
- CloneNotSupportedException - When attempting to clone an object than cannot be cloned (Deep copy / exact copy)
- NoSuchMethodException - Not defined method
- InterruptedIOException - If thread is interrupted (has a bytesTransferred field)
- ClassNotFoundException - Not defined class
- IOException - Failed IO
- FileNotFoundException - Error due to file not existing
- IIOException(<string>) - Failure in readin / writing DOES NOT HAVE NO ARG CONSTRUCTOR
- SQLException - SQL Error
- FontFormatException
Unchecked Errors
- AssertionError - When assertion fails
- ExceptionInInitializeError - When an exception occurs in a static initializer
- VirtualMachineError([string]) - Thrown when a JVM error occurs
- InternalError([string])
- OutOfMemoryError([string])
- StackOverflowError([string])
- UnknownError([string])
- OutOfMemoryError - When garbage collection is unable to free up any space
- NoClassDefFoundError - No class deifnition found at compile time
Custom Exceptions should define a constructor which no arg and another with a single String arg
- Extend Exception for checked exceptions, RuntimeException for unchecked exceptions
- End name with 'Exception'
To throw:
throw new <Type>([String]); //Must be Throwable else compile error
Exceptions can be thrown up into calling code until main and then uncaught (JVM kills application)
Methods with throw exceptions must catch or pass to calling code
<method>() throws <ExceptionType {}
try-catch, catch block catches exceptions thrown in the try block
try {
//Code
throw ...
//Code after exception is thrown will not be run
} catch (<ExceptionType> <variableNameNormallyAcronymOfExceptionType>) {
//Handle - do not silence the error
} ...
- Catch more specific Excepption types first, up to Exception last
- But should be catching specific exceptions dependant on code
- If exception class not found, looks up superclasses
- Can add finally block which will always be executed, try block must have catch or finally block to compile
getMessage - return exception message
toString - return exception messages and class name
printStackTrace - print detailed message, class name and stack trace
Can also try with resources (must implement the AutoCloseable interface) - Since 1.7
try (<initialize AutoClosable object) {
/* Code */
} catch (<Exception>) {
/* Code */
}
Can also have multi-catch clauses
} catch (<Exception> | <Exception> ...) {
/* Code */
}
Questions
=========
http://www.gocertify.com/quizzes/oracle/ocajp-java-quiz-1.html
http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=303&p_certName=SQ1Z0_803v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment