Black Lives Matter. Support the Equal Justice Initiative.

Variables and Types

Variables and Types

Variables are a fundamental part of any programming language, including Java. Variables are used to store pieces of data and give them a name. When we want to use these variables in some way, we can refer to them by their name.

Primitive Variable Types

Let's explore the primitive types of data that variables can hold.

  • String: a string of characters, also known as text
  • byte: a number between -128 and 127
  • short: a number between -32,768 and 32,767
  • int: a number between -2,147,483,648 and 2,147,483,647
  • long: a number between -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
  • float: a floating point number, a number with decimals
  • double: a floating point number but with more precision
  • char: a single character
  • boolean: a binary value, true or false

Now that we know the primitive types supported in Java, let's declare our variables.

Declaring

Declaring a variable is how you create them. Here's an example featuring all of the primitive data types:

	
    public class Main {
        public static void main(String[] args) {
            String a = "Sabe.io";
            System.out.println(a);

            byte b = 6;
            System.out.println(b);

            short c = 1337;
            System.out.println(c);

            int d = 12345;
            System.out.println(d);

            long e = 13371337;
            System.out.println(e);

            float f = 13.37f;
            System.out.println(f);

            double g = 13.37;
            System.out.println(g);

            char h = 'a';
            System.out.println(h);

            boolean i = true;
            System.out.println(i);
        }
    }
	
	
    Sabe.io
    6
    1337
    12345
    13371337
    13.37
    13.37
    a
    true
	

In general, to declare a variable, you must start off with their type, then an equal sign, then the value. This is the general syntax:

	
    type name = value;
	

Since Java is strongly typed, it requires you to give every variable their type.

Variable Naming Rules

There are rules in place for naming Java variables, and here they are:

  • The variable name can only contain alphanumeric characters, underscores, and dollar signs
  • The variable name must start with a letter, dollar sign, or underscore
  • The variable name cannot contain spaces

With that in mind, here are some examples of valid Java variable names:

	
    apples
    _apples
    _apples_
    $apples
	

And here are some examples of invalid Java variables names:

	
    1apples
    app les
    &apples
    %apples