In this section we will learn about following topics:
a) Keywords, reserved words
b) Operators
c) String methods
d) Input - Output
e) Converting values from one type to another
f) Math methods (no import required)
g) Control Flow Statements
Assume these declarations for the following method prototypes.
int i, j;
double d;
boolean b;
char c;String s, s1, t; // n, n1, n2 are numeric
| 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
| ||
| Arithmetic ops |
+ - * / % ++ -- | Operands are numeric, result is numeric. | |
| Comparison ops |
< <= == != >= > | Operands are numeric or char, result is boolean.
| |
| Logical ops | && (and) || (or) ! (not) |
Operands and result are boolean.
| |
| 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. | |
Input - Output | ||
| Dialog I/O - JOptionPane methods - 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.YES_OPTION, JOptionPane.NO_OPTION.,
JOptionPane.CANCEL_OPTION, or JOptionPane.CLOSED_OPTION |
| Text I/O - System.out and Scanner methods - import java.util.* | ||
| 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. |
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 = | |
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. |
Indenting is essential. Four spaces is most common.
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 Statementswitch 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 loopThe 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 controlsAll loop statements can be labeled, so thatbreak 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 labelPut label followed by colon at front of loop.
outer: for (. . .) {
. . .
continue outer;
|
for loopMany 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 loopThis is the least used of the loop statements, but sometimes a loop that executes one time before testing is used.
do {
statements
} while (testExpression);
|