Docs - james-bern/CS136 GitHub Wiki
Java is an object-oriented, statically typed, garbage-collected programming language.
A fixed-size sequence of elements of the same type.
class ElementType[] {
final int length;
}
-
int[] array = new int[16];
creates and zero-initializes a new array (in this case, of 16 ints) -
double[] array = { 42.0, 0.0, -1.0 };
creates and initializes an array (in this case, of 3 doubles) -
array[i] = foo;
sets the i-th element of an array (in this case, to foo) -
foo = array[i];
gets the i-th element of an array (and, in this case, assigns it to foo) -
PRINTS(array);
prints an array (it callsSystem.out.println(Arrays.toString(array));
)
int[] array = { 3, 9, 81 };
int[] array = new int[8];
for (int i = 0; i < array.length; ++i) {
array[i] = i;
}
PRINT(array); // { 0, 1, 2, 3, 4, 5, 6, 7, }
int[] array = { 1, 2, 3, 4, 5 };
// reverse array in place
for (int i = 0; i < array.length / 2; ++i) {
int j = (array.length - 1) - i;
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
PRINT(array); // { 5, 4, 3, 2, 1, }
Internally, this is an array of characters.
class String {
int length(); // Number of characters in the string
char charAt(int index); // Get character at index (like array[index])
String substring(int start, int onePastEnd); // Get substring (like for (int i = start; i < onePastEnd; ++i))
int indexOf(String str); // Get index of the first occurrence of the substring (returns -1 if not found)
}
String string = "Hello"; // makes a new String
PRINT(string.length()); // 5
PRINT(string.charAt(1)); // 'e'
PRINT(string.substring(0, 3)); // "Hel" (characters 0, 1, 2, but NOT 3)
PRINT(string.substring(1, 3)); // "el" (characters 1, 2, but NOT 3)
PRINT(string.indexOf("ell")); // 1 (substring "ell" starts at index 1)
PRINT(string.indexOf("Kahoot")); // -1 (substring "Kahoot" NOT found)
The +
operator is oddly convenient (though also slow; consider StringBuilder if concatenating a lot of large String's)
String string = "Hello" + 3; // "Hello3" (calls "Hello".concat(Integer.toString(3)))
String string = "" + 3; // "3"
System.out.println("You have been asleep for " + numberOfDaysInRoom + " days.");
Generic data structures from Java's standard library
An automatically-expanding array, aka a stretchy buffer, dynamic array, vector, ... Internally, this is an array.
โ ๏ธ Be very careful removing (or adding) elements from/to an array list while you are iterating over it! (If you find yourself wanting to do this, there is probably a different (better) approach!- (If you must delete while iterating, iterate backwards.)
โ ๏ธ You can only calllist.set(index, ...);
iflist
's size is at leastindex + 1
. Otherwise you will get an out of bounds error just like if you have calledarray[index] = ...;
class ArrayList<ElementType> {
void add(ElementType element); // Adds a new element to the back of the list.
void add(int index, ElementType element); // Add (insert) a new element into the list at a specific index.
ElementType get(int index); // Get the element at a specific index. Similar to `array[index]`.
void set(int index, ElementType element); // Set the element at a specific index. Similar to `array[index] = element;`
void remove(int index); // Remove the element at a specific index. NOTE: Careful doing this while iterating over the list!
int size(); // Get the number of elements currently in the list.
boolean isEmpty(); // Get whether the list is empty (size() == 0).
}
ArrayList<String> list = new ArrayList<>();
PRINT(list); // []
list.add("Hello");
list.add("World");
PRINT(list); // [Hello, World]
list.add(1, "Cruel");
PRINT(list); // [Hello, Cruel, World]
PRINT(list.size()); // 3
PRINT(list.get(1)); // Cruel
list.remove(0);
PRINT(list); // [Cruel, World]
list.set(1, "Summer");
PRINT(list); // [Cruel, Summer]
A basic stack. Push to the top. Pop from the top. (Peek at the top.) This extends ArrayList (ish).
โ ๏ธ I find the output ofPRINT(stack);
very confusing (feels "upside-down"). Careful printing stacks; see example code below to understand what happens.
class Stack<ElementType> extends ArrayList<ElementType> {
void push(ElementType element); // Push (add) a new element to the top of the stack.
ElementType pop(); // Pop (remove) the top element of the stack and returns it.
ElementType peek(); // Peek (look) at the top element of the stack (without removing it) and return it.
int size(); // Get the number of elements currently in the stack.
boolean isEmpty(); // Get whether the stack is empty (size() == 0).
}
Stack<String> stack = new Stack<>();
stack.push("Hello");
stack.push("Cruel");
stack.push("World");
PRINT("BOTTOM " + stack + " <-> TOP"); // BOTTOM [Hello, Cruel, World] <-> TOP
PRINT(stack.peek()); // World
PRINT(stack.size()); // 3
PRINT(stack.pop()); // World
PRINT(stack.pop()); // Cruel
PRINT(stack.pop()); // Hello
A basic First In First Out queue. Add to the back. Remove from the front. (Also peek at the front.)
- (Java doesn't actually have this data structure, so I'm using something more complicated and leaving out a bunch of functions so we can pretend.)
class ArrayDeque<ElementType> {
void add(ElementType element); // Add (enqueue) a new element to the back of the queue.
ElementType remove(); // Remove (dequeue) the front element of the queue and return it.
ElementType peek(); // Peek (look) at the front element of the queue (without removing it) and return it.
int size(); // Get the number of elements currently in the queue.
boolean isEmpty(); // Get whether the queue is empty (size() == 0).
}
ArrayDeque<String> queue = new ArrayDeque<>();
queue.add("Hello");
queue.add("Cruel");
queue.add("World");
PRINT("FRONT <- " + queue + " <- BACK"); // FRONT <- [Hello, Cruel, World] <- BACK
PRINT(queue.peek()); // Hello
PRINT(queue.size()); // 3
PRINT(queue.remove()); // Hello
PRINT(queue.remove()); // Cruel
PRINT(queue.remove()); // World
A map/dictionary (similar to Python or Lua's dictionary). Internally, this is an array.
class HashMap<KeyType, ValueType> {
// Put (add, insert) a new key-value pair into the map.
// NOTE: Can also be used to update a key's value.
void put(KeyType key, ValueType value);
// Get (lookup) a key's value in the map.
// NOTE: Returns null if map doesn't contain key.
Value get(KeyType key);
// Get the (unordered) set of all keys.
// NOTE: Use this to iterate through all keys.
// for (KeyType key : map.keySet()) { ... }
Set<KeyType> keySet();
// Get the number of key-value pairs currently in the hash map.
int size();
// Return whether the map contains a key-value pair with the specified key.
boolean containsKey(KeyType key);
// Return whether the map contains a key-value pair with the specified value.
boolean containsValue(ValueType value);
// Get (lookup) a key's value in the map.
// NOTE: Returns default value if map doesn't contain key.
ValueType getOrDefault(KeyType key, ValueType default);
}
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("Ekans", 23);
map.put("Arbok", 24);
map.put("Jigglypuff", -1);
map.put("Jigglypuff", 39);
PRINT(map.get("Jigglypuff")); // 39
PRINT(map.get("Ash Ketchum")); // null
PRINT(map.size()); // 3
for (String key : map.keySet()) {
PRINT(key);
}
// Jigglypuff
// Arbok
// Ekans
Cow.Java is a simple Java dialect and game library designed to prepare you to program in C
- Use
boolean
for truth values,double
for real numbers,int
for (signed) integers, andchar
for characters- NOTE: do NOT use
byte
,short
,long
, orfloat
- NOTE: do NOT use
-
PRINT(thing);
is likeSystem.out.println(thing);
but can actually print arrays, prints regularchar
's like'A'
(instead of printingA
), and prints the null char like'\0'
(instead of printing nothing)
-
Number MIN(Number a, Number b);
returns the lesser of the two arguments (can beint
ordouble
) -
Number MAX(Number a, Number b);
returns the greater of the two arguments (can beint
ordouble
) -
Number ABS(Number a);
returns$|a|$ (can beint
ordouble
) -
double SQRT(double a);
returns$\sqrt{a}$ - NOTE: to square a number use
a * a
-
int MODULO(int a, int b);
is likea % b
but works for negative numbers (like Python's%
๐) -
int ROUND(double a);
rounds$a$ to the nearest integer -
boolean ARE_EQUAL(double a, double b);
checks whether$a \approx b$ (allows for "floating point error"); returns$(|a - b| < \varepsilon)$ for a small$\varepsilon$
-
void beginFrame();
can be used to create a game/app with the classic setup-loop structureclass HWXX extends Cow { public static void main(String[] arguments) { // setup double time = 0.0; while (beginFrame()) { // loop time += 0.033; drawCircle(mouseX, mouseY, 32.0, colorRainbowSwirl(time)); } } }
-
boolean keyPressed(char key);
returns whetherkey
was pressed on your keyboard during the previous frame-
keyPressed('A')
returns whether the key labeledA
was just pressed on your keyboard- NOTE: do NOT use
keyPressed('a')
(there is no key labeleda
on your keyboard) - NOTE: for uppercase and lowercase use
(keyHeld(SHIFT) && keyPressed('A'))
and((!keyHeld(SHIFT)) && keyPressed('A'))
- NOTE: do NOT use
-
-
boolean keyHeld(char key);
returns whetherkey
is currently held on your keyboard boolean keyReleased(char key);
-
boolean keyToggled(char key);
is useful for creating "toggle switches"- NOTE:
keyToggled('A')
will befalse
ifA
has never been pressed,true
if it has been pressed once, `false if it has been pressed twice, ...
- NOTE:
-
boolean keyAnyPressed;
is whether any key was pressed during the previous frame
For most keys, you can use a char
, such as 'A'
for "the A key" and ' '
for "the space bar." For other special keys, you can use these constants.
char ENTER, TAB;
char BACKSPACE, DELETE;
char CONTROL, COMMAND, ALT, SHIFT;
char LEFT_ARROW, RIGHT_ARROW, UP_ARROW, DOWN_ARROW;
-
double mouseX;
is the x-coordinate of the current mouse position- NOTE:
$x$ increases as we move from left to right
- NOTE:
-
double mouseY;
is the y-coordinate of the current mouse position- NOTE:
$y$ increases as we move from bottom to top
- NOTE:
-
boolean mousePressed;
is whether your left mouse button was pressed during the previous frame- NOTE: This is true for exactly one frame after you press the mouse
-
boolean mouseHeld;
is whether your left mouse button is currently held- NOTE: This starts being true on the same frame as
mousePressed
- NOTE: This starts being true on the same frame as
boolean mouseReleased;
-
double mouseScrollAmount;
is the how far the user scrolled on the mouse wheel (or trackpad) during the previous frame
Simple drawing functions.
-
void drawLine(double x1, double y1, double x2, double y2, Color color, double thickness);
draws a line connecting$(x_1, y_1)$ and$(x_2, y_2)$ ;thickness
is in something like pixels -
void drawCircle(double x, double y, double radius, Color color);
draws a circle with center$(x, y)$ and radius$r$ -
void drawRectangle(double x1, double y1, double x2, double y2, Color color);
draws a rectangle with corners$(x_1, y_1)$ and$(x_2, y_2)$ -
void drawTriangle(double x1, double y1, double x2, double y2, double x3, double y3, Color color);
draws a triangle with vertices$(x_1, y_1)$ ,$(x_2, y_2)$ and$(x_3, y_3)$ -
void drawString(String string, double x, double y, Color color, int fontSize);
draws a string at position$(x, y)$ with thefontSize
in pixels -
NOTE: The style arguments
color
andthickness
are optional (they default to BLACK and a reasonable thickness).
My simple color class. We will just use the constants it provides in our calls to the drawing functions.
Color BLACK, BLUE, BROWN, CYAN, GREEN, MAGENTA, ORANGE, PURPLE, RED, YELLOW, WHITE;
-
Color colorRainbowSwirl(double time);
is a cyclic rainbow color map.
โ ๏ธ If you want to make a new Color object, you can call new Color(double red, double green, double blue)
, where each component ranges from 0.0 to 1.0
-
canvasConfig(double left, double bottom, double right, double top, Color color, int maxDimensionInPixels)
; can be used to set up the canvas coordinate system and size- NOTE: the left-bottom corner of the canvas is
$(x_\text{left}, y_\text{bottom})$ in "world units" - NOTE: the right-top corner of the canvas is
$(x_\text{right}, y_\text{top})$ in "world units" - NOTE: the canvas is cleared to
color
eachbeginFrame()
- NOTE: the longer side of the canvas is
maxDimensionInPixels
pixels long on your screen - NOTE: the
color
andmaxDimensionInPixels
arguments are optional (they default toWHITE
and512
) - NOTE: calling this function at all is optional (the other arguments default to
-256
,256
,-256
,256
)- NOTE: but if you're going to call this function, put it just above
while (beginFrame()) { ... }
- NOTE: but if you're going to call this function, put it just above
- NOTE: the left-bottom corner of the canvas is