Java Variables Tutorial

In this section, we will learn what variables are in Java and how to work with them.

What Is a Variable in Java? (Defining variable)

A variable is a name created by developers to represent part of a computer memory. You can think about it as a link to a section in memory.

Using this variable, you can store data in memory, retrieve that data, or even replace it with other data.

The reason that is called “variable” is that they allow you to store different values in them! Basically, their values are not constant and that’s why they are known as variable.

Usually in a program, you’ll create many variables and store different values in them.

If we think about it, programs for most cases need data to function correctly.

For example, a calculator takes numbers and runs operations on them (like division, addition, and multiplication etc.). Or consider a browser that needs the address of a website to load that website for us to see.

A video player is another example of a program that needs data (video) to display it to users.

Using variables, we store these data in the memory and access them whenever needed.

Java Variables Syntax

This is the structure of how we create a variable:

Data-type variable-name;

Identifiers in java

The name of a variable is known as identifier. For example, if you have a variable name “firstName” in your program, you can say I have an identifier named “firstName”. What this variable name stores or its data type doesn’t matter at this stage! All that is matter is that you have an identifier that is named “firstName”.

The reason that we call it an identifier is that it identifies part of the memory that is dedicated to store specific type of values.

Data types of variables in Java

`Data-type`: data in programs has different types and when we create a variable, it’s important to declare the type of that variable as well.

For example, if we have a value that is an integer like 100, and we want to store this value in a variable, we need to declare the type of that variable as `int` which stands for integer.

Also, after declaring the type of a variable, we can’t change that type anymore and from the declaration onward, only values of the specified type are allowed to be stored in the target variable.

Now the question is why in programs we need to declare the type of a variable?

Well, the first reason is the amount of memory space that will be allocated to a variable.

In Java, there are multiple data types like `int`, `double` (for storing floating values), `float` (another data-type for storing floating values) and other types.

Each of these types takes a different amount of memory. For example, a variable of type `int` has enough memory space to only store integer values range from -2,147,483,648 to 2,147,483,647.

If in a program we need to store a value larger or smaller than the range that a variable of type `int` can support, then we need to use another type like `long` and `short` just to name a few.

So the data type of a variable declares the amount of memory space that should be allocated to a variable.

The second reason that we use data-types is to help the compiler and developers to figure out what type of values may be stored in the variable.

Note: if we put a value of different data type to a variable, depending on the type of the value, your program will either crash and stop working properly or it will try to cast the value to the right type which again might end up malfunctioning.

Check the Java data type section for more information.

Declaring (creating) variables in Java

Creating a variable is known as variable declaration.

When we declare a variable, we’re basically set a data type and followed by that comes the name of the variable (AKA identifier) and at the end we put a semicolon `;` to tell the computer that the declaration is done.

Example: creating Java variable

int age; 
String name;

Here, the first variable is named `age` and its data type is `integer` so we can store values range from -2,147,483,648 to 2,147,483,647 into this variable.

The second variable is named `name` and its data type is `String`. A variable of type String is used to store string of characters like names, sentences etc.

At this moment, we have two identifiers in our program, named `age` and `name`.

So now if we want to store an integer value in the memory, we can use the `age` variable to store it, and if we want to store a string value in the memory, we can use the `name` variable.

Variable initialization

Storing a value in a variable for the first time is called initialization.

You can initialize a variable right when declaring it, in one statement or first declare a variable and then in another statement initialize that variable.

Now, in order to store a value in a variable, we use the assignment `=` operator. In math, this operator is known as equal sign, but in programming you should know that it is called assignment operator and is used to assign a value to a variable.

Note:the equal operator in Java is `==`.

Example: initializing variables in Java

int age; 
String name = “John”;
age = 40; 

Here, for the variable `age` we’ve first declared the variable in one statement and then in another statement we’ve assigned a value to this variable. So basically, the declaration and initialization happened in two independent statements.

Note: the initialization statement could happen in any part of your program. Basically, you don’t need to set this initialization right where the declaration occurred.

Now for the `name` variable, the declaration and initialization occurred both at one statement. Basically, here we’ve told the computer to create the variable `name` and store the value “John” for its initial value.

Note: We use double quotation `” “` to store string values into a variable of string type.

Java Variables naming conventions

There are some rules that need to be followed when we want to set a name for a variable:

  • The name that we use for a variable can contain letters, numbers and underscores (_). For example: jack, ellen2020, _black, sunnySeason etc.
  • A name for a variable can begin with either underscore or letter. For example: _sum, check_point etc.
  • The name of a variable cannot start with number.
  • We can’t use white space and special characters like [email protected]# %^&*()+ etc. in variable’s name.

For example, these names are illegal: ell en, %%jack, Tony&&, pre-process.

  • The Java language is case sensitive, which means a variable named `ellen` is different than a variable named `Ellen` or `ELLEN`.
  • We can’t create two variables with the same name in the same scope. But we can have two variables with the same name each live in different scope or one live in one method and the other live in global (outside all other functions).

  • Semicolon `;`: the process of creating a new variable is called `declaration statement` and any declaration statement ends with semicolon `;`.
  •  

Note: We only use data types once when we’re declaring a variable. From that moment afterward, assigning values to a variable does not need mentioning the type of the variable anymore.

Java Reserved Words

We can’t use Java language reserved keywords as the name of a variable.

Here’s the list of reserved keywords:

abstract do if private this
assert double implements protected throw
boolean else import public throws
break enum instanceof return transient
byte extends int short true
case false interface static try
catch final long strictfp void
char finally native super volatile
class float new switch while
const for null synchronized continue
default goto package    
Java Reserved Words

Variable Types in Java and Locations where we can declare a variable in Java:

Other than the data type of variable, depending on where and how we create a variable, it can be categorized in different types as well!

Here’s the list of variables:

Local variable:

We are not yet reached to functions and scopes yet, so this type of variable at this stage might be a little difficult to understand. But just to give you a glance of what they are: a local variable is a variable that is created in part of your program that is only accessible there! Basically this variable is local to a segment of your program and other sections can’t access such variable! In fact the other parts of your program don’t even know if such variable exists! That’s why this type of variable is called local. (You’ll learn more about this in later sections).

– Instance variable:

In Java we have a concept called class and another concept that is known as object. A class is a blueprint of a structure that we might need in our program. Basically Java is nothing but a bunch of tools and interfaces that are created by default and we can use them based on the needs of our program. But Java doesn’t have the entire tools in the world! Sometimes we need to build our own tool and use it in a program. This is where classes come in. As mentioned before, class is just a blueprint. Basically we first design how our tool should look like by creating a class. But this is just the internal design and we need to build something out of it to become usable in a program. Now the process of creating a tool out of that class is called object construction! For now you don’t need to know how to create an object out of a class but one thing we need to know is that an object like any other data in a program needs to be stored in the memory.

As we learned before, it’s the variables that allow us to locate a memory location and store things in there. So if you create a variable and stored an object there, that variable will be known as `instance variable`! This is because the variable is now representing an instance of a class (a constructed example of a class).

Also inside the body of an object, there might be one or more variables for internal usage. These variables are also known as instance variables. Because each instance that is created from a class will get its own copy of those variables.

Again, if these concepts at this stage is confusing, don’t worry, we will get back to them in later sections (specially in Class and Object sections.)

– Static Variable:

When we have a class in a program, we can create an infinite number of objects from that class. Each of these objects will be created independently from the other and changing their content (AKA state) won’t affect the other.

Basically, if in the target class we’ve created a variable `firstName`, then each created object of that class will get its own variable with the name `firstName`. For example, if there are two objects created from this class, then there will be two variables with the name `firstName` each inside one of these objects.

But sometimes we want to have only one variable in a class no matter how many objects are created from it! Basically, we want a variable to be shared between the entire objects and if one changed the content of that variable, the other objects see this change and be able to modify the content themselves as well.

This is where we can create a variable as static.

Static variables are explained in greater details in later sections but in short, in order to create such variable, we put the `static` keyword behind the datatype of a variable when it is being declared.

For example:

static String firstName;

– Parameter:

Variables could also be used in methods (AKA functions) as parameters. Method is a block of code that is created to do a specific task. For example, you can create a method that takes two values and add them together and return the result. Now for this particular method, the two values we give to it needs to be stored somewhere in the memory right? This is where parameters comes in.

Basically parameters are nothing but local variables in a method block but because of the location we declare these variables in a function as well as their purposes (to store input values), they are known as parameters.

You’ll learn more about functions in later sections.

Local variables in Java:

As mentioned before, a variable that is declared inside a block or function is known as local variable.

Let’s see an example of a local variable in Java:

public class Simple {

    public static void main(String[] args){
        int age = 40;

    }
    public static void second(){
        System.out.println(age);
    }
}

Output: 
Error: Cannot fine the symbol: variable age.

As you can see we have a variable named `age` in the `main` method so it is the local variable of this method. But we’ve also tried to access the value of this variable in another method named `second`.

Now because a local variable as its name suggests is not accessible in another method, the compiler returned error instead of compiling the program. Basically, our program crashed even before running!

Note: A variable could also be declared outside of the body of any method. In such case it is called a global variable or instance variable or field. You’ll learn about this in the future lessons.

Multiple variable declarations in Java:

We can declare multiple variables of the same type in a single statement as well.

Here’s the syntax:

Data-type variable_one, variable_two, variable_n;

In this structure, each variable is separated via colon `,`.

For example:

double v_one, v_two, v_n;

In the example above, we’ve created 3 variables of type `double`.

Note: we could also assign values directly to each variable if we wanted.

For example:

int variable_one = 10, variable_two = 30, variable_n = 50;

Java Variable Assignment

As mentioned before, a variable is capable of taking values and store them in the memory. This process is called variable assignment.

For example:

int age; 
String firstName;
age = 50; 
firstName = “John”; 

In this example, we have two variables named “age” and “firstName”. After declaring these variables, now they are linked to a memory location and we can use them to store values in the memory. For example, in the first variable `age` we’re allowed to store integer values and here we did so with the value 50. For the `firstName` variable we also set the value “John”.

Now in the linked memory of these two variables, the two values 50 and “John” are stored.

One thing you should know is that variables can replace their values with a new one! That why they are called variables right?

For example:

int age; 
String firstName;
age = 50; 
firstName = “John”;
age = 10; 
firstName = “Jack”; 

Here the variable `age` at first assigned the value 50 to its memory but then in another statement we’ve assigned another value `10`. At this stage, the old value of this variable will be replaced with the new one!

Remember: the old value won’t be added to the new one! The new value will replace the old one instead! So the old one is gone after that.

Also for the `firstName` variable the same process happened. Basically at first this variable took the value “John” and then in another statement, its old value was replaced with a new one “Jack”.

So now if you call the `firstName` variable to get its value, you’ll see “Jack” instead of “John”.

Note: you first declare a variable and then assign a value to it. If you do this process on the opposite, you’ll get error and your program won’t work. This is because you need to have a memory space first and then store a value there!

Java Variable Reading

A variable has a dual purposes:

The first purpose is to write content into it as you saw in the assignment section.

But the second purpose is to retrieve the content of that variable whenever it is needed.

This is called reading a variable.

For example:

int age = 40;
int secondAge = age; 

In this example we have two variables `age` and `secondAge`. The age variable is initialized with the value 40.

Now look at the `secondAge` variable! The value we’ve assigned to it is `age`.

But to be specific here: We’ve assigned the value that was stored in the `age` variable. Basically, when computers run this statement, they see a variable named `age` and then they will check the memory space that is linked to this variable to see if there’s a value there or not.

If there was a value (which there is and it’s 40) computers will copy that value and store it in the memory location that is linked to the `secondAge` variable for this particular example.

Basically, anytime you put a variable in a place other than ON THE LEFT SIDE OF AN ASSIGNMENT `=` OPERATOR you’re trying to get the value of the target variable.

This means the only place that a variable acts as a receiver of value is when we put it on the left side of the assignment `=` operator. Otherwise in any other places if we call a variable, we are retrieving its value instead.

Var in Java: Java Local-Variable Type Inference

We mentioned that in order to create a variable we first define its datatype and then comes the name of the variable. This is how we create a variable in Java.

But there’s another way of creating a variable and that is by using the keyword `var` instead of the datatype of a variable.

For example:

var firstName = “John”;

Using the `var` keyword we’re basically telling the compiler that we don’t know what’s the data type of a variable is and it’s your job to figure that out! So behind the scene compilers will check the type of a value that is assigned to the variable and based on that value it will set the correct data type for the variable.

Note: it is important to initialize such variable with a value so that using the type of that value compilers can figure out the data type of the variable.

Basically if you create a variable with the keyword `var` and not initializing it, like this:

var name; 
name = "John";
System.out.println(name);

You’ll get an error because you’ve declared a variable with the keyword `var` and in this statement there’s no way for the compiler to find out the data type of the `name` variable. Hence it doesn’t know how much memory space it should allocate for this variable and so it will stop compiling the program altogether because of this confusion.

Java Variable Access Specifier:

A variable also has something called access specifier.

In access specifier section we will explain in details but for now remember that an access specifier comes before the data type of a variable and it declares the accessibility of that variable.

For example a variable that is declared `private` like:

private int variable_one = 10;

Means the variable is only accessible in the class where it’s being declared and no objects that are created from that class can access the variable.

Or if we set the access specifier of a variable as `public` that means the variable is accessible from objects created from that class.

public int variable = 10;

Note: access specifiers are only used for class level variables (AKA global variables) and we can’t use them for the local variables though.

Again in access specifier section we will explain this topic in greater details.

Java Final variables

Alright, so far we’ve learned that a variable by its nature can change its value in a program as many times as needed.

But you can create an identifier that is not variable! That means for such identifier, after the first time you set a value stored in it, from that moment onward you can’t change that value anymore!

Basically, the identifier becomes final (constant) and not variable!

You might be asking why does anyone want that?!

Well, consider the value Pi in math! The value is constant right? No matter where or how you use such value, it is always the same.

Now in programming you might have a value that you’re assured that will stay the same throughout the life cycle of the program. So in order to protect the value from any accidental change, you can create a final (constant) identifier and store such value there and you’re guaranteed that no one can change the value of that identifier!

Alright, in order to create a final identifier we use the keyword `final` behind the datatype of a variable

Here’s the syntax:

final data-type variable_name = value;

Note: it is super important to initialize a final variable right where it’s being declared. If you don’t initialize such identifier, you’ll get a compile time error and your program won’t run.

Example: creating final variables in Java

public class Main {
    public static void main(String[] args) {

        final String firstName = "John"; 
        System.out.println(firstName);
    }
}

Output: John

In this example, the identifier named `firstName` is created as final and so after initializing it, the value can’t be changed anymore!

Any attempt to do so will result in compile time error.

Example:

public class Main {
    public static void main(String[] args) {

        final String firstName = "John"; 
        firstName = "Jack";
        System.out.println(firstName);
    }
}

Output: 
Main.java:5: error: cannot assign a value to final variable firstName
        firstName = "Jack";
        ^
1 error

As you can see the compiler is complaining about the reassignment of a value to the `firstName` variable because it is declared as final and such action is not allowed for this type of identifier.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies