The Compiler is Your Friend
Doc Comments
This is the proper way to write multi-line comments to summarise a code file. You can later compile these into doc files:
/**
* This program does such and such.
* @author Ben Weston <b.weston60@gmail.com>
*/
Strongly Typed Languages
In strongly typed languages you must explicitly say the type of a variable. You must also match your types appropriately when completing manipulations.
Strongly typed languages give the following benefits:
- Prevent accidental (or malicious) memory access.
- Capture preventable runtime errors at compile time.
- Compiler complains, not your users.
Type Casting
Is when you assign a value of one primate data type to a variable of another type.
- Widening Casting (automatic)
byte
$\rightarrow$short
$\rightarrow$char
$\rightarrow$int
$\rightarrow$long
$\rightarrow$float
$\rightarrow$double
int myInt = 9; double myDouble = myInt; // Assigns 9.0
- Narrowing Casting (manually)
double
$\rightarrow$float
$\rightarrow$long
$\rightarrow$int
$\rightarrow$char
$\rightarrow$short
$\rightarrow$byte
double myDouble = 9.78; int myInt = (int) myDouble; System.out.println(myDouble); // Outputs 9.78 System.out.println(myInt); // Outputs 9
Constants
Constant are variable whose values don’t change in runtime:
final <type> <CONSTANT_NAME> = <value>;
Here final
is a keyword to denote that the following is a constant.
By convention identifiers denoting constants are in all caps.
Why Use Constants
Compiler optimisations will result in smaller, binary code with a smaller memory footprint.
It also helps with readability so that you know what the values in your code mean.
Finally it makes your code easier to maintain as changes propagate through the program.