Variable Java

Variable Java

The variable is the basic unit of storage in a Java program.

All variables have a scope, which defines their visibility, and a lifetime.

Declaring a Variable

All variables must be declare before they can be used. The basic form of a variable declaration is show here:

type identifier [ = value ]

  • Type is one of Java’s atomic types, or the name of a class or interface
  • The identifier is the name of the variable
  • initialize the variable by specifying an equal sign and a value
int a, b, c;         // declares three ints, a, b, and c. 
int d = 3, e, f = 5; // declares three more int. // d and f. 
byte z = 22;         // initializes z. 
double pi = 3.14159; // declares an approximation of pi. 
char x = 'x';        // the variable x has the value 'x'.

Dynamic Initialization

Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.

// Demonstrate dynamic initialization. 
class DynInit {   
    public static void main(String args[]) {     
        double a = 3.0, b = 4.0; 

       // c is dynamically initialized     
       double c = Math.sqrt(a * a + b * b); 
 
    System.out.println("Hypotenuse is " + c);  
 } 
}

Here, three local variables—a, b, and c—are declared.The first two, a and b, are initialized by constants. c is dynamically initialized using Math.squrt function.

The Scope and Lifetime of Variables

All of the variables use and declare at the start of the main( ) method. However, Java allows variables to be declare within any block.

A block is an opening curly brace and ended by a closing curly brace. A block defines a scope.

Each time you start a new block, you are creating a new scope. Because, A scope determines what objects are visible to other parts of your program. It also determines the lifetime of those objects

1) Local Variable

A variable declare inside the body of the method is call local variable. You can use this variable only within that method and the other methods in the class aren’t even aware that the variable exists.

And, A local variable cannot be define with “static” keyword.

2) Instance Variable

A variable declare inside the class but outside the body of the method, is call instance variable. It is not declare as static.

3) Static variable

A variable which is declare as static is call static variable. It cannot be local. You can create a single copy of static variable and share among all the instances of the class.

Types of variables in java

class A{  
   int mDog=50;         //instance variable  
   static int mCat=100; //static variable  
   void method(){  
   int mBird=90;        //local variable  
}//end of class  

More links AndrWep Tutorials