VARIABLES IN JAVA

There are two basic aspects to Programming: Data and Instructions. You need to understand variables and types to work with data, while to work with instructions, you need to understand control structures.

Table of Contents

[hide]
  • What is Java Variable
  • How to declare and Initialize variables in Java
  • Types of Java Variables
  • Java Variable Naming Conventions

What is a Java Variable

A Java variable is a peice of a memory location that stores data when the program is executed. We just have to worry about the name, it is compiler's responsibility to keep track of memory location.

All the variables must be declared before executing the program. Variable can store any kind of information ranging from temporary results, calculative information, names etc. A variable has a data type. We will learn about Data Types in Java in the next module.

It is called "Variable" because its values can be changed.When we talk about Variable just assume it is stored with some value in a reserved memory location. i.e movie name (Swades) is stored some where in the system's memory which you dont have to worry about.

How to Declare and Initialize variables in Java

Before a Java variable is usable, it must be assigned a memory location and initialized. You must specify the type to declare (create) a variable, give at least one space, then the name of the variable and end the line with a semicolon (;).

int total;

total is the variable name that has just been declared not initialized yet. It is assigned a location in memory. There is now some physical location in memory that can be queried by the runtime environment to retrieve the variable.

If you make an attempt to use this variable before initializing it will result in a NullPointerException.

One way to initialize a variable is to code an assignment statement after declaration of the variable. A Java variable can be initialized as the moment it is declared. It can have the general form as :type variableName = expression;

int total = 20;

Lets see a small example with the simple Java Program.

copyimage
//Java Program to illustrate the declaration and initializaton of variables.
public class Demo{
    public static void main(String args[]){  
      int num1 = 20;
      int num2 = 30;
      int total = num1 + num2;
         System.out.println("Total of two numbers is : " + total);
    }
}

OUTPUT: Total of two numbers is 50

In the given program there are three Java variables : num1, num2 and total. The first two variables have been initialized with respective values and the sum of these two variables is stored in the variable name total. Each of the variable hold some reserved memory location.

By now you must have learned how to declare a variable in Java and how to initialize a Java variable.

Types of Java Variables

There are three Types of Variables is Java :

  • 1. instance variable
  • 2. static variable
  • 3. local variable

Lets discuss each of them in detail with examples.

Instance Variables in Java

The Variable that are declared within the class but outside the method, constructor or any block is known as Instance Variables. They are called instance variable because their values are instance specific and are not shared among instances .

Instance Variables Properties

  • 1. Instance variables are created at the time of object creation (as they are a part of object), and is destroyed as soon as the object is destructed.
  • 2. Instance variables are allocated in heap memory area as they are a part of object and object resides in the heap.
  • 3. The value of instance variables are varied from object to object.
  • 4. For every object seperate copy of instance variable is created.
  • 5. Instance variables can be initialized with access modifiers like public, private, protected. By default it is initialized to Default Access modifier.
  • 6. Instance Variables cannot be declared as static, the native, the strictpf and synchronized modifier. However it can be marked as final and transient.
copyimage
//Java Program to illustrate the use of instance variable
public class InstanceCodeBator{
  int age=20;// instance variable

     public static void main(String args[]){  
         InstanceCodeBator result = new InstanceCodeBator();
         InstanceCodeBator result1 = new InstanceCodeBator();

         System.out.println(" results : " + result.age);
         System.out.println(" results : " + result1.age);

         result.age = 70;
         System.out.println(" result changed : " + result.age);
         System.out.println(" results : " + result1.age);
     }
}

OUTPUT

result : 20result : 20result changed : 70result : 20

For every object seperate copy of instance variable is created. This can be seen in the above program as when we changed the value of result and then print the value of all the objects, we could see that only value of object result changed. This indicates that they have their own copy of instance variable.

Static Variables in Java

Static variables are also known as class variable, since they are class-related and specific to all instances of class. As soon as the class is loaded into the memory, memory allocation to static variable happens as they are a part of class. These static variables are declared using static keyword within the class and outside method, constructor or any block just same as instance variable.

Static Variables Properties

  • 1. Static variables are created at the time of program execution when class file is loaded into the memory by JVM and destroyed at the time of class unloading i.e when program execution is done.
  • 2. Static variables are allocated in Method area.
  • 3. If the value of a variable is not varied from object to object, it is recommended to declare a variable as static variable.
  • 4. For every object a single copy of static variable is created at class level and shared by every object of the class.
  • 5. Static variables are Non Access Modifier. The Static modifier can be applied to a variable or Method or block or inner Class.
  • 6. A Static Method cannot access an instance variable.
copyimage
//Java Program to illustrate the use of static variable
public class InstanceCodeBator{
   public static int age=20; //static variable 

         public static void main(String args[]){  
         InstanceCodeBator result = new InstanceCodeBator();
         InstanceCodeBator result1 = new InstanceCodeBator();

         System.out.println(" results : " + result.age);
         System.out.println(" results : " + result1.age);

         result.age = 70;
         System.out.println(" result changed : " + result.age);
         System.out.println(" results : " + result1.age);
     }
}

OUTPUT

result : 20result : 20result changed : 70result : 70

You must have seen the diffrence in the output in case when we use instance variable and when we use static variable. As we know for every object a single copy of static variable is created at class level and shared by every object of the class. Hence changes made to the variable using one of the object would reflect when you access it through other objects.

Local Variables in Java

Local variables are temporary variables that are declared inside the method, constructor or any block are called local variables. Their scope is limited to the method in which they are declared, you cannot change their values and access them outside of the method.

Local Variables Properties

  • 1. Local variables are created while executing the method , block or constructor in which they are declared. Once the execution of method, block or constructor completes automatically the local variables are destroyed.
  • 2. Local variables are allocated in Stack area. Hence also known as stack variables.
  • 3. JVM do not provide default values for local variables, initialization is important.
  • 4. For every thread a separate copy of local variable is created, hence also known as thread safe.
  • 5. We cannot use access modifiers for declare local variable.
  • 6. We can not defined local variable with "static" keyword.
copyimage
//Java Program to illustrate the use of local variable
public class LocalCodeBator{ 

      public void findage(){  
      int age = 0; //local variable
      age = age + 5;
      System.out.println(" Current age is : " + age);
      }

      public static void main(String args[]){  
      LocalCodeBator obj = new LocalCodeBator();
      obj.findage(); //calling method from class object
    }
}

OUTPUT

Current age is : 5

In the above example we have created a local variable name "age". This variable is defined inside findage() method and thus its scope is limited to this method only. Method is accessed through the class object, in our case its obj. We will learn more about objects later in the tutorials.

Java Variable Naming Conventions

Best Java Variable Naming Conventions would be to select a name that will tell the reader of the program that what does that variable represents. For example if you are writing a program to calculate the age of a person then it would be good if you declare a variable name as age and not a2.

There are some rules which we have to follow before declaring a variable.

  • 1. All variables names should begin with letter of a alphabet , a ($) dollar sign, or an underscore. It is encouraged to always use a letter of a alphabet rather than using dollar sign and underscore.
  • 2. Variables can contain any combination of letters and digits(0-9) only after the first initial letter. Spaces and Special characters are not allowed like &(ampersand).
  • 3. Usage of one-character variable is not recommended. Ex e, f, g.
  • 4. If a variable name has multiple words then it is recommended to start with a lowercase and end with uppercase letter. Example mobileCover.
  • 5. You cannot use java keywords also known as reserved words for a variable name.