CS300-Java
1. Array and Methods
Basic structure
1 | |
Input
import java.util.Scanner;
`Scanner scnr=new Scanner(System.in);
scnr.nextInt();
Method signature errors
1 | |
Perfect Size Arrays
int[] highTemps={1,2,3}
Must initialize when declaration, used when size of array fixed
could be returned
passing a array reference : could update the content of original
passing a primitive can’t
toCharArrays(String);requires a perfect size
split() (instance method) split a String to Strings by defining separators
OverSize Arrays
elements used is less than or equal to the memory allocated
elements are located in 0 - size-1 ONLY (compact)
1 | |
toString(requires int array and size);

for arrays, use Array.equals(a,b);->true
for objects , equals are rewrite to compare the content rather than the reference.
String pool: once find the same content, just point the previous
a way to prevent this: use new String(“a”);
Integer Wrapper Pool: from -128 to 127
Float, Double don’t have this
Java.util package
Tools
Arrays : sort, binarySearch, equals, toString
Objects : isNull()
Collections
List: ArrayList,LinkedList
Set
Map
Queue
import java.util.ArrayList;
import java.util.Arrays;
2. Objects
Java variables
primitive : int,double, char
reference : refer to an object
Wrapper class object and String are immutable
when we try to change like
1 | |
the reference will be changed and point a new object, previous -> GC
1 | |
a==b – compares reference - false and seldom use
a < b – compare value $\checkmark$
a==5 – $\checkmark$
compare content – use equals() or compareTo();
0 - equal
<0 - a<b;
Static vs Instance Method

Wrapper class conversions
autoboxing: Integer s=50;
unboxing: s>50; double t = 100-s;
s=s+1; – auto and un
boxing on null -> NullPointerException
Converting to primitives and string
1 | |
ArrayList
import java.util.ArrayList;
ArrayList<Integer> vals = new ArrayList<Integer>()
1 | |
Heap & Stack
memory regions:
- Code
- Static memory : static variables
- The Stack(Automatic memory) : local variables, reference variables in main
- The Heap(free store) : Object
Exception Handling
try - will exit immediately when throwing an exception
catch - exception handler
0/0 ->exception
0.0/0.0 ->NaN
throw new Exception("A message here").

1 | |
Unchecked vs Checked Exceptions
Checked : need to handle within the program
Unchecked : not expected to catch and handle when running
Ex.
- NullPointerException
- ArithmeticException
- IOError
- ClassCastException
- IllegalArgumentException
throws

throws InvalidNegativeInputException, NaNException: No orders
Finally
always run the code when a exception occurs BEFORE return or code crash


Return and New Exceptions will be replaced the one in the Finally
Before return or break or continue, the code in finally will be still operated.
Code Crash: Note that 3 is before crashing

Define exception
1 | |
Closing files
1 | |
try with resources
try (Scanner fileScnr = new Scanner(new FileInputStream("input.txt")))
Java short-circuiting
1 | |
if we replace || to &&, it can’t work
Class
`Restaurant favLunchPlace = new Restaurant();
Field(or Member Variables):
field 1 field 2 private field(can’t be accessed by class users but member method)
Method
Field and method subsitute the class members
Private Field & Static Field
1 | |
s could not be used outside of the class.
p is static and used for every object of this class. They have the same one.
Those kind of variable could be used before declaration
Mutators Accessors Constructors
mutator – change the value
accessor – get without changing
constructor : (if you don’t define, the compiler will generate automatically)
1 | |
Constructor overloading
If any constructor defined, no-arg constructor should also be defined
Inheritance
Derived class <- Base Class
1 | |
can be derived ONLY 1 class
Derived class can only access parameters that is not private of the Base.
Members: Protected : Accessible only in derived class and main
Classes : Usually No specifier or public
Override
The @Override annotation causes the compiler to produce an error when a programmer mistakenly specifies parameters.
Annotation means it will be viewed by the compiler, if we don’t write the @Override and the overriding is failed, then it will compile successful.
However, it will be hard to find the bug, so it is good to use @Override.
call the overridden method just the base(base of base is incorrect): `super.method();
Object Class
Two common methods:
- toString() returns the String representation of this object like java.lang.Object@372f7a8d
- equals(otherObject) compares the reference
println() automatically calls toString() and help to decrease the risk of NullPointerException (String concatenation as well)
But String s = classname is $\times$ !!!
Polymorphism
ArrayList <baseclass> inventoryList = new ArrayList <baseclass>
- Runtime polymorphism
iterate the objects in the arraylist, the JVM will automatically use different method(overriding) due to different class type, this is called Runtime polymorphism
Abstract Class
a class that guides the design of subclasses but cannot itself be instantiated as an object
Abstract Method: not inplemented in the base class and need to be overridden in subclasses.
1 | |
Subclasses have things common and required – use Abstract Classes
Subclasses only have additional features – inheritance is enough
Public / Protected : All subclass need to override the abstract method
Default : Subclass in a package need to override the abstract method
Private : Absolutely wrong.
Overriding on multiple classes
1 | |
A overide B and B override Object, But they need to have same method signature, which means in A equals(B b) is wrong.
Generic methods
A generic method is a method definition having a special type parameter that may be used in place of types in the method

The Java compiler internally replaces type parameters like <ElemType> with the Object type.
Type erasure is the compiler’s replacement of type parameters with a common base type.
Type Erasure
The generic will only be a description when compiling, and during runtime, the generic list will be erased to Base Type(Usually Object).
1 | |
This will cause a compiler error: a and b will be recognized as Object during runtime.
But if we use the toString, it will use the Overriddened String toString because of polymorphism.
Bounded type parameters
1 | |
Generic classes

Pair<String> username = new Pair<String>("deft", "bagel");
Interface
1 | |
Interface does not require the write an abstract
Algorithm Analysis
O notation
determined by the highest order term of the function, if it is a product of several factors, the constant will be omitted. Same growth rate has save O notation.
O(N) = O(100N) = O(N+99999)



constant time operation O(1)
an operation that, for a given processor, always operates in the same amount of time, regardless of input values.
assignment of variable - constant
multiplication of fixed number - constant
- loop - not constant
- String concatenation - not constant
- LinkedList.get(index) - not constant
- list.add(0, 100) - not constant
- calculations on unknown int - constant
1 is not constant because we could not know the actual value of variables after compiling.
2 3 4 is not constant because there are n manipulation.
worst-case runtime of an algorithm is the runtime complexity for an input that results in the longest execution
O(log N) = O($log_2$N) = O($log_{10}$N) = O($log_e$N)
O(N + M) = O(max(N,M))
Upper and lower bounds
Lower Bounds: single term polynomial and bounds T(N) as tightly as possible
e.g.
T(N) = 5N+4 -> O(N) and O(9N)
T(worst: 3$N^2$ + 10N+17, best: 2$N^2$ + 5N+5) -> O(2$N^2$) and O(30$N^2$)

Recursion
recursive method
method call other methods, including calling itself
Binary Search
1 | |
base case: without applying itself to a smaller subproblem
Sorting
Selection Sort
Select smallest index -> swap array[i] and array[smallestindex] ->sort array from i+1 to length - 1.
Worst : N - 1 swaps
O($N^2$)
Insertion Sort
1 | |
Worst : $\frac{N(N-1)}{2}$ swaps
O($N^2$)
Merge Sort
1 | |
Quick Sort
1 | |
Best : O(logN * N)
Worst : O(N^2)
Heapsort
1 | |
O(NlogN)
Linked List

ArrayList : faster access
LinkedList : faster removing and appending
ArrayList:
add(a, b); add b at index a
2: remove(Object) remove(index)
remove Integer ArrayList:
1 2 3 -> 1 3
remove(1) or remove(new Integer(2))
Array-Based lists
list: length
array: use allocation size and >= length
append(list, element)
resize() -> allocation size * 2 usually but can’t use directly
prepend(list, element)
insertAt(list, index, element)
search(list, item)
remove(list, index) – change length but do not change allocation size
Singly-linked lists
a type of positional list
first node - head
last node - tail
numberList - head and tail
element 1 - data , next
element 2 - data , next
…
element N - data , next = null

Linked List
1 | |
1 | |
1 | |
Doubly-linked lists

Stacks, Queues and Iterators

full stack: length -> max
resize: length == allocationSize

Binary Tree
Binary Search Tree
all keys in left subtree < key < all keys in right subtree
edge : link to a child.
depth : number of edges from root. Roots’ depth = 0.
level : all nodes in same depth.
height : maximum of depth in a tree.
Every node contains 0 or 2 children -> full
All leaves in same level + every internal has 2 children -> perfect
Perfect without last level + last level displays from left to right -> complete
subtree: all descendants with the root of them