You are on page 1of 15

Java Programming Cheatsheet

This appendix summarizes the most commonly used Java language features in the textbook. Here are the APIs of the most common libraries.

Hello, World.

Editing, compiling, and executing.

Built-in data types.

Declaration and assignment statements.

Integers.

Floating point numbers.

Booleans.

Comparison operators.

Math library.

The full Math API.

Command-line arguments.

int a = Integer.parseInt(args[0]); // read int from commandline double b = Double.parseDouble(args[1]); // read double from command-line String c = args[2]; // read String from command-line

Type conversion.

If and if-else statements.

Nested if-else statement.


6

While and for loops.

Nested for loops. If-else nested inside a while loop.


// how many fair bets until you go broke? int bets = 0; while (stake > 0) {

bets++; if (Math.random() < 0.5) stake+ +; } else stake--;

Deeper nesting.
// print out Pythagorean triples (i, j, k) such that i^2 + j^2 = k^2 for (int i = 1; i <= N; i++) { for (int j = i; j <= N; j++) { for (int k = j; k <= N; k++) { if (i*i + j*j == k*k) { System.out.println("(" + i + ", " + j + ", " + k + ")"); } } } }

Break statement.

Do-while loop.

Switch statement.

Arrays.
// declare and compile-time initialize an array int[] a = { 3, 1, 4, 1, 5, 9 }; double[] b = { 3.0, 1.0, 4.0, 1.0, 5.0, 9.0 }; String[] suits = { "Clubs", "Hearts", "Diamonds", "Spades" }; // declare and run-time initialize an array of integers int N = 100; int[] c = new int[N]; for (int i = 0; i < N; i++) { c[i] = i; } double[] d = new double[N]; for (int i = 0; i < N; i++) { d[i] = i; } // compute the average of the elements in the array d[] double sum = 0.0; for (int i = 0; i < d.length; i++) { sum = sum + d[i]; } double average = sum / d.length;

Two-dimensional arrays.
// declare and compile-time initialize a 5-by-5 array of doubles double[][] p = { { .02, .92, .02, .02, .02 }, { .02, .02, .32, .32, .32 }, { .02, .02, .02, .92, .02 }, { .92, .02, .02, .02, .02 }, { .47, .02, .47, .02, .02 }, }; // declare and run-time initialize an M-by-N array of doubles double[][] b = new double[M][N];

for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { b[i][j] = 0.0; } }

The String data type.

The full String API.


String s = "Hello"; String t = "World"; String u = s + " " + t; // "Hello World" int length = s.length(); // 5 (length of string) char c = t.charAt(2); // 'r' (character indices start at 0) s.equals("Hello"); // compare string for equality

Our standard output library.

10

Our standard input library.

11

Our standard drawing library.

A few extra commands


StdDraw.mouseX() StdDraw.mouseY() StdDraw.mousePressed() StdDraw.text() StdDraw.picture() StdDraw.setCanvasSize()

Our standard audio library.

12

Redirection and piping.

Constructors.

13

Instance variables.

Instance methods.

Classes.

14

15