Variable types and Scope in Java Programming Language

Rumman Ansari   Software Engineer   2019-03-30   14958 Share
☰ Table of Contents

Table of Content:


Variable Types and Scope

The Java programming language defines the following kinds of variables:

  1. Instance Variables
  2. Static Variables
  3. Local Variables

variable-Types-in-java-programming

Instance Variable

A variable which is declared inside the class but outside the method is called instance variable. It is not declared as static.

members of the class:

the methods and variables defined within a class are called members of the class.

Why the name is instance: Variables defined within a class are called instance variables because each instance of the class (that is, each object of the class) contains its own copy of these variables. Thus, the data for one object is separate and unique from the data for another.


Important Points about Instance Variable:

  • Instance variables are used in a class, but outside a method, constructor or any block.
  •  A slot for each instance variable value is created, when space is allocated for an object in the heap.
  • Instance variables can be declared in the class level before or after use.
Example of local variable
class ClassName { 
data_type instance-variable1 ; 
data_type instance-variable2 

// ... 
data_type instance-variableN ;

data_type methodname1(parameter-list) {
// body of method
 }

 data_type methodname2(parameter-list) {
 // body of method
 }
 
 // ...
 data_type methodnameN(parameter-list) { 
 // body of method
 }
 }
  • Instance variables are created when an object is created with the use of the keyword 'new' keyword 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.
  • 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 (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName.

simple code to understand instance variable:

Class Man
{
String name;
int    age;
String gender;
}

Person P1,P2,P3;

 

Simple Example to understand Instance Variable:

Here, name is a instance variable.consName is local variable because it is inside construcor.

public class InstanceVariable{

    public String name;// this instance variable 

    public InstanceVariable(String consName)
     {
     name = consName;
     System.out.println("Your Name is: " + name);
     }

    public static void main(String args[])
    {
        InstanceVariable r = new InstanceVariable("atnyla");
    }
}
  
Output:
Your Name is: atnyla
Press any key to continue . . .

Static variable

A variable that is declared as static is called static variable. It cannot be local.

We will have detailed learning of these variables in next chapters.

  • Class variables also known as static variables 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 store values for the variables in a common memory location. Because of this common location, if one object changes the value of a static variable, all objects of the same class are affected.
variable-Types-in-java-programming
  • 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 the static memory. It is rare to use static variables other than declared final and used as either public or private constants.
Example of static variable
class ClassName { 
access_specifier static  data_type static_variable1; 
access_specifier static data_type static_variable2; 

// ... 
access_specifier static data_type  static_variableN;

data_type methodname1(parameter-list) {
// body of method
 }

 data_type methodname2(parameter-list) {
 // body of method
 }
 
 // ...
 data_type methodnameN(parameter-list) { 
 // body of method
 }
 }
  • 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 the class name ClassName.VariableName.
  • When declaring class variables as public static final, then variable 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.

simple code to understand static variable:

Class Man
{
String name; // instance variable
int    age;  // instance variable
String gender;  // instance variable

static String city = "newyork";  // static variable
};

Simple Example to understand local variable:

Here, age,name are a static variable. This is defined inside class and its can access able anywhere from program

// Java program to demonstrate Static variable in Java
public class StaticVariableExample {

   // age  variable is a static variable
   static int age;

   // name is a constant
   static final String name = "atnyla";

   public static void main(String args[]) {
      age = 21;
      System.out.println(name + "'s age age is:" + age);
   }
}
  
Output:
atnyla's age age is:21
Press any key to continue . . .

Local Variable

A variable which is declared inside the methods, constructors, or blocks is called local variable.

  • Local variables are declared in methods, constructors, or blocks.
  • Local 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.
Example of static variable
class ClassName { 
data_type instance_variable1; 
access_specifier  static  data_type  static_variable ;

ClassName(data_type local_variable)
 {
 //  // body of constructor
 }


data_type methodname1(data_type local_variable1) {
// body of method
 }

 data_type methodname2(data_type local_variable2, data_type local_variable2) {
 // body of method
 }
 
 // ...
 data_type methodnameN(parameter-list local_variable) { 
 // body of method
 }
 }
  • 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.

simple code to understand local variable:

int addition(int n1,int n2) //here n1 and n2 is local variable
  {
  int sum;
  sum = n1 + n2;
  return(sum);
  }
  

Simple Example to understand local variable:

Here, number is a local variable. This is defined inside addition() method and its scope is limited to only this method.

// Java program to demonstrate local variable in Java
public class LocalVariable {
   public void addition() {
      int number = 7 ;  // number is local variable
      number = number + 23;
      System.out.println("Recent number is : " + number);
   }

   public static void main(String args[]) {
      LocalVariable test = new LocalVariable();
      test.addition();
   }
}
  
Output:
Recent number is : 30
Press any key to continue . . .

We should initialize local variable before use:

Following example uses number without initializing it, so it would give an error at the time of compilation.

// Java program to demonstrate local variable should initialize in Java
public class LocalVariable {
   public void addition() {
      int number ;
      number = number + 23;
      System.out.println("Recent number is : " + number);
   }

   public static void main(String args[]) {
      LocalVariable test = new LocalVariable();
      test.addition();
   }
}
  
Output:
C:\LocalVariable.java:5: error: variable number might not have been initialized
      number = number + 23;
               ^
1 error

Tool completed with exit code 1