Java Programming Cheatsheet
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.
Integers.
Booleans.
Comparison operators.
Math library.
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.
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; } }
10
11
12
Constructors.
13
Instance variables.
Instance methods.
Classes.
14
15