"Hello, world!" program (dynamic version) |
/* A dynamic Java program that prints "Hello, world!" */ class Hello { Hello(String name) { // constructor method System.out.println("Hello, " + name + "!"); // print the message } public static void main(String[] arg) { // execution begins here new Hello("world"); // create new Hello object } } |
||
---|---|---|---|
Unix and DOS commands |
cd dir              change directory to "dir" (within current directory) cd ..               move up to parent directory javac Hello.java    compile the program Hello.java java Hello          run the program Hello.class ls                  list contents of current directory (Unix only; use dir on DOS) rm *.class          remove all files with extension .class (Unix only; use del on DOS) [up arrow]          retype previous command control-c           interrupt a program |
||
Primitive variable types |
int         
32-bit integer (up to 2147483647; use long for larger integers) double       64-bit ("double-precision") floating point number (up to about 10308) boolean      true or false |
||
Arithmetic | +   -   *   /   (* and / take precedence over + and -; use parentheses when needed) | ||
Shortcuts | +=   -=   *=   /=    ++   -- | ||
Relations | ==   !=   <   <=   >   >= | ||
Logic | && (and)    || (or)    ! (not) | ||
java.lang.Math |
Math.PI         Math.E Math.cos(t)     Math.acos(x)    Math.log(x) (natural log) Math.sin(t)     Math.asin(x)    Math.exp(x) (ex) Math.tan(t)     Math.atan(x)    Math.sqrt(x)     Math.pow(x,y) (xy) Math.max(x,y)   Math.min(x,y)   Math.abs(x) (absolute value) Math.round(x)   Math.floor(x)   Math.ceil(x) (round normally, down, or up) Math.random() (pseudo-random double between 0 and 1) |
||
Converting data types (casting) |
myInt = (int) myDouble; // rounds myDouble toward zero roundedX = (int) Math.round(x); // rounds x to nearest integer randInt = (int) (Math.random() * n); // random integer from 0 to n-1 |
||
Control structures |
if (balance <= 0) { broke = true; } else { broke = false; } |
while (t < 10) { t += dt; doStuff(); } |
for (i=0; i<100; i++) { System.out.println( "I will not hack."); } |
Declaring a method |
double hypotenuse(double a, double b) { return Math.sqrt(a*a + b*b); } |
||
Arrays |
double[] x; // declare that x is an array of doubles x = new double[100]; // create the array (size could be a variable) x[0] = aValue; // first entry has index zero x[99] = x[98] + dx; // last entry is 99; "x[100]" gives an error |
||
Formatting numbers |
import java.text.*; // put this line at top of program DecimalFormat myFormat = new DecimalFormat("0.00"); myString = myFormat.format(myNumber); // or just print it |
||
Parsing command-line arguments |
double x0 = 0.0; // default value try {x0 = Double.parseDouble(arg[0]);} // or Integer.parseInt catch (ArrayIndexOutOfBoundsException e) {} // use default if no arg catch (NumberFormatException e) {} // or if invalid |