Java Variables

Within Java programming, a variable serves as an identifier for a memory location utilized as a repository for holding values throughout the execution of a Java program. Each variable necessitates association with a data type to specify the type of data it is capable of storing. Java classifies variables into three distinct types: local variables, instance variables, and static variables. This section will delve into an exploration of Java variables and their types, supplemented with illustrative examples.

Prior to delving into Java variables and their classifications, it is essential to have a grasp of the concept of variables and the conventions for naming them.

What is a Variable?

A variable represents a designated space in memory that can be altered during program execution. Essentially, it denotes a specific memory address. The term "variable" is derived from "vary + able," indicating that its stored value is modifiable.

Example

int data=50;//Here data is variable

Types of Java Variables

There are three types of variables in Java :

  • Java Local Variable
  • Java Instance Variable
  • Java Static Variable
  • 1) Java Local Variable

A variable that is defined within a method's body is referred to as a local variable. This variable is only accessible within the method where it is declared, and other methods within the same class are not able to access or be aware of its existence.

It is not possible to declare a local variable using the "static" keyword.

Example of Local Variable

Consider the following example to illustrate the concept of Local Variables in Java.

Example

Example

//defining a Local Variable

        int num = 10;

        System.out.println(" Variable: " + num);

Output:

Output

Variable: 10

2) Java Instance Variable

An instance variable is a variable declared within a class but outside of any method body. It differs from a static variable as it is not declared with the static keyword.

Referred to as an instance variable, its value is unique to each instance and not shared across instances.

Example of Instance Variable

Consider the following example to illustrate the concept of Instance Variables in Java.

Example

Example

public class InstanceVariableDemo {

    //Defining Instance Variables

    public String name;

    public int age=19;

 //Creadting a default Constructor initializing Instance Variable

    public InstanceVariableDemo()

    {

        this.name = "Deepak";

    }

}

public class Main{

    public static void main(String[] args)

    {

        // Object Creation

       InstanceVariableDemo obj = new InstanceVariableDemo();

        System.out.println("Student Name is: " + obj.name);

        System.out.println("Age: "+ obj.age);

    }

}

Output:

Output

Student Name is: Deepak

Age: 19

3) Java Static Variable

A static variable is a variable declared with the static keyword, making it inaccessible as a local variable. With static variables, a single instance can be shared across all class instances. Memory for static variables is allocated only once during class loading into memory.

Example Static Variable

Consider the following example to illustrate the concept of a Static Variable in Java.

Example

Example

class Student{

    //static variable

   static int age;

}

public class Main{

   public static void main(String args[]){

       Student s1 = new Student();

       Student s2 = new Student();

       s1.age = 24;

       s2.age = 21;

       Student.age = 23;

       System.out.println("S1\'s age is: " + s1.age);

       System.out.println("S2\'s age is: " + s2.age);

   }

}

Output:

Output

S1's age is: 23

S2's age is: 23

More Examples on Java Variables

Let's explore additional instances to enhance comprehension of Java variables:

Variables Example 1: Add Two Numbers

In this program, we utilize variables to hold values and execute an addition operation. The values are stored in variables referred to as a and b, while another variable, c, is used to store the sum of a and b. Finally, the program outputs the result.

Example

Example

int a=10;  

int b=10;  

int c=a+b;  

System.out.println(c);

Output:

Variables Example 2: Widening Type Casting

The following illustration showcases implicit type conversion in Java. In this scenario, an integer variable 'a' holds the integer value 10, which is implicitly transformed into a float type and stored in variable 'f'. Subsequently, both 'a' and 'f' are displayed, highlighting Java's capability to convert an integer to a float seamlessly without any loss of information.

Example

Example

int a=10;

float f=a;

System.out.println(a);

System.out.println(f);

Output:

Output

10

10.0

Variables Example 3: Narrowing Type Casting

In this illustration, we showcase the explicit conversion of a float to an int in Java. Attempting to assign a float variable 'f' directly to an int variable 'a' results in a compilation error due to the lack of automatic conversion between a float and an int. However, by employing (int)f, the float value of 10.5 undergoes type casting to 10, effectively discarding the decimal portion. Subsequently, both the original float value and the truncated integer value are outputted.

Example

Example

float f=10.5f;

//int a=f;//Compile time error

int a=(int)f;

System.out.println(f);

System.out.println(a);

Output:

Output

10.5

10

Variables Example 4: Overflow

The following illustration showcases an overflow scenario when performing explicit type conversion in Java. Specifically, the integer 130 is explicitly converted to a byte. Due to the byte data type's range being from -128 to 127, the conversion causes an overflow, producing the value of -126.

Example

Example

//Overflow

int a=130;

byte b=(byte)a;

System.out.println(a);

System.out.println(b);

Output:

Output

130

-126

Variables Example 5: Adding Lower Type

The following example illustrates type promotion in Java. Despite a and b being of type byte, the operation a + b is automatically elevated to int, resulting in a compilation error if assigned to a byte. By explicitly casting the outcome to byte, the value can be stored in c and printed without any issues.

Example

Example

byte a=10;

byte b=10;

//byte c=a+b;//Compile Time Error: because a+b=20 will be int

byte c=(byte)(a+b);

System.out.println(c);

Output:

Input Required

This code uses input(). Please provide values below: