How to declare a variable in Java

A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory location or temporary memory locations used to store values. In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here:

Generalized Syntax Of Variable Declaration : type identifier [ = value][, identifier [= value] …];

Example: int length= 25,breadth=10;

  • The “type” is one of Java datatype such as int, char, String etc. In the above example type is “int”
  • The “identifier” is the name of a variable. In above example variable is “length”
  • To declare more than one variable of the specified type, use a comma-separated list. In the above example, two variables “length” and “breadth” are declared separated by comma

Some of the Variables naming Conventions followed are:

  • No spaces, no special characters except underscore( _ ) and dollar ($)
  • Variable should start with an alphabet
  • It should not be a Keyword & it is case sensitive
  • Variables should be unique within its scope
  • It should follow camelCase & can contain Unicode characters

Below is the flow diagram explaining hierarchy of Data Type in Java

Data Types In Java

Here are several examples of variable declarations of various types

  • byte (number, 1 byte)

byte b = 22;

  • short (number, 2 bytes)

boolean b = false;

  • int (number, 4 bytes)

int myNumber = 5;

  • long (number, 8 bytes)

long num = 5;

  • float (float number, 4 bytes)

float f = (float) 4.5;

  • double (float number, 8 bytes)

double d = 4.5;

  • char (a character, 2 bytes)

char c = 'g';

  • boolean (true or false, 1 byte)

boolean b = false;

There are three kinds of variables in Java

  • Local Variables
  • Instance Variables
  • Class/Static Variables

Sample Example

class Test{  
int Marks=50;                    //instance variable   
static int Number=100;           //static variable 
void method(){ 
int Students=90;                 //local variable
}                                //end of class

Local variables 

  • Local variables are declared in methods, constructors, or blocks
  • These variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block
  • Access modifiers cannot be used for local variables
  • Local variables are visible only within the declared method, constructor or block
  • Local variables are implemented at stack level internally
  • There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use

Example: Here age is a local variable. This is defined inside pupAge() method and its scope is limited to this method only

public class Test{
    public void pupAge(){
    int age = 0; 
    age = age + 7;
    System.out.println("Puppy age is : " + age);
 public static void main(String args[]){
 Test test = new Test(); <

This would produce the following result:
Puppy age is: 7

Instance variables:

  •  Instance variables are declared in a class, but outside a method, constructor or any block
  • When space is allocated for an object in the heap a slot for each instance variable value is created
  • Instance variables are created when an object is created with the use of the keyword ‘new’ and destroyed when the object is destroyed
  • Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object’s state that must be present throughout the class
  • These variables can be declared at the class level before or after use. Access modifiers can be given for instance variables.
  • The instance variables are visible for all methods, constructors, and block in the class
  • Normally it is recommended to make these variables private (access level).However, visibility for subclasses can be given for these variables with the use of access modifiers
  • Instance variables have default values
    • For numbers the default value is 0, for Booleans it is false and for object references it is null
    • Values can be assigned during the declaration or within the constructor
  • Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods and different class ( when instance variables are given accessibility), the should be called using the fully qualified name.ObjectReference.VariableName.
     class Employee{ 
     // this instance variable is visible for any child class
     public String name; 
     // salary variable is visible in Employee class only
     private double salary; 
     // The name variable is assigned in the constructor
     public Employee (String empName){ 
     name = empName; 
     // The salary variable is assigned a value
     public void setSalary(double empSal){ 
     salary = empSal;
     // This method prints the employee details
     public void printEmp(){
     System.out.println("name : " + name ); 
     System.out.println("salary :" + salary); 
     public static void main(String args[]){ 
     Employee empOne = new Employee("Ransika"); 
     empOne.setSalary(1000); empOne.printEmp(); 

    This would produce the following result:
    name: Ransika
    salary: 1000.0

Class/static variables

  • Class variables are also known as static variables and are declared with the static keyword in a class, but outside a method, constructor or a block
  • There would only be one copy of each class variable per class, regardless of how many objects are created from it
  • Static variables are rarely used other than being declared as constants
  • Constants are variables that are declared as public/private, final and static
  • Constant variables never change from their initial value
  • Static variables are stored in static memory
  • It is rare to use static variables other than declared final and used as either public or private constants
  • Static variables are created when the program starts and destroyed when the program stops. Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class
  • Default values are same as instance variables. For numbers the default value is 0, for Booleans it is false and for object references it is null
  • Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks
  • Static variables can be accessed by calling with the class name
  • When declaring class variables as public static final, then variables names (constants) are all in upper case. If the static variables are not public and final the naming syntax is the same as instance and local variables
     class Employee{ 
     // salary variable is a private static variable 
     private static double salary; 
     // DEPARTMENT is a constant 
     public static final String DEPARTMENT = "Development"; 
     public static void main(String args[]){ 
     salary = 1000; 
     System.out.println(DEPARTMENT+"average salary:"+salary);

    This would produce the following result
    Development average salary:1000
    Note: If the variables are accessible from an outside class the constant should be accessed as Employee.DEPARTMENT

Characteristic Local variable Instance variable Class variable
Where declared In a method, constructor, or block. In a class, but outside a method. Typically private. In a class, but outside a method. Must be declared static. Typically also final.
Use They hold values used in computations in a method. Instance variables hold values that must be referenced by more than one method or that are essential parts of an object’s state that must exist from one method invocation to another. Class variables are mostly used for constants, variables that never change from their initial value.
Lifetime Created when method or constructor is entered.

Destroyed on exit.

Created when an instance of the class is created with new.Destroyed when there are no more references to enclosing object (made available for garbage collection). Created when the program starts.

Destroyed when the program stops.

Scope/Visibility They (including formal parameters) are visible only in the method, constructor, or block in which they are declared. Access modifiers (private, public, …) cannot be used with local variables.

A special case is that local variables declared in the initializer part of a forstatement have a scope of the forstatement.

Instance (field) variables can be seen by all methods in the class. Which other classes can see them is determined by their declared access:

private should be your default choice in declaring them. No other class can see private instance variables. This is regarded as the best choice. Define getter and setter methods if the value has to be gotten or set from outside so that data consistency can be enforced, and to preserve internal representation flexibility.

Same as an instance variable, but are often declared public to make constants available to users of the class.
Declaration Declare before use anywhere in a method or block. Declare anywhere at class level (before or after use). Declare anywhere at class level with static.
Initial value None. Must be assigned a value before the first use. Zero for numbers, false for booleans, or null for object references. May be assigned value at declaration or in the constructor. Same as an instance variable, and in addition can be assigned value in special static initializer block.
Access from outside Impossible. Local variable names are known only within the method. Instance variables should be declared private to promote information hiding, so should not be accessed from outside a class. However, in the few cases where there are accessed from outside the class, they must be qualified by an object (eg, myPoint.x). Class variables are qualified with the class name.  They can also be qualified with an object, but this is a deceptive style.
Name syntax Standard rules. Standard rules, but are often prefixed to clarify difference from local variables. static public final variables (constants) are all uppercase, otherwise normal naming conventions.


For more Examples on this topic visit Git repo of CodedBug