Java Variables

A variable is a named box in memory where your program keeps a value it wants to remember and reuse. In Java, every variable has a type that is fixed the moment you declare it, so the compiler always knows what kind of data lives inside.

Declaring a variable

To create a variable in Java you write its type, then its name, and usually an initial value. The type tells Java how much space to reserve and what operations are allowed; the name is how you refer to that value later in your code. This pairing of a type with a name is what makes Java a statically typed language.

Declaring and using a variable

public class Main {
  public static void main(String[] args) {
    int score = 42;
    System.out.println(score);
  }
}

You can declare a variable on one line and assign it a value later. The variable is not usable until it actually holds a value, so Java will refuse to compile code that reads a local variable before it has been set.

Declare first, assign later

public class Main {
  public static void main(String[] args) {
    String greeting;
    greeting = "Hello, Java";
    System.out.println(greeting);
  }
}

Common variable types

Beginners meet a handful of types again and again. Here are the ones you will use most often when you are starting out.

TypeStoresExample value
intWhole numbersint age = 30;
doubleDecimal numbersdouble price = 9.99;
charA single characterchar grade = 'A';
booleanA true or false flagboolean active = true;
StringA sequence of textString name = "Maya";

Naming rules and conventions

  • A name may contain letters, digits, the underscore, and the dollar sign, but it cannot start with a digit.
  • Names are case sensitive, so count and Count are two different variables.
  • You cannot use reserved words such as int, class, or public as a name.
  • By convention, variable names use lowerCamelCase, for example totalPrice or userName.
  • Choose descriptive names; daysLeft reads far better than the mysterious d.
Note: Since Java 10 you can write var instead of a type when the value makes the type obvious, as in var count = 5. Java infers int here. It only works for local variables that are initialised on the same line.

Changing a value

A normal variable can be reassigned as many times as you like, as long as the new value has the same type. Reassigning simply replaces the old contents of the box with the new value.

Reassigning a variable

public class Main {
  public static void main(String[] args) {
    int lives = 3;
    lives = lives - 1;
    System.out.println("Lives left: " + lives);
  }
}
Note: Java will not let you store the wrong kind of value in a variable. Writing int age = "thirty"; is a compile error because a piece of text cannot fit in an int.

Exercise: Java Variables

Which keyword prevents a variable's value from being changed after it is set?