Java Cheat Sheet found at http://mindprod.com/jgloss/jcheat.html Control Structures // I F / E L S E if ( a > b ) { System.out.println ( a ); } else { System.out.println ( b ); } // I F / E L S E : is x in range low .. high? if ( low <= x && x <= high ) { System.out.println ( } "in range" ); else { System.out.println ( } "out of range" ); // S W I T C H / C A S E switch ( n ) { case 1: System.out.println ( "one" ); "two" ); break; case 2: System.out.println ( break; default: System.out.println ( "something else" ); }// end switch (n) Loops // F O R // Note lack of ; after i++ for ( int i=0 ; i<n ; i++ ) { System.out.println( i ); } POS 407 -- Computer Programming II Page 1 Course Syllabus // R E V E R S E for ( int i=n-1 F O R ; i>=0 ; i-- ) { System.out.println( i ); } // D U A L F O R // Note lack of ; after j++ for ( int i = 0 ,j = 0; i<n ; i++ ,j ++ ) { System.out.println( i ); } // However, this is illegal! for ( int i=0 , float r =1.0; i <n; i ++ ,r= r *2.0 ) { System.out.println( i ); } // E N U M E R A T I O N // Note ; after hasMoreElements(). for ( Enumeration e = props.propertyNames (); e.hasMoreElements(); ) { String key = (String) e.nextElement(); System.out.println ( key ); } // I T E R A T O R // Note ; after hasNext() for ( Iterator iter = list.iterator (); iter.hasNext(); ) { String key = (String) iter.next(); System.out.println( key ); } // I T E R A T O R : alternate Iterator someFiles = getFilesToProcess(); while ( someFiles.hasNext ()) { File ... } = (File) someFiles.next (); f // W H I L E while ( moreData () ) { readIt(); } POS 407 -- Computer Programming II Page 2 Course Syllabus // D O / W H I L E do { readIt(); if ( if ( done () ) break; bypassThisOne () ) processIt(); } while ( continue; moreData () ); The variables used in the while (boolean) clause can't be declared inside the while loop. The inside of the loop is considered a separate inner block. Try/Catch/Throw public class Test extends StandardTest { public static void main (String [] args) { try { dangerMethod(); } catch ( StrangeException { System.out.println ( } e ) "oops" + e.getMessage () ); } // end main void dangerMethod() throws StrangeException { if ( unexpected () ) throw } // end dangerMethod new StrangeException ( "oh oh" ) ; } // end class Test To help you remember the syntax of exception as a parameter. catch, think of it as like a method, that gets passed an Try/Catch/Finally try { somethingDangerous(); } catch ( IOException { System.out.println( e ) "oh oh" throw new BadDataException ) ; (); } finally POS 407 -- Computer Programming II Page 3 Course Syllabus { file.close(); // always executed } Literals A literal is an explicit number or string constant used in Java programs. Here is a list of all the variant forms I have found Java to support: int 1, -1, hex ints 0x0f28, unicode hex '\u003f', octal 027, Integer.MAX_VALUE (2,147,483,647), Integer.MIN_VALUE (-2,147,483,648) Beware! A lead 0 on an integer implies OCTAL. That was a major design blunder inherited from C, guaranteed to introduce puzzling bugs. Be especially careful when specifying months or days, where you naturally tend to provide a lead 0. byte / short There is no such thing as a byte or short literal. You would have to write it with a cast e.g. (byte)0xff or (short)-99. long 3L, -99l, 0xf011223344L (Beware! some compilers will just chop the high bits from literals without the trailing L even when assigning to a long.), Long.MAX_VALUE (9,223,372,036,854,775,807), Long.MIN_VALUE (-9,223,372,036,854,775,808). float 1.0345F, 1.04E-12f, .0345f, 1.04e-13f, Float.NaN. double 5.6E-120D, 123.4d, 0.1, Double.NaN, Math.PI. Note floating point literals without the explicit trailing f, F, d or D are considered double. In theory you don't need a lead 0, e.g. 0.1d may be written .1d, though the Solaris and Symantec compilers seem to require it. boolean true and false. String "ABC", enclosed in double quotes. You may not split strings over two lines. If you must, code like this: String s = + "def"; "abc" There is no speed penalty for the + concatenation. It is done at compile time. String literals can be used anywhere you might use a String reference. e.g. "abc".charAt(1) is legal. For problematic characters like embedded ", see escape sequences below. POS 407 -- Computer Programming II Page 4 Course Syllabus char 'A', enclosed in single quotes, or integer forms e.g. (char)45, (char)0x45, '\u003f'. For problematic characters like embedded ', see escape sequences below. Escape sequences inside char and string literals include: '\u003f' unicode hex, (must be exactly 4 digits) '\n' newline, ctrl-J (10, x0A) '\b' backspace, ctrl-H (8, 0x08) '\f' formfeed, ctrl-L (12, 0x0C) '\r' carriage return, ctrl-M (13, 0x0D) '\t' tab, ctrl-I (9, 0x09) '\\' backslash, '\'' single quote (optional inside " "), '\"' double quote (optional inside ' '), '\377' octal (must be exactly 3 digits. You can get away with fewer, but then you create an ambiguity if the character following the literal just happens to be in the range 0..7.) \007 bel, ctrl-G (7, 0x07) \010 backspace, ctrl-H (8, 0x08) \013 vt vertical tab, ctrl-K (11, 0x0B) \032 sub, eof, ctrl-Z (26, 0x1A) Unsupported There is no Pascalian '#nnn' style way of specifying decimal constants. Just use char c = 123; The following C forms are not supported: '\a' alert '\v' vertical tab '\?' question mark '\xf2' hex. Use the unicode \uffff form for printable characters. Primitives Primitive variables include boolean, char, byte, short, int, long, float and double. Strings, arrays and Objects are not considered primitives. Type boolean char Signed ? Bit s Byte s n/a 1 1 false true zero/one 2 '\u0000' [0] aka Character.MIN_VALUE '\uffff' [216-1] aka Character.MAX_VALUE Unicode chars are twice as big as C's. unsigne d Unicode 16 Lowest Highest Mnemonic byte signed 8 1 -128 [-2 ] aka Byte.MIN_VALUE +127 [2 -1]aka Byte.MAX_VALUE Bytes are signed, so half the usual 255 range. short signed 16 2 -32,768 [-215] aka Short.MIN_VALUE +32,767 [215-1] aka Short.MAX_VALUE 32K POS 407 -- Computer Programming II 7 Page 5 7 Course Syllabus int signed long signed float signed expone nt and mantiss a double signed expone nt and mantiss a 32 64 32 64 4 -2,147,483,648 [-231] aka Integer.MIN_VALUE +2,147,483,647 [231-1] aka Integer.MAX_VALUE 2 gig 8 9,223,372,036,854,775,80 8 [-263] aka Long.MIN_VALUE +9,223,372,036,854,775, 807 [263-1] aka Long.MAX_VALUE 9 exabytes, or 9 billion gig 4 ±1.40129846432481707e45 ±3.40282346638528860e+ 38 with 6 to 7 significant digits of accuracy. rough float 8 ±4.94065645841246544e324 ±1.79769313486231570e+ 308 with 14 to 15 significant digits of accuracy. high precision float Primitives vs Immutable Wrapper Objects Contrast that table of primitives, with this table of basic Java types: Mutable Primitives Immutable Objects boolean Boolean ordinary signed byte Byte unsigned byte Byte short Short char Character int Integer long Long float Float double Double char[] String Precedence Operator Precedence Precedence Operator Association Notes 1 (prefix) ++ -(unary) + ~! (cast) ++ prefix means preincrement, . ~ is bitwise not for ints. ! is logical not for booleans. Nearly always, you have to put the Right (prefix) expression after ! in parentheses. You might as well make a habit of always doing it. 1 (postfix) ++ -- Right (postfix) ++ postfix means postincrement 2 */% Left (infix) % is modulus, remainder. / is integer division for ints and floating point division for doubles. POS 407 -- Computer Programming II Page 6 Course Syllabus 3 +- Left (infix) a - b - c means (a - b) - c not a - ( b - c ), additive operations are performed left to right. + also means concatenation. There is no <<< operator because it would be identical to <<. You have to keep your wits about you when doing unsigned shifts to remember all right shifts must be done with >>>. 4 << >> >>> Left (infix) 5 < > <= >= instanceof Left (infix) 6 == != Left (infix) Pascal's <> not equal will not work. == and != work on booleans too, often saving a forest of if/elses. 7 & Left (infix) Bitwise AND mostly for for ints. XOR for ints. It is the difference operator. It is true if the boolean operands are different. e.g. false ^ false == false false ^ true == true true ^ false == true true ^ true == false 8 ^ Left (infix) It is useful in cryptography because of this magic property of encryption and decryption with a random scrambler number. long encrypted = message ^ scrambler ; long decryped = encrypted ^ scrambler ; If you XOR twice with the scrambler, you get right back where you started. For booleans it is clearer to use a != b instead of a ^ b and a == b instead of !( a ^ b) 9 | Left (infix) bitwise OR mostly for ints. 10 && Left (infix) short circuit logical AND for booleans. 11 || Left (infix) short circuit logical OR for booleans. 12 ?: Right ( ternary ) a = b ? c : d; is shorthand for if ( b ) a = c; else a = d; 13 = *= /= += -= <<= >>= >>>= &= ^= |= Right (infix) These make proofreading easier by eliminating typing a variable name twice. Keywords Java Keywords abstract do import boolean double instanceof return transient break else int short try byte extends interface static void case final long strictfp volatile POS 407 -- Computer Programming II public throws Page 7 Course Syllabus catch finally native super char float new switch class for package synchronized private this continue if default while implements protected throw Reserved keywords (not currently in use) const goto Reserved Literals null true false JavaDoc /** FormattedTextField.java * @author Roedy Green * @version 1.34 1998 January 18 * @deprecated Noreplacement * @deprecated Replaced by otherMethod(int) * @see otherMethod * @see #otherMethod * @see java.awt.Component#repaint * @see <a href="http://mindprod.com/gloss.html">Java & Internet Glossary</a> * @see "design patterns by Gamma et. al" * @param x <b>pixels</b> right of the origin. * @return number of oranges. * @exception java.beans.PropertyVetoException when mask is invalid * @since JDK1.1 */ POS 407 -- Computer Programming II Page 8 Course Syllabus