Variables in Java

Variables in Java with Examples

In this article, I am going to discuss the Variables in Java with Examples. Please read our previous article, where we discussed Operators in Java with examples. At the end of this article, you will understand what are variables and their type and how to create and use variables in Java Applications with examples.

What are the variables in Java?

The Variable is a piece of memory that is typically used to store information. All the variables must be declared before use in the Java code. During the program execution, the value stored in the variable can be changed.

Variables are just the name of the reserved memory location, and all the operations done on the variables will definitely effects that memory location.

How to declare a variable in Java?

The Syntax for declaring a variable in java: data_type variable_name; where, data_type is the type of data to be stored in this variable, and variable_name is the name given to the variable.

Example: int age; Here, int is the data type and age is the name of the variable where int data type allows the age variable to hold the integer value.

How to initialize a variable in Java?

The Syntax for initializing a variable: data_type variable_name = value; where, data_type is the type of data to be stored in this variable, and variable_name is the name given to the variable. value is the initial value stored in the variable.

Example: int age = 20; Here, int is the data type and age is the name of the variable where int data type allows age variable to hold the integer value 20.

Variables Scope and Lifetime in Java:

The scope of a variable is the part of the program over which the variable name can be referenced. You cannot refer to a variable before its declaration. Variable scope refers to the accessibility of a variable.

The lifetime of a variable refers to the time in which a variable occupies a place in memory. The scope and lifetime of a variable are determined by how and where the variable is defined.

Scope vs Lifetime in Java:

Scope refers to the range of code where you can access a variable. We can divide the scope into:

  1. Method body scope variable is accessible in method body only (local variables, parameters)
  2. Class definition scope variable is accessible in the class definition (instance variables)

Lifetime refers to the amount of time a variable (or object) exists. We can divide lifetime into categories too:

  1. Method body lifetime exists on method body lifetime entry, disappears on method body exit (local variables, parameters).
  2. Class definition lifetime exists as long as the object is around (instance variables).
Naming Conventions of Variables in Java:

Variable’s names are case-sensitive. The variable name money is not the same as Money or MONEY. Variables naming cannot contain white spaces, for example, int num ber = 100; is invalid because the variable name has space in it. A variable name can begin with special characters such as $ and _

As per the java coding standards, the variable name should begin with a lower case letter, for example, int number; For lengthy variables names that have more than one word do it like this: int smallNumber; int bigNumber; (start the second word with a capital letter).

Types of Variables in Java:

Basically, there are three types of variables in java :

  1. Local Variable
  2. Instance Variable
  3. Static Variable

Variables in Java with Examples

Local Variables in Java:

Local Variables are declared inside the method of the class. The scope of the local variable is limited to the method, which means you cannot change the value of the local variable outside the method and you cannot even access it outside the method. The initialization of the local variable is mandatory.

Scope of Local Variable: Within the block in which it is declared.

The lifetime of Local Variable: Until the control leaves the block in which it is declared.

Example to Understand Local Variables in Java:
package Demo;
public class LocalVariableExample
{
    public void EmployeeAge ()
    {
        // local variable age 
        int age = 30;
        age = age + 5;
        System.out.println ("Employee age is : " + age);
    }
    public static void main (String args[])
    {
        LocalVariableExample obj = new LocalVariableExample ();
        obj.EmployeeAge ();
    }
}

Output: Employee age is : 35

In the above code, age is the Local Variable to the method EmployeeAge(). If we declare age outside the method, it will give a compilation error.

Instance Variables in Java:

The instance variable is also known as a non-static variable. It is always declared in a class but outside the method, block, or constructor. The instance variable is created when an object of the class is created and destroyed when the object is destroyed. Instance Variables can only be accessed by creating the objects of the class. The initialization of the instance variable is not required, it takes the default value as 0.

Scope of Instance Variable: Throughout the class except in static methods.

The lifetime of Instance Variable: Until the object is available in the memory.

Example to Understand Instance Variables in Java:
package Demo;
class Marks
{
    // These variables are instance variables. 
    // These variables are in a class 
    // and are not inside any function 
    int engMarks;
    int mathsMarks;
    int phyMarks;
}
class InstanceVariableExample
{
    public static void main (String args[])
    {
        //Object
        Marks obj1 = new Marks ();
        obj1.engMarks = 50;
        obj1.mathsMarks = 80;
        obj1.phyMarks = 90;

        // displaying marks for object 
        System.out.println ("Marks for first object:");
        System.out.println (obj1.engMarks);
        System.out.println (obj1.mathsMarks);
        System.out.println (obj1.phyMarks);
    }
}
Output:

Example to Understand Instance Variables in Java

Static Variables in Java:

The static variable is also known as the Class Variable. Static variables are created at the start of program execution and destroyed automatically when execution ends. These variables are declared similarly to instance variables, the difference is that static variables are declared using the static keyword within a class outside any method constructor or block. Initialization of Static Variable is not mandatory, it’s default value is 0. If we access the static variable without the class name, the Compiler will automatically append the class name.

To access static variables, we need not create an object of that class, we can simply access the variable as class_name.variable_name;

Scope of Static Variable: Throughout the class.

The lifetime of Static Variable: Until the end of the program.

Example to Understand Static Variables in Java:
package Demo;
class Employee
{
    // static variable salary 
    public static double salary;
    public static String name = "Harsh";
}
public class StaticVariableExample
{
    public static void main (String[]args)
    {
        // accessing static variable without object 
        Employee.salary = 1000;
        System.out.println (Employee.name + "'s average salary:" + Employee.salary);
  }
}

Output: Harsh’s average salary:1000.0

In the next article, I am going to discuss the Identifiers and Reserved Words in Java with Examples. Here, in this article, I try to explain Variables in Java with Examples and I hope you enjoy this Java Variables with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this Java Variables with Examples article.

Leave a Reply

Your email address will not be published.