Please enable JavaScript to use CodeHS

Java Tutorial

Variables in Java

Variables are how programs remember things. In Java, every variable gets a type before it gets a value. Learn to declare, initialize, and name variables the way Java programmers do.

java ~15 min Beginner friendly
The Big Idea

What is a variable?

In programming, we use variables to store information. By storing values in variables, we can reference and change that information anywhere in a program. Say we create a game where players have a certain number of lives. We could use a variable to store the number of lives.

In Java, creating a variable starts with declaring it, and declaring has two key parts: picking the type of data the variable will hold, and picking its name. The number of lives is a whole number, so we declare the variable with the type int:

MyProgram.java
int numLives;

Right now, numLives is an empty storage container that can only hold whole numbers. Next we initialize it, which means giving it its first value:

MyProgram.java
int numLives = 3;

Now say the player loses a life and has 2 left. We change what a variable holds by assigning a different value to it:

MyProgram.java
numLives = 2;

Notice that we do not write int again. The variable already exists, so we are just changing its value, not creating a new one.

Semicolons matter: every Java statement ends with a semicolon ( ; ). Forget one, and the program will not compile. Think of it like the period at the end of a sentence.

If you have written Python before, this type-first style is the biggest difference. Python figures out the type on its own, but Java makes you say it up front:

Python
num_lives = 3

No type, no semicolon, snake_case name.

Java
int numLives = 3;

Type first, semicolon last, camelCase name.

See It Run

Try it: player lives

Here is that idea as a complete Java program. Java code lives inside a class and a main method, which is where the program starts running. Press Run and watch what prints each time numLives changes:

numLives.java
public class numLives
{
    public static void main(String[] args)
    {
        int numLives = 3;
        System.out.println("You have " + numLives + " lives left.");

        numLives = 2;
        System.out.println("You have " + numLives + " lives left.");
    }
}
Console
You have 3 lives left.
You have 2 lives left.

Look closely: the + signs glue text and variables together into one printed message. The same println line prints something different the second time, because numLives holds a different value at that moment.


Data Types

Types of variables

So far we have only stored whole numbers. But variables can hold other kinds of information too, and the type you declare tells Java exactly what kind. Here are the ones you will use constantly:

primitive int

Integer

Whole numbers, such as -5, 0, or 15.

int numLives = 3;
primitive double

Double

Numbers with a decimal, such as 43.67 or -0.11.

double cost = 40.25;
primitive boolean

Boolean

Either true or false. No quotes!

boolean isJedi = true;
primitive char

Character

One single character, in single quotes.

char grade = 'A';
object String

String

Text. Strings always get double quotes.

String name = "Baby Yoda";

Why is String capitalized? String is an object data type, while int, double, boolean, and char are primitive data types. Object types start with an uppercase letter, and primitive types are all lowercase.

Take a look at the different variable types in action, then press Run. Can you identify the type of each variable before the output appears?

MyProgram.java
public class MyProgram
{
    public static void main(String[] args)
    {
        String name = "Baby Yoda";
        System.out.println("The child's name is " + name);

        double age = 140.6778;
        System.out.println("The child is " + age + " years old.");

        boolean isJedi = true;
        System.out.println("Is the child a Jedi?: " + isJedi);
    }
}
Console
The child's name is Baby Yoda
The child is 140.6778 years old.
Is the child a Jedi?: true

Think about it: the boolean value true has no quotes around it. If you wrote "true" with quotes, what type would it be? (Answer: a String! The quotes turn it into text.) And what happens if you change the value of age to 140? Its type would need to change to int.


Conventions

Naming variables

When naming variables in Java, follow these rules:

  • no spaces
  • must start with a letter, $, or _
  • variable names are case sensitive, so numLives and NumLives are two different variables
  • written in lower camel case: the first word starts with a lowercase letter, and every word after that starts with a capital letter, like numLives or highScoreToday

camelCase is the opposite of Python style, where the same name would be num_lives with underscores. In Java, the capital letters are the humps that separate the words.

One more tip that is not strictly a rule: name your variable so it describes what it is holding. playerSpeed beats ps every time, because it makes your program easier to read and understand.



  • ✓ No spaces
  • ✓ Starts with a letter, $, or _
  • ✓ Only letters, numbers, $ and _
  • ✓ Not a reserved Java word (like int or class)
  • ✓ camelCase style: starts lowercase, no underscores

Interactive

Build a declaration

Time to think like the Java compiler. Pick a type, then choose a name and a value. The builder assembles the declaration live and checks it the same way Java would. Try to break it! Give an int a decimal, or a boolean the word maybe, and read the compiler error you get back.

Declaration builder

1. Pick a type   2. Name it   3. Give it a value

MyProgram.java - line 5

        

Nice detail: when you pick String, the builder adds the double quotes for you. In real code, forgetting the quotes around text is one of the most common beginner errors.


Your Turn

Practice problem

The best way to learn variables is to use them. Try this challenge in any Java editor - or jump into the CodeHS Playground to code right in your browser.

1

Favorite Television Shows!

Declare and initialize a couple of variables, then print their values to the console. Create a variable that stores the name of your favorite television show, and another variable that stores which season of that show is your favorite. Then print that information, including an explanation for why you chose it. Your program might print something like this:

Sample output
My favorite television show is Game of Thrones.
The best season is season 3, because of the incredible plot twists.

Here is your starting point:

MyProgram.java
public class MyProgram
{
    public static void main(String[] args)
    {
        // Initialize your variables here!

        // Then print your responses to the console using
        // System.out.println()
    }
}
MyProgram.java
public class MyProgram
{
    public static void main(String[] args)
    {
        String favoriteShow = "Game of Thrones";
        int bestSeason = 3;
        String reason = "the incredible plot twists";

        System.out.println("My favorite television show is " + favoriteShow + ".");
        System.out.println("The best season is season " + bestSeason + ", because of " + reason + ".");
    }
}
Console
My favorite television show is Game of Thrones.
The best season is season 3, because of the incredible plot twists.

Notice the types: the show name is text, so it is a String. The season is a whole number, so it is an int. Choosing the right type is half the job of declaring a variable.


Code

A Java variables example

Java is strongly typed, so you must declare the type of each variable. This program declares and prints a few values.


Check Yourself

Quick quiz

1. Which line correctly declares a variable that stores the price 9.75?

2. Which of these follows Java's naming conventions?

3. What does this program print?

int score = 10;
score = 25;
System.out.println(score);

Keep learning Java

You can store data with the right type. Next, learn more ways to print it, or make Java do the math for you. Or go deeper with a full Java course on CodeHS.