Variables and types

What a variable and a type are; int, double, String, boolean.

1. What is this?

A variable is a named slot holding a value. A type is the kind of value allowed: int (whole numbers), double (decimals), String (text), boolean (true/false). Java requires you to declare the type: int age = 28 means 'slot age holds whole numbers, starting at 28'.

2. Why do we use it?

Types catch whole categories of bugs before the program runs — you cannot accidentally store text in an age.

3. Syntax breakdown

  • int age = 28;

    Declares an int variable age with value 28.

  • String name = "Ava";

    String holds text. Note the capital S.

  • System.out.println(name + " is " + age);

    + joins (concatenates) strings and values into one line.

5. Common mistakes

  • int age = "28" — quotes make it text, which does not fit an int.
  • Using = when comparing (use == for comparison).
  • Forgetting that String needs double quotes, char needs single quotes.

Practice task

Add String city = "Berlin"; and print "I live in Berlin." using + joining.

Hint

Declare the variable, then println("I live in " + city + ".");

Try it below — tests run automatically when you press Run.

java

Output

Press Run to see output.

Mini quiz

3 questions. Answer, then check.

  1. 1. Which type holds whole numbers?

  2. 2. Which holds text?

  3. 3. What does + do between strings?

4. Example — edit and run

java

Output

Press Run to see output.

Expected output: Ava is 28