Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Variables

Variables in java are storage locations where data values are kept.


Example :

The way a kid uses notebook to write numbers for addition, subtraction e.t.c. Similarly, java uses variables to write numbers for addition, subtraction and other purposes.

The below example shows how to add two numbers using variables :


public class Test{
  public static void main(String[] arg){
    int x = 5; // Here x is a variable.
    int y = 8; // Here y is also a variable.
    int z; // And z is the variable which holds added value.
    z = x + y;
    System.out.println("The added value is : "+z);
  }
}


The above example shows how to add two numbers using variables :


1.


int x = 5;

We are asking java to write the number '5' to a variable 'x'. 'int' is telling java, the value to be stored should be a number and not anything else.

java_variable_1


2.


int y = 8;

Similarly, we are asking java to write the number '8' to a variable 'y'.

java_variable_2

3.


int z;

Now, an empty variable 'z' is created to store the added value.

java_variable_3

4.


z = x + y;

Then, we are adding the values inside 'x' variable and 'y' variable using '+' operator and putting the added value in 'z' variable using the Assignment Operator '='.

java_variable_4

5.


System.out.println("The added value is : "+z);

Finally, we are using the above line to print the added value to the screen.

As we know that writing anything inside 'System.out.println()' will be printed on the screen.

So, there are two sections inside 'System.out.println()'.

First is within double quotes("") and the next is without any double quotes after a '+' sign.

You can mention anything inside the double quotes, i.e. it can be any meaningful information. And without double quotes will always be a variable. And the '+' operator is used to join both.


Note :The above '+' operator is not adding two numbers but joining a String with a number. It's because we are trying to add a String with a number.

And the output would be :



   The added value is : 13

Assignment Operator

A very important point to note is '=' used above is not exactly same as the equalto used in mathematics.

It simply means the value in the right hand side of '=' will be put to the variable in left hand side (e.g : x = 5). It's called assignment operator in java.


Note :In java there cannot be two variables with the same name.

So, far we have seen how java can store a number. But what if it has to store a name or a long string or a decimal value. We will be looking next.