Variables in Java

In this chapter, we will discuss the variables in Java and the types of variables in java. We will see how to declare and use it. In java, we use different variable types like static variable in java, instance variable in java, java global variable, a local variable in java.
Here is the table content of the article will we will cover this topic.
1. Declaration of variable
2. Initialization of variable
3. Declaration with Initialization of variable
4. Types of variables
5. Local variables
6. Instance variables
7. Static/class variables

8. Why local variables must be initialized in java?
9. Rules/Naming conventions for variables

10. Difference between local variable and global variable
11. Difference between static variable and instance variable

A variable is a container that holds the value that can be changed during the execution of the program. It is the name of a memory location. A variable is always assigned with a datatype.

  int a = 5;

Here “a” is a variable associated with value 5.
“int” is the data type of variable “a”. It means “a” can hold numeric values.

NOTE:  A variable must be declared before use.

Declaration of variable

data_type variable_Name

data_ type: Type of data that you want to store in this variable. 
variable_Name: Name of variable.

int a

Here the data type of variable is “int” and “a” is variable name.

Initialization of variable

After the declaration of a variable, you can initialize the variable. By mean of initialization is simply assign some value. To initialize a variable, follow this syntax:

variable_Name = value
a = 5;

As we already discuss “a” is a variable name and its data type is int. So, it can store integer values.

Declaration with Initialization of variable

You can declare the variable with assign the value to it.

data_type variable_Name = value;
int a = 5;

So we have two ways to declare and assign the value to variables.

Types of variables

1. Local variable in java

  • A Local variable in method
  • A local variable in static block
  • A local variable in instance block
  • A local variable in Constructor


2. Global variable in java

  • Instance variables
  • Static/class variables

1. local variable in java

A variable declared inside the body of a method or block or constructor is called a local variable. You can’t access these variable outsides of the method. These variables are created in memory when the function/block/constructor is called. After completing the execution of function/block/constructor these variables are destroyed by JVM. We can access these variables only within that block because the scope of these variables exists only within the block. The initialization of the local variables is mandatory. If you don’t initialize the variable compiler will throw a runtime exception. Let’s see how to define local variable.

  • A Local variable in method

We can create a local variable within the method and use it. But the scope of variables is enclosed within the method. Because these variables get created when the method gets invoked and destroyed after the execution of the method. You can’t leave a local variable without a declaration. It’s mandatory to initialize the local variable.

public class Student 
{ 
        public void studentRollNo() 
	{ 
	   // local variable rollNo, Its declared in studentRollNo ()
	   int rollNo = 5; 
	   System.out.println("Student Roll  no is : " + rollNo); 
	} 

	public static void main(String args[]) 
	{ 
		Student student = new Student(); 
		student.studentRollNo(); 
         } 
}

Output: Student Roll  no is : 5

In the above program, the variable rollNo is defined in the function studentRollNo(). If we use the variable rollNo outside from the StudentRollNo() function, the compiler will show an error.

public class Student 
{ 
	public void studentRollNo() 
	{ 
	   // local variable rollNo, Its declared in studentRollNo ()
	   int rollNo = 5; 
	   System.out.println("Student Roll  no is : " + rollNo); 
	} 

	public static void main(String args[]) 
	{ 
	    // using local variable rollNo outside it's scope 
       	    System.out.println("Student Roll no is : " + rollNo); 
        } 
}

Output: Exception in thread “main” java.lang.Error: Unresolved compilation problem: rollNo cannot be resolved to a variable at Student.main(Student.java:13)

  • A local variable in a static block

When we declare a variable within the static block. It is known as a local variable within a static block. But this variable is not accessible outside the block because it has limited scope. The scope is enclosed with the braces. If you are a beginner then you can read the topic of the static block later. Let’s see the example:

public class MainClass
{
    static
    {
        String name = "JavaGoal";
    }
    public static void main(String[] args)
    {
       System.out.println("Name :"+name);
    }
}

Output: Compilation error

In the above example, the variable name is declared within a static block so we can’t access it outside the block.

  • A local variable in instance block

Like static block, We can declare the variable in instance block and that is known as a local variable in instance block. We can perform actions on variables only within the instance block because we can’t access the variable outside the block.

public class MainClass
{
    {
        String name = "JavaGoal";
        name = name + "Website";
    }
    public static void main(String[] args)
    {
       System.out.println("Name :"+name);
    }
}

Output: Compilation error

  • A local variable in Constructor

We can declare a variable within the constructor and that will be accessible only within the constructor. Let’s take an example:

public class MainClass
{
    public static void main(String[] args)
    {
       System.out.println("Main method");
       new MainClass();
    }
    MainClass()
    {
        // Local variable
        int a = 5;
        System.out.println("value of a: "+a);
    }
}

Output: Main method
value of a: 5

2. Global variable in java

The global variable is always declared outside the method/block/constructor. It is always get declared within the body of the class. Unlike local variables, the scope of these variables is not limited. We can access the global variable within the class or outside the class. Global variables are categorized in two ways: Instance variable in java and Static/Class variable in java

Instance variable in java

A variable declared outside the method/block/constructor but inside the class is called an instance variable in java. We don’t use the static keyword with instance variable because if we use static with it, It makes it class variable and it will be common for all instances/Objects.

  • When an object of the class is created then the object also creates one copy of the instance variable and destroyed when the object is destroyed.
  • We can specify the access specifier for instance variables. By default, the default access specifier will be used.
  • Initialization of Instance Variable is not Mandatory. Its default value is depending on the data type of variable.
  • These variables can be accessed by creating objects.

An important point about instance variables: Every object has its own separate copy of the instance variable. If we created two objects of a class, then each object contains its own instance variables. Let’s understand with an example:

public class Student 
{ 
	// instance variable
	int rollNo;
	public void printStudentRollno()
	{
		System.out.println("Student Roll No: "+rollNo);
	}
	public static void main(String args[]) 
	{ 
           // Creating first object of Student class. 
           //This object creates separate copy of "rollNo".
	   Student firstStudent = new Student();
		
           // Assign the roll no to first Student 
	   firstStudent.rollNo = 5;
		
           // print the first student roll no
	   firstStudent.printStudentRollno();
		
           // Creating second object of Student class. 
           //This object also creates separate copy of "rollNo".
	   Student secondStudent = new Student();
		
           // Assign the roll no to second Student 
	   secondStudent.rollNo = 8;
		
           // print the second student roll no
	   secondStudent.printStudentRollno();
	} 
}

Output:
Student Roll No: 5
Student Roll No: 8

As you can see in the above program the variable “rollNo” is an instance variable. In case we have multiple objects as in the above program, each object will have its own copies of instance variables. We have changed the instance variable by different objects it doesn’t reflect another object value. It is clear from the above output that each object will have its own copy of the instance variable.

Memory representation: Objects are always created in heap memory

Memory representation of Instance variables in Java

Static variable in java / class variable in java

When we use a static keyword with an instance variable it makes it a static or class variable. The Static variable is known as class variables because they are associated with the class and common for all the objects of a class.

We will read this topic in separate post. If you want it in detail please read it.

  • Static variables are declared using the static keyword within a class outside any method/constructor/block.
  • When a class created then one copy of a static variable created in memory. Static variables would be common for all objects of class because a static variable is associated with the class.
  • Static variables are created at the start of program execution and destroyed automatically when execution ends.
  • Initialization of Static Variable is not Mandatory. Its default value is depending on the data type of variable.
  • If we access the static variable through an object the compiler will show the warning message. The compiler will replace the object name to the class name automatically.

NOTE: We don’t need to create an object of that class to access static variables.

Syntax to access static variables:

Class_Name.variable_name
public class Student 
{
   // static variable
   static int count = 0 ;
   public void printStudentRollno()
   {
      System.out.println("Now number of Student is: "+count);
   }
   public static void main(String args[])
   {
      // Access the static variable through class name and assign value
      Student.count = 1;
      // Creating first object
      Student firstStudent = new Student();
      firstStudent.printStudentRollno();

      // Again access the static variable through class name and assign value
      Student.count = 2;
      // Creating second object
      Student secondStudent = new Student();
      secondStudent.printStudentRollno();
   }
}

Output:
Now number of Student is: 1
Now number of Student is: 2

As you see in example “count” is a static variable. So that can access through class name. All the objects will share the same “count” variable.

Memory representation: Object are always created in heap memory

Memory representation of Static variables in Java

Both objects access the static variable from a static pool. We will discuss it in a static keyword.

Why local variables must be initialized in java?

As we know local variables have limited scope and lifetime. They can’t be accessible outside the method/block/constructor, so the compiler can predict the execution route of the local variables. Due to the limited scope and lifetime of a variable, the compiler identifies the declared variable and instructs a programmer to initialize it.
If the compiler allows a local variable without initialization, that leads to the possibility of a potential bug in the program.
Now you must think, the compiler should provide the default value as it provides in the case of global variables. But initializing every variable with a default value takes a hit on the performance.

Rules/Naming conventions for variables

  • The variable name should start with a lowercase letter such as name, marks, etc.
  • It should not start with the special characters like & (ampersand), $(dollar), _ (underscore).
  • If the name contains multiple words, then you can use two ways to write :
    • First, Start it with the lowercase letter followed by an uppercase letter such as firstName, lastName. It is known as camelCase convention.
    • Second, You can append an underscore(_) between the multiple words. Example: first_Name, last_Name, etc
  • You should avoid the using of one-character variables such as a, b,c

Difference between local variable and global variable

We have read the local and global variables. Let’s find what is the difference between the local variables and the global variables. Finds the local variable and instance variable in java.

Scope

The local variable has limited scope than the global variable. Because it is always declared within function/constructor/block. So, it can’t be accessible outside the function/constructor/block.

But global variable has large scope than the local variable because it is always declared outside the function/constructor/block. The global variables always accessible in the whole class.

Lifetime

The lifetime of local variables starts when a function/constructor/block gets invoked and ends with the completion of the execution of a particular function/constructor/block.

The lifetime of the global variable depends on the type of variable.
For static variable: The lifetime of static variables starts when the class gets load and ends when the class will be destroyed from memory.

For non-static/Instance variable: The instance variable gets loads when we create an object of the class and destroyed when the object gets destroyed.

Use of data

If we want to use the local variable in different methods, then we have to pass it as an argument/parameter. Because we can’t share the data of local variables in different methods with passing as arguments.

But a global variable is accessible everywhere in the class. We don’t need to pass it as arguments.

Default value

It is mandatory to initialize the local variable. If we don’t initialize a local variable the compiler throws a compilation error because JVM doesn’t provide default values to local variables.

JVM provides default values if we don’t initialize the variable. The default value depends on the data type of variable. Like 0 for int, false for boolean.

The same name of variables

A local variable can have the same names but in a different method/block/constructor. Because they have limited scope and don’t affect each other.

But the name of the global variable must but unique. We can’t use duplicate names of the global variables. The changes of global variable create affect in whole class wherever it is used.

Difference between static variable and instance variable

Let’s discuss the difference between the static and non static variable in java because non static variables are instance variables. This is known as the difference between class variable and instance variable.

Instance variables

1. When we declare a global variable without a static keyword that is known as an instance variable. We don’t use the static keyword with instance variables. Because instance variable binds with instance/object of the class.

2. When we create an instance/object of a class then JVM creates a copy of instance variables and associated with corresponding object. The instance variable gets destroyed when the instance/object is destroyed.

3. The instance variables are accessible through the object.

4. In non-static methods, Instance variables are accessible directly by name within the class. But in the static method, we have to use the object name.

5. Instance variables are not common for all objects because JVM creates a separate copy of each instance variable when we create an object.

Class variables(static variables)

1. When we declare a global variable with the static keyword that is known as class variable/ static variable. Class variables are also known as static variables because we use static keywords. These variables directly bind to class instead of instance/object.

2. But static variables load in memory during the class loading. When JVM loads the class in memory then a static variable gets created in Static pool memory. The static variables get destroyed when the program stops.

3. The static variables are accessible directly by class name.

4. In static or non-static methods, we can directly access the static variables by name of the variable within the same class.

5. But static variables are common for all objects of class because they binds with class not instance/object.

1. Quiz, Read the below code and do answer.

Can we declare a variable without its data type?

Click on anyone to know the answer.

2. Quiz, Read the below code and do answer.

Can we access the local variable outside the function/block/constructor?

Click on anyone to know the answer.

3. Quiz, Read the below code and do answer.

A variable declared within method/block/constructor is known as?

Click on anyone to know the answer.

4. Quiz, Read the below code and do answer.

public class Example
{
    public static void main(String[] args)
    {
        {
            int a = 5;
        }
        System.out.println("Value of a ="+ a);
    }
}

Click on anyone to know the answer.

5. Quiz, Read the below code and do answer.

Can we declare a local variable as a static variable?

Click on anyone to know the answer.

6. Quiz, Read the below code and do answer.

public class Example
{
    public static void main(String[] args)
    {
        int a;
        System.out.println("Value of a = "+a);
    }
}

Click on anyone to know the answer.

7. Quiz, Read the below code and do answer.

public class Student
{
    // instance variable
    int rollNo;
    public void printStudentRollno()
    {
        System.out.println("Student Roll No: "+rollNo);
    }
    public static void main(String args[])
    {
        Student firstStudent = new Student();
        firstStudent.rollNo = 5;
        firstStudent.printStudentRollno();

        Student secondStudent = new Student();
        secondStudent.rollNo = 8;
        secondStudent.printStudentRollno();
    }
}

Click on anyone to know the answer.

8. Quiz, Read the below code and do answer.

public class Example
{
    public static void main(String args[])
    {
        static int a = 5;
        System.out.println("Value of a = "+ a);
    }
}

Click on anyone to know the answer.

9. Quiz, Read the below code and do answer.

public class Student
{
    // static variable
    static int count = 0 ;
    public void printStudentRollno()
    {
        System.out.println("Now number of Student is: "+count);
    }
    public static void main(String args[])
    {
        Student.count = 1;
        Student firstStudent = new Student();
        firstStudent.printStudentRollno();
        Student.count = 2;
        Student secondStudent = new Student();
        secondStudent.printStudentRollno();
    }
}

Click on anyone to know the answer.

10. Quiz, Read the below code and do answer.

public class Example
{
    public static void main(String args[])
    {
        int _a = 5;
        System.out.println("Value of a = "+ _a);
    }
}

Click on anyone to know the answer.

3 thoughts on “Variables in Java”

Leave a Comment