There is a lot of syntax in Java and we don't want you to have to memorize it all. The interesting part about learning to program is instead learning the paradigms that allow computers to solve problems. This document is meant to serve as a reference handout for syntax. While it doesn't cover all of Java syntax, this handout has the most common bits needed in CS106A.

Note: This is a brand new handout made in Jan 2019, just for you. Hopefully it is useful. The handout may be incomplete, but we will do our best to add more. Please let us know if you would like us to add any missed Java Syntax.

Variables

int, double, boolean, char

Variables store data. Have name, type, value, scope. The primative types are int, double, boolean and char.:

int x = 5; // creates an int double y = 4.3; // creates a double boolean z = false; // creates a boolean char ch = 'x'; // creates a char println(z); // variables can be accessed by name y = 7; // variables can be modified

Strings

String variables store sequence of characters:

String str = "chris"; // makes a string println(str + 5); // prints "chris5"

Arithmetic Operators

+, -, /, * Operators

Standard math operators. Example:

int x = 4; int ex1 = x + 5; // ex1 is 9 int ex2 = 10 - x; // ex2 is 6 int ex3 = x * 4; // ex3 is 16 int ex4 = 4 / 2; // ex4 is 2

% Operator

The "Mod" or "Remainder" operator. Returns the remaining value when the left-hand-side is divided by the right-hand-side. Example:

int x = 17 % 4; // x = 1 since 17/4 is 4 with remainder 1

+=, -=, *=, /= Operators

Adds, subtracts, multiplies or divides a variable by a given right hand side.

int x = 5; x += 2; // x = 7. Same as x = x + 2 x -= 1; // x = 6. Same as x = x - 1 x *= 2; // x = 12. Same as x = x * 2 x /= 3; // x = 4. Same as x = x / 3

++, -- Operators

Increments a variable to be one larger (++) or smaller (--). Example:

int x = 5; x++; // x = 6. Same as x += 1 x--; // x = 5. Same as x -= 1

Boolean Operators

==, != Operators

Tests equlity (==) or inequality (!=). Equality test returns true if the left-hand-side is the same as the right-hand-side.

int x = 5; println(x == 5); // true println(x != 5); // false

<, <=, >, >= Operators

Standard comparison operators. Compares a left hand side to a left hand side.

int x = 5; println(x < 5); // false. "x is less than 5" println(x <= 5); // true. "x is less or equal to 5" println(x > 5); // false. "x is greater than 5" println(x >= 5); // true. "x is greater than or equal to 5"

Logical Operators

&& Operator

Calculates logical and. Returns true if both the left hand side and the right hand side expressions are true

int x = 5; boolean digit = x < 10 && x >= 0; // digit is true

|| Operator

Calculates logical or. Returns true if either the left hand side or the right hand side expressions is true

int x = 5; boolean notDigit = x >= 10 || x < 0 // notDigit is false

! Operator

Calculates logical not. Returns true if and only if the expression is not true.

boolean rainy = true; boolean sunny = !rainy; // sunny is false

Control Flow

for Loop

Loops. Declaration has three parts (init; cond; update). First runs "init". Repeats while "cond" holds. Runs "update" after each iteration:

// prints the numbers 5,4,3,2,1,0 for(int i = 5; i >= 0; i--) { println(i); }

while Loop

Loops. If the condition holds, executes the body. Then jumps back to the condition:

int x = 5; // prints the numbers 5,4,3,2,1,0 while(x >= 0) { println(x); x--; }

if Statement

Executes a code block if a condition is true. If the condition fails, the control flow falls to an else statement (or else if) if one exists.

int x = 1; // prints "else-if condition" if(x > 2) { println("if condition"); } else if(x < 2) { println("else-if condition"); } else { println("else condition"); }

break

Exits a loop. As soon as a program hits a break statement, it exits the inner most loop that is executing and skips to the line after the loop.

int x = 5; // prints the numbers 5,4,3,2,1,0 while(true) { println(x); x--; if(x < 0) { break; } }

Graphical Objects

This handout doesn't include all graphical objects. For a full list please see the Stanford library docs.

GRect

A rectangle variable. Can change location, width, height, color etc:

GRect rect = new GRect(200, 200); // constructs a 200x200 rectangle rect.setFilled(true); // the rect is now filled rect.setColor(Color.BLUE); // the rect is now blue add(rect, 20, 30); // adds the rect to the screen at location (20,30) println(rect.getX()); // returns the x location of the rect println(rect.getY()); // returns the y location of the rect rect.move(2, 3); // move the rect 2 pixels to the right, and 3 pixels down

GOval

An oval variable. Can change location, width, height, color etc. Is the oval inscribed within the given rectangle dimensions:

GOval oval = new GOval(200, 200); // constructs a 200x200 oval oval.setFilled(true); // the oval is now filled oval.setColor(Color.BLUE); // the oval is now blue add(oval, 20, 30); // adds the oval to the screen at location (20,30) println(oval.getX()); // returns the x location of the oval println(oval.getY()); // returns the y location of the oval oval.move(2, 3); // move the oval 2 pixels to the right, and 3 pixels down

GLabel

An text graphics object variable. Can change location, or text. Given location is the start of the text base-line:

GLabel label = new GLabel("example"); // constructs a label with text "example" label.setFont("Courier-24"); // now its big and uses courier font label.setColor(Color.BLUE); // can set color add(label, 20, 30); // adds the label to the screen at (20, 30) println(label.getWidth()); // gets the width of the label prinlnt(label.getAscent()); // gets the height of the label

GLine

An line graphics variable. Specified by two points

GLine line = new GLine(5, 5, 20, 20); // constructs line from (5, 5) -> (20, 20) line.setColor(Color.BLUE); // can set color add(line); line.setStartPoint(20, 30); // changes start point line.setEndPoint(0, 0); // changes the end point

Console Methods

This handout doesn't include all program methods. For a full list please see the Stanford library docs.

Console Output

Use println or print to output text to a console. Println moves the cursor to the next line after printing.

println("hello world"); // prints "hello world" on the screen print("hello "); // prints "hello " on the screen (no next line)

User Input

Prints a prompt and waits for a user to enter a value. Returns the user's value.

int x = readInt("enter an int: "); // gets an int from the user double y = readDouble("enter a double: "); // gets a double from the user String z = readLine("enter a line of text: "); // gets a String from the user

Graphics Methods

getWidth, getHeight

Returns the width or height of the screen in pixels.

int width = getWidth(); // the default screen is 800 pixels wide int height = getHeight(); // the default screen is 600 pixels high

add, remove, removeAll

You can put objects on the screen, and take them off.

GRect x = new GRect(100, 100); add(x, 0, 0); // add x to (0, 0) remove(x); // take x off the screen removeAll(); // take all objects off the screen

waitForClick

Pauses the program at this line until the user clicks anywhere on the screen.

waitForClick(); // pauses here until a user clicks anywhere

getElementAt

Returns the GObject at a given location, or null if there is no object. If there are multiple objects, getElementAt returns the top most one.

GObject obj = getElementAt(x, y); // gets the GObject at location (x, y)

Random Generators

A variable type that can produce random looking values.

RandomGenerator rgen = new RandomGenerator(); int x = rgen.nextInt(42); // returns integer between 0 and 41, inclusive int y = rgen.nextInt(42, 100); // returns integer between 42 and 100, inclusive double a = rgen.nextDouble(42); // returns double between 0 and 41, inclusive double b = rgen.nextDouble(42, 100); // returns double between 42 and 100, inclusive