JAVA

Java Variables


What is Variables?

Variable is a name of memory location or identifier that is used to store and manipulate data within a program.

 

Syntax

data_type var_name = value;

 

Example

// Integeric Types

byte byteValue = 127;  // Here, byteValue is a variable of type byte
short shortValue = 32767;  // Here, shortValue is a variable of type short
int intValue = 2147483647;  // Here, intValue is a variable of type int
long longValue = 9223372036854775807L;  // Here, longValue is a variable of type byte. Note the 'L' suffix for long literals


// Floating Types

float floatValue = 3.14f;  // Here, floatValue is a variable of type float. Note the 'f' suffix for float literals
double doubleValue = 2.71828;  //  Here, doubleValue is a variable of type double.


// Character Type
char charValue = 'A';  // Here, charValue is a variable of type char


// Boolean Type
boolean booleanValue = true;  // Here, booleanValue is a variable of type boolean

 

 

Types of Variables

Java variables can be classified into three main categories based on their scope.

 

1. Local Variables

  • Defined within a method, constructor, or a block.
  • Limited to the scope in which they are declared.
  • Must be initialized before use.
      
     

Example

 

public class Local {
    public static void main(String[] args) {
        int x = 10; // Local variable
        System.out.println(x);
    }
}			

 

 

2. Instance Variables

  • Defined within a class but outside of all the methods.
  • Automatically initialized to default values.

 

Example

 

public class Instance {
    int y; // Instance variable
    void fun(){ 
    }
}

 

 

3. Static Variable

  • Belong to the class rather than to instances of the class.
  • Shared among all instances of the class.
  • Declared with the static keyword.
  • It is also called class variable.

 

Example

 

public class Static {
    static int z; // Static variable
}