Variables

A Variable is a name holding a value.

Java programming language is statically typed which means the variable needs to be declared before assigning value to it and the value of the variable can be changed during the execution of the program based on the operations performed in the program

While declaring a variable a particular memory space is created for that variable based on the data type of the variable

Syntax to declare a variable in Java

A variable can be declared as below

datatype variablename = value;
example:int x=100;

Java has the option to declare a variable without value and the value can be assigned during the execution of the program

Example:int x;

Types of variables

The different types of variables in Java are as follows

Static(class)variables

Static variables are also known as class variables

- It is declared with the keyword “static”

- It holds the same value regardless of how many times the class is instantiated

- Memory allocation for the static variables happens only once during the class loading

Instance Variables (Non-Static)

- Instance variables are also known as Nonstatic variables

- The value of the instance variable is unique to each instance of the class

Local Variables:

- Local variables  are temporarily set to access variables inside a method

- It doesn't have any particular keyword it depends on where it is declared, local variables should be declared inside the opening and closing braces of a method

- Local variables are available only inside the method it is not available for the rest of the class

Sample program to understand variables:

class demo {
    int x = 50;//instance variable 
    static int y = 100;//static variable 
    void method() {
        int z = 90;//local variable 
    }
}//end of class  

 

The naming convention for variables

The set of rules to be considered while naming a variable is as follows

- Variable names are case-sensitive.

- White space is not permitted while naming a variable

- Variable name should not be a Keyword or reserved word

- While naming a variable it is highly recommended to use the full name instead of abbreviations this helps in easy understanding of the code

- It is highly recommended to use a letter as the starting letter of a variable. Usage of $ and _ is not recommended

- If the variable name is one word use lowercase, If it is two words the first word should be in lowercase and the starting letter of the second word should be in uppercase (Ex: power calculation)

 

 

Related Tutorials

Map