Variables

Programming Languages · Java Basics · 10 min

Store numbers, text and true/false values in variables, and change them.

Whole numbers: int

A variable is a labelled box that holds a value. In Java you say what kind of value goes in the box first. int means a whole number.

int age = 30;
System.out.println(age); // prints 30

No quotes around age in println: you want the value inside the box, not the word.

  • Create an int variable called score set to 10.

  • Print score.

Decimals and true/false

double holds a number with a decimal point. boolean holds just true or false, perfect for yes/no facts.

double height = 1.75;
boolean isRaining = false;
  • Create a double called price set to 4.99, then print it.

  • Create a boolean called inStock set to true, then print it.

Letters and text: char and String

char holds a single character in single quotes. String holds text of any length in double quotes. Note the capital S in String.

char initial = 'Z';
String city = "Paris";
  • Create a char called grade set to 'A', then print it.

  • Create a String called name set to "Ada", then print it.

Changing a variable

You can put a new value in a variable any time. Leave out the type the second time: the box already exists.

You can even use the old value to make the new one:

int coins = 5;
coins = coins + 2; // now 7
  • Below the first print, take 1 away from lives using lives itself.

  • Print lives again.

Values that never change: final

Put final in front of a variable and Java won't let anyone change it later. Use it for fixed values. By habit, their names are in CAPITALS.

final int MAX_PLAYERS = 4;
// MAX_PLAYERS = 5; would not compile
  • Create a final double called PI set to 3.14.

  • Print PI * 2.

Put it together: level up

Let's build a tiny game character. Store the player's name and level, level them up, then show both.

  • Create a String called player set to "Ada" and an int called level set to 1.

  • Level up: add 1 to level using level itself.

  • Print player, then level, on separate lines.

More in Java Basics

Previous: Hello, World! · Next: Strings