Variable is a container or memory to store data values. A variable is assigned with a data type. There are different types of variables. Here is a few of them will discuss more in future.

  • String
  • int
  • char
  • boolean 


Syntax

type variable = value;


You can use (=) equalto sign for assigning value to the variable for example: 

int age = 25;


We can use a variable everywhere in a class. let me create an example to understand variable and store some data values


JavaApplication.java

public class JavaApplication {

    
    /*
     data and my_data is variables but outside of method
    is call global variable we access with anywhere
    */
    int data = 50;
    static int my_data = 100;

    public static void main(String[] args) {

        /*
        num is variable but inside method 
        so only we can access within this method
        */
        int num = 90;//local variable  
        
        
        // you can print the output and can do anything
    }

}


Some point you need to remember about above example:

  • data and my_data is variables but outside of method is call global variable
  • num is variable but inside method so only we can access within this method


Another example of variables

Example of adding two numbers


JavaApplication.java

public class JavaApplication {


    public static void main(String[] args) {

      int num1 = 10;
      int num2 = 20;
      
      System.out.println(num1 + num2);
    }

}



Output:

30


In some upcoming chapter will also understand more about the variables and data types but for now, now you have a clear how to create a variable in the store data value inside a variable so if this example will help you please give Thumbs Up and thanks for coming here.