Variables and types
A variable is a box to put a value in. Every box has a name and a type.
AboutMe.java in jGRASP.
Boxes
A variable is a labelled box. Each box has a type, so Java knows what fits.
score and Score are two different boxes.
The five types
| Type | Holds | Example |
|---|---|---|
String | Words | String name = "Adi"; |
int | Whole numbers, positive or negative | int age = 16; |
double | Numbers with decimals | double cost = 0.37; |
boolean | true or false, nothing else | boolean isRaining = false; |
char | Exactly one character | char initial = 'B'; |
Done some Python?
Python infers the type, so age = 12 is enough. Java requires explicit types: int age = 12;. In return it catches a whole class of mistake before the program runs.
Two that have no Python equivalent: char holds exactly one letter and uses single quotes, and every statement ends in a semicolon.
String uses double quotes "like this". char uses single quotes 'B'. Swapping them is a compile error.
The format
Names use a-z, A-Z, 0-9 and _. No spaces, and they cannot start with a number. Every statement ends with a semicolon.
Problems
1. Name the type
Pick the type to store each answer in.
Hint
Words, a whole number, a decimal, one letter, or a yes/no?
2. About me
AboutMe.javaFill in the five variables with answers, then run it.
Example outputName: Sam
Age: 12
Favourite number: 7.5
First initial: S
Pineapple on pizza: true
Hint 1
Only change what is on the right of each =. Leave the types alone.
Hint 2
If it will not compile, check the quotes. Words need ", single letters need '.
3. Break the rules
AboutMe.javaTry each of these, one at a time, and read the resulting error:
- Put a decimal into an
int. - Put two letters into a
char. - Name a variable
2cool.
Which of the three messages is easiest to understand? Which one would be hard to guess from the error alone?