Cheat Sheet
Objects
An object describes a new data type with its own
fields and methods.
- Have constructors
- Have a toString() method
- Have an equals(Object) method
- Operator == compares if classes are the same instance
- May have a value of null
- Are passed by reference
- Fields without keyword static are by instance
- A class can extend from only one class
- If extends not used, then the class extends java.lang.Object
- All classes extend from java.lang.Object
- If class A extends B, then A is the subclass and B is the superclass
- If class A extends B, then A inherits from B
- Add @Override for checking that a method overrides
Primitive Types
- There are 8:
- boolean,
- byte,
- char,
- short,
- int,
- long,
- float,
- double
- Are passed by value
Interfaces
An interface is a specification for a class, with no implementation.
- Interface names are type names
- Interfaces may not be instantiated
- All interface methods are public
- Interface only have methods, and the methods
do not have bodies, i.e. they have ";" instead of "{}"
- You can implement any number of interfaces
Casting
A cast changes one type to another. For objects, this only changes the type
of the reference. For primitive types, it changes the value.
- int n = (int)3.14; converts a double to an integer.
- A a = new B() allowed only if B extends A.
- A a = (A)new B() is a cast. The compiler will allow it, but the runtime may not.
- if(B instanceof A) checks if the runtime will allow the cast.
toString() methods
- Don't print, return a String
- Use String.format()
Arrays
- Use StringBuilder (see Alist.java
- Autoboxing: int => Integer, short => Short, byte => Byte, char => Character, etc.
- Number is superclass of Integer, Short, Double, etc.
- assert statement: enabled by -ea.
- Understanding error messages: the stack and stack traces.
More Arrays
- Scope of variables
- List and ArrayList classes (see ArList.java
- Packages (see UseArList.java
- The stack and exceptions (see Npe.java
Still More Arrays
- Enhanced For Loops
- Interface Iterable, see Alist2.java
- Interface Iterator, see Alist2.java