Java: CMIS 102A Java Summary - v9

Keywords, reserved words, etc

Misc import, class, final, private, public, static, new
Control flow if, else, switch, case, default, break, while, do, for, return
Types int, double, boolean, char, String. (Ignore byte, short, long, float)
Constants null, true, false, integers (10, -15), and doubles (3.14).

Operators

Arithmetic + - * / % ++ --Operands are numeric, result is numeric.
Comparisons < <= == != >= >Operands are numeric or char, result is boolean. Don't use these ops for String comparisons.
Logical && (and) || (or) ! (not) Operands and result are boolean.

String methods

Assume: int i, j; double d; boolean b; char c; String s, s1, t; // n, n1, n2 are numeric

Length
i =  s.length() length of the string s.
Getting parts
s1 = s.substring(i, j) substring from index i to BEFORE index j of s.
s1 = s.substring(i) substring from index i to the end of s.
c = s.charAt(i) Single character at position i.
Searching -- Note: indexOf returns -1 if the string is not found
i = s.indexOf(t) index of the first occurrence of String t in s.
i = s.indexOf(t, i) index of String t at or after position i in s.
i = s.lastIndexOf(t) index of last occurrence of t in s.
i = s.lastIndexOf(t, i) index of last occurrence of t on or before i in s.
Creating a new string from the original
s1 = s.toLowerCase() New String with all chars lower case
s1 = s.toUpperCase() New String with all chars upper case
s1 = s.trim() New String with whitespace deleted from front and back
Comparison (Strings should use these instead of == and !=)
i = s.compareTo(t) compares to s. returns <0 if s<t, 0 if ==, >0 if s>t
i = s.compareToIgnoreCase(t) same as above, but upper and lower case are same
b = s.equals(t) true if the two strings have equal values
b = s.equalsIgnoreCase(t) same as above ignoring case

Misc

System.exit(0); Stop the program.

Dialog Input - Output (import javax.swing.*;)

JOptionPane.showMessageDialog(null, s); Display dialog with message s.
s = JOptionPane.showInputDialog(null, s); Return user string or null if cancelled.
i = JOptionPane.showConfirmDialog(null, s); Return JOptionPane.YES_OPTION, JOptionPane.NO_OPTION., JOptionPane.CANCEL_OPTION, or JOptionPane.CLOSED_OPTION

Console Output

System.out.println(x); Prints value of x (any type) on console followed by a newline.
System.out.print(x); Same as above, but without newline at end.

Console Scanner input (import java.util.*;)

Scanner in = new Scanner(System.in); Create a new Scanner object. Reuse this object for all subsequent input.
i = in.nextInt(); Read an int.
d = in.nextDouble(); Read a double.
s = in.next(); Read a "word".
s = in.nextLine(); Read the next input line.
b = in.hasNextInt(); True if an int is next. Reads ahead to check.
b = in.hasNextDouble(); True if a double is next. Reads ahead to check..
b = in.hasNext(); True if a "word" is next. Reads ahead to check..
b = in.hasNextLine(); True if there is another input line. Reads ahead to check.

Converting values from one type to another

i = Integer.parseInt(s); Converts s to integer or throws NumberFormatException.
d = Double.parseDouble(s); Converts s to double or throws NumberFormatException.
i = (int)d; Converts d to int, truncating fractional part. Can assign int to double without cast.
s = String.valueOf(x); Converts x to a string. More common is s = "" + x;
df = new java.text.DecimalFormat("0.00"); Creates a DecimalFormat object which can be used to format doubles.
s = df.format(d); Converts double to String according to the format.

Math methods (no import required)

n = Math.max(n1, n2); Returns maximum of n1 and n2. Works with numeric types.
n = Math.min(n1, n2); Returns minimum of n1 and n2. Works with numeric types.
d = Math.random(); Returns a random number from 0.0 up to but not including 1.0.

Control Flow Statements

if Statement

//----- if statement with a true clause
   if (expression) {
       statements // do these if expression is true
   }
   
//----- if statement with true and false clause
   if (expression) {
       statements // do these if expression is true
   } else {
       statements // do these if expression is false
   }
   
//----- if statements with many parallel tests
   if (expression1) {
       statements // do these if expression1 is true
   } else if (expression2) {
       statements // do these if expression2 is true
   } else if (expression3) {
       statements // do these if expression3 is true
   . . .
   } else {
       statements // do these no expression was true
   }
   
   

switch Statement

switch chooses one case depending on an integer value. This is equivalent to a series of cascading if statements, but switch is easier to read if all comparisons are against one value. The break statement exits from the switch statement. If there is no break at the end of a case, execution falls thru into the next case, which is almost always an error.
   switch (expr) {
      case c1:
            statements // do these if expr == c1
            break;
      case c2: 
            statements // do these if expr == c2
            break;
      case c2:
      case c3:
      case c4:         //  Cases can simply fall thru.
            statements // do these if expr ==  any of c's
            break;
      . . .
      default:
            statements // do these if expr != any above
   }

while loop

The while statement tests the expression. If the expression evaluates to true, it executes the body of the while. If it is false, execution continues with the statement after the while body. Each time after the body is executed, execution starts with the test again. This continues until the expression is false or some other statement (break or return) stops the loop.
   while (testExpression) {
       statements
   }

Other loop controls

All loop statements can be labeled, so that break and continue can be used from any nesting depth.
   break;       //exit innermost loop or switch
   break label; //exit from loop label
   continue;    //start next loop iteration
   continue label; //start next loop label
Put label followed by colon at front of loop.
outer: for (. . .) {
         . . .
               continue outer;
   

for loop

Many loop have an initialization before the loop, and some "increment" before the next loop. The for loop is the standard way of combining these parts.
   for (initialStmt; testExpr; incrementStmt) {
       statements
   }
This is the same as (except continue will increment):
   initialStmt;
   while (testExpr) {
       statements
       incrementStmt
   }

do-while loop

This is the least used of the loop statements, but sometimes a loop that executes one time before testing is used.
   do {
      statements
   } while (testExpression);

Defining Methods

public static double max(double a, double b) { // 1, 2, 3, 4
    double result;                             // 5
    if (a > b) {
        result = a;
    } else {
        result = b;
    }
    return result;                             // 6
}
  1. Visibility: public allows everyone to call it, private only in class..
  2. Class (static) methods used if don't references "fields".
  3. Return type: Either a primitive or class type, or void if no return value.
  1. Parameters: (arguments) are declared in a list with their types.
    Parameter names are completely independent of names outside method.
  2. Local variables created when method is called, destroyed when method returns.
    Local variable names are independent of names outside method.
  3. Return terminates the method and specifies value to be returned to caller.

Style standards

Comments: Identify purpose, author, date at top. Before "paragraphs". On variables.
Indent 4 spaces. Either K&R or Allmann style.

Copyleft 2007 Fred Swartz
-->