Intro to Java week 1
BASIC_TYPES.JAVA

Variables and types

A variable is a box to put a value in. Every box has a name and a type.

Download week 1 Unzip, then open AboutMe.java in jGRASP.

Boxes

A variable is a labelled box. Each box has a type, so Java knows what fits.

five boxes, five types
Stringname
intage
doublepi
booleanlikesPizza
charinitial
Case matters

score and Score are two different boxes.

The five types

TypeHoldsExample
StringWordsString name = "Adi";
intWhole numbers, positive or negativeint age = 16;
doubleNumbers with decimalsdouble cost = 0.37;
booleantrue or false, nothing elseboolean isRaining = false;
charExactly one characterchar 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.

Quotes matter

String uses double quotes "like this". char uses single quotes 'B'. Swapping them is a compile error.

The format

inttype
agename
=
16value
;ends it

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.java

Fill in the five variables with answers, then run it.

Example output
Name: 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.java

Try 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?