Java variables

July 9, 2016

In this lesson of Java tutorial, we are going to talk about Java variables. Variables are used to store some values. Maybe you remember from your math lessons at school that you used some variables, e.g. x. You assigned some value to it, like:

and you did some operations on these variables. Variables in Java are pretty similar. You can assign a value to a variable in Java and then operate on this variable.

1. Variable declaration

Variables in Java can have many types. One of the types is int, which is an abbreviation from an integer. You can store integer numbers in this variable. To use a variable, you have to at first declare it. To declare a variable in Java, you have to at first write its type and then its value. Let’s have a look on below line of code:

Above line of code is a variable declaration. The first word indicates a type of variable. This variable has type int. Next word indicates a variable name. The name of this variable is “counter”. At the end of the line with a variable declaration, you have to put a semicolon.

So the general format of variable declaration is:

2. Assigning value to variable

After declaring a variable, you can assign a value to it. After doing that, this value will be stored in this variable. To assign a value to a variable, you have to use = sign, like in the line of code below.

In the above line of code, we assign value 1 to a variable counter.

So the general format of variable declaration in Java is:

3. Printing variable value to console

Now, I’m going to print the content of the variable counter to the console. To do this I will use the System.out.println() method. We will pass a variable of type int to this method.

So let’s go to Eclipse and in our project named JavaTutorial create a new class named VariableExample. If you don’t remember how to do that, you can find this information here. After creating this class let’s copy paste code below to your eclipse:

Let’s run this program. The output visible in console is like this:

As you can see the System.out.println() method prints the value stored in the variable named counter. So it doesn’t print just the name of the variable, but the value which is stored in this variable. We can do many things with variables, and they are useful when creating a program, as you will see later in this tutorial.

4. Declaration and assignment of variable in one line

We can also move declaration and assignment of a variable into one line. So we can do in Java something like this:

Which is equal to:

So now you can copy and paste below code to you Eclipse class VariableExample:

And as you can see this program also prints 1 to the console.

Click here to add a comment

Leave a comment: