Easy Tutorial
For Competitive Exams

Java Programming Variables Theory

Variables

  • Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the memory.
  • During program execution we can modify that data.

The data stored in the memory of the computer can be of many types. Example: integer, Decimal numbers, String etc. A Variable has TYPE, NAME and VALUE.

Syntax for Declaring a Variable

In the below example int is the type, a is the name, 10 is the value.

Syntax : Variable Declaration

int a = 10;

Addition of Two Numbers

Step 1) Declare two variables, say a and b as integer, assign values.

Step 2) Print addition of two numbers.

Example:Addition of two numbers

public class Demo{
   public static void main (String[] args) {
       int a=10;
       int b=20;
       System.out.println(a+b);
     }
}
Try it Yourself

Exercise: Find the output of the following program.

10740.
Find the output of the code:
public class Demo{
   public static void main (String[] args){
      int a=10;
      System.out.println(a+a+a);
   }
}
20
30
40
10

Rules to declare a Variable

Rule Correct Incorrect
No space are allowed in the variable declarations. int var a=10;
Except underscore ( _ ) no special symbol are allowed in the middle of variable declaration. int var_1=10; int "var"_1=10; int var-1=10;
No keywords should access variable name. int int=5;
int main= 5;

Assigning Value to Variable

Example:Multiply two numbers

public class Demo{
   public static void main (String[] args) {
       int a=5,b=10,c;
       c=a*b;
      System.out.println(c);
     }
}
Try it Yourself

Exercise Q&A

14278.Find the output of the code:
public class Demo{
   public static void main (String[] args){
      int a=5,b=10,temp;
      temp=a;                                                         
      a=b;                                                          
      b=temp;
      System.out.println(a+" " +b);
   }
}
10 10
5 5
10 5
5 10
14281.Find the output of the code:
public class Demo{
   public static void main (String[] args){
      int a=5;
      int b=a*10;
      System.out.println(b);
   }
}
20
20
40
50
Share with Friends