Variables in Java

In this tutorial, we are going to learn about variables in java. In short, variables are used to temporarily store data in computer's memory.

Here is an example: Suppose we want to store someone's age in computer's memory. So, we declare variable like this:

int age = 23;


In above example, int is the data type of variable. So in this variable we can store only integer data. Again we will learn data types later. But focus on structure here. Then, age is variable name which will hold our data. In this case, our data is 23. So, age will store 23.

DataType Identifier = value;
Remember that variable name is identifier and we have certain rules to name it. Read here if you haven't already.

After then, we can print data of variable simply using variable name. Take a look at this example:

int age = 34; System.out.println(age);
As you guessed, this code will print 34 as output.

We can change data of any variable by overwriting it. Take a look at this example:

int age = 34; int age = 12; System.out.println(age);
Here, this code will print 12 as output.

Also we can declare variable without data and assign some data later. It is not mandatory to use Data Type once it is declared.

int age; age = 32; System.out.println(age);
It will still print 32 as output.

We can print text and our variable by using + (plus) sign in between. Here is example:

int age = 45; System.out.println("My age is: " + age);
It will print My age is: 45 as output.

Some other data types

int myNum = 5; float myFloatNum = 5.99f; char myLetter = 'D'; boolean myBool = true; String myText = "Hello";
We will learn about data types later. Here is an example only to show the use of variables.

Test it yourself

public class Variables { public static void main(String[] args) { int x = 5; System.out.println("Value of x is: " + x); x = 10; System.out.println("Now value of x is: " + x); } }
Value of x is: 5
Now value of x is: 10

Identifiers in Java Previous Next Comments in Java