Cheat Sheet
This cheat sheet contains the most important takeaways that lead up to section ten.
Definitions
-
Class: blueprint from which you can create objects.
-
Object: an object is a thing that you can see or describe.
-
Field: class variable that describes an object.
-
Action: method (function) that represents what the object can do.
-
Constructor: runs when you create a
new
object.- Purpose: update every field of the newly created object.
-
this
: refers to the current object that's calling the constructor or method.- Purpose: useful when fields and parameters have conflicting names.
-
Copy Constructor: runs when you create an object.
- Purpose: copy every value from a
source
object into anew
object.
- Purpose: copy every value from a
-
Getter: method (function) that returns a copy of a
private
field's value. -
Setter: method (function) that updates the value of a
private
field. -
toString
: method that returns aString
representation of every field in an object.- Purpose: When you print an object, Java internally calls the
toString
method.
- Purpose: When you print an object, Java internally calls the
public
vs. private
-
public
: provides public access to a field or method from anywhere.- Constructors and methods tend to be
public
.
- Constructors and methods tend to be
-
private
: prevents direct access of a field or method outside of its class.- To protect the state of an object, fields tend to be
private
.
- To protect the state of an object, fields tend to be
The Big Three
If a class
has fields, you need to add:
-
Constructor -- to update the fields of a
new
object. -
Getters -- to get the value of a
private
field. -
Setters -- to set the value of a
private
field.
Debugging
- Continue: continues to the next breakpoint.
- Step over: steps over a line (see Debugging Exercise 3).
- Step into: steps into a function/cons.
- Step out: steps out of a function/cons.
- Restart: restarts the runtime.
- Stop: stops the runtime
Exceptions
Checked:
- Compile-time.
- Outside the application's control.
- Java forces you to
try-catch
the potential failure.
Unchecked:
- Runtime.
- Results from badly written code.
- Do not catch unchecked exceptions. Instead, fix your code.
Throwing Exceptions:
- Forces the caller to improve their code.
- Throw an
IllegalArgumentException
if the caller passes illegal values into a method/constructor. - Throw an
IllegalStateException
if the caller invokes a method at a bad time (object not in a valid state).
Mutable / Immutable Objects
- Mutable class: class with accessible mutators (setters).
- Immutable class: class without accessible mutators (setters).
Example 1:
An array is a mutable object.
Every array is a mutable object of a type[]
class.
It follows that arrays are vulnerable to the reference trap.
Example 2:
String
is an immutable class.
It follows that objects of the String
class are immune to the reference trap.
Reference Trap
The state of a variable should not change because you updated another.
Falling into a reference trap can:
-
lead to unpredictable behavior.
-
lead to variables changing when you don't expect them to.
-
leave you wondering: why is my code doing this?
Wrapper class
Wrapper: Immutable class that wraps around a primitive.
String
is not a wrapper class. But, it is immutable.
Rule:
- Use primitive when possible (faster and less memory).
- Use wrapper only when you need to (inside
ArrayList
...).
Array
vs. ArrayList
vs. HashMap
-
Array
- fixed.
- stores primitives and objects.
type[] values = new type[]
-
ArrayList
- resizable.
- stores objects.
ArrayList<object> values = new ArrayList<object>();
-
HashMap
- resizable.
- stores key-value pairs.
HashMap<Object, Object> pairs = new HashMap<Object, Object>()
Rule: use arrays when size is fixed (less overhead). Use ArrayList
when size can vary. Use HashMap
when there is parity between data.
HashMap
vs. TreeMap
vs. LinkedHashMap
Collection types that implement the Map
interface.
HashMap
- Unordered entries.
TreeMap
- Entries ordered based on what you specify.
LinkedHashMap
- Entries ordered based on insertion.
Rule: favor HashMap
because it offers the best performance. Use TreeMap
or LinkedHashMap
in the unique event that entries must be sorted.
Test-Driven Development.
- Identify meaningful test cases.
- Write a unit test for each test case.
- Write code to make the test fail.
- Write code to make the test pass.
- Refactor if necessary.
@Test
annotates a unit test. @Before
annotates a method that runs before each test.
Stream Pipeline
Instead of loops, you should pass elements into a pipeline:
collection.stream() .intermediateOperation(lambda expression) .intermediateOperation(lambda expression) .intermediateOperation(lambda expression) .intermediateOperation(lambda expression) .terminalOperation(lambda expression)
Intermediate operation: processes the sequence of elements and continues the pipeline.
Terminal operation: ends the pipeline and may return a final value.
Lambda expression syntax:
((parameter) -> {
code goes here
})
equals()
method
public boolean equals(Object obj) {
return false if parameter is null.
return false if parameter isn't instance of class.
typecast the object.
compare fields from both objects and return the result.
}
hashCode()
method
When you add an equals()
method, you must always add a hashCode()
method.
public int hashCode() {
return Objects.hash(fields go here);
}
Naming Conventions
- class:
CamelCase
- variable:
lowerCamelCase
- method:
lowerCamelCase
- constant:
UPPER_SNAKE_CASE
static
and final
static
: variable or method belongs to the class.final
: cannot be updated.
Inheritance
- Classes that share common fields should inherit from a parent class.
- Use
super()
to call the parent constructor from the child class. - Use
super.method
to call a parent method from the child class. - Interface: contract of behaviour. Classes that implement an interface must override every method inside of it.
- Polymorphism:
- an object can take its form or the class it inherits from.
- an object can take its form or the interface it implements.
abstract
class: Parent class that provides inheritance. The caller is forbidden from creating objects of anabstract
class.abstract
method: a child must override everyabstract
method.
Enums
Use an enum
to ensure a variable can only be a limited number of values.
Tips and Tricks.
-
Conditional assignment syntax:
variable = (comparison) ? value true : value false
. -
Syntax to directly pass an array into a method:
new String[] { element, element }
-
Syntax to directly return an array:
return new String[] { element, element }
-
Use the Java Code Generators extension to autogenerate
getters
,setters
,equals()
,hashCode()
, andtoString()
.