Variables and constants must be predefined to be used in a Java program.
By convention, we declare variables and constants at the beginning of the method (or function) in which they are used. Prefer no initialization with declarations.
By convention, declarations should be grouped based on data type.
Self documenting code suggests that variable names should make intuitive sense and should be used for only one purpose in any program.
For 239, if your variable names are CLEAR you don't need to document each one. You MUST use the @param for input arguments and each of these must be documented individually, one per line.
Java will not allow automatic narrowing conversions (loss of precision message) (except when????) Use type-casting to explicitly change the type of a result.
Examples: Variable.java
Note: All data is stored in binary on the computer. That limits the range of values for each of the primitive types. See book, Chapter 2, pg 74 for further discussion of data types.
Operators
Assignment | = | Place the value on the right into the variable on the left. |
Arithmetic | + - |
Addition Subtraction |
* / |
Multiplication Division |
|
Integer Arithmetic | / % |
Division: whole quotient Modulo or Remainder: remainder of division operation |
Increment/Decrement
careful! see example |
++ | Add 1 (increment by 1) |
-- | Subtract 1 (decrement by 1) | |
Relational | == != |
equals not equals |
> < |
greater than less than |
|
>= <= |
greater than or equal to less than or equal to |
|
Logical | && | AND |
|| | OR | |
! | NOT (not is unary) |
Memorize the truth tables
Operator precedence * / before + - and && before ||
Automatic data conversion - Done as it is needed, operation by operation. Wrapper class - autoboxing
Type casting - Done at whatever point you want to change
the type.
Casting is in the precedence rule list.
Examples: Operator.java
DeMorgan's Laws: ! (a && b) is equivalent to !a || !b
and ! (a || b) > is equivalent to !a && !b
For 239, you may use mixed operators as long as you know exactly what they can do (and a nasty side effect if you are not careful).
Two decision (or selection) statements in Java, if and switch.
if (condition)The else portion is optional.
statement (or statement block)
else
statement (or statement block)
Alternate format:
if (condition) statement;Use this form only for simple statements.
else statement;
Examples: Decisions.java
Be aware of code efficiency.Four items to look for in a loop structure:
Types of loops
Terms
Loop usage
Loop equivalency - A loop may be rewritten (sometimes awkwardly) as any other kind of loop.
See example: Loops.java