CORE JAVA

ProwessApps Learning Portal

Variables in Java


  • Variables are named locations in memory that are used to hold a value that may be modified by the program.

  • A variable may take different values at different times during execution.

Syntax for variable declaration :

       DataType Identifier = value (optional);

Example :

int a;
int x = 100;
float f = 2.3f;
etc...

Types of Variable in Java :

Local Variable

Instance Variables (Non-Static Fields)

Class Variables (Static Fields)

  1. Local Variable :
    Local variables are those variables whose scope is local to block.A variable which is declared inside the method is called local variable.


  2. Instance Variables (Non-Static Fields)

    A non-static variable which is declared inside the class but out side of the method is instance variable.

    Non-static fields are also known as instance variables because their values are unique to each instance of a class(object), mean to say that every object has its own separate copy of instance variables..


  3. Class Variables (Static Fields)

    A static variable which is declared inside the class is class variable.

    Static variable cannot be local.


Example :

Test.java Copy Code
public class Test{  
 int x = 50;//instance variable
 static int y = 100;//static variable

 void myMethod(){
  int z = 150;//local variable  
  } 
}     




advertisement