Java Variables
Variables are containers that store information that can be manipulated and referenced later by the programmer within the code. Java variables have a data type associated with them which can tell us about the size and layout of the variable’s memory.
Syntax:
There are three types of variables in java:
- Local variable
- Instance variable
- Class/Static variable
A. Local Variables:
A variable that is declared inside the body of the method or constructor is called a local variable. It is called so because the extent of a local variable lies only within the method or constructor within which it is created and other methods in the class cannot access it.
Inside the method body, local variable is declared using the static keyword.
Example:
Output:
If it is accessed outside the method or constructor within which it is creaed, then it give an error.
Example:
Output:
B. Instance Variables:
An instance variable is declared inside the class but outside a method or a constructor. It is similar to a static variable except that it is declared without using the keyword static. These variables are accessible by all methods or constructors that are inside the class.
Example:
Output:
C. Class/Static Variables:
An static variable is declared inside the class but outside a method or a constructor. It is similar to a instance variable except that it is declared using the keyword static. These variables are accessible by all methods or constructors that are inside the class.
Example:
Output:
If variable is not declared static the it gives an error.
Example:
Output:
0 Comments