Variables in Java – Core Java tutorial

Posted by :
Last updated : February 3, 2023

In this blog post, we will be diving deep into the world of variables in Java. We will be covering everything from the basics of declaring and initializing variables, to the more advanced concepts of final variables and the difference between local, instance, and static variables.

We will then go on to explore the rules and conventions that must be followed when declaring and initializing variables in Java.

Finally, we will wrap up the post by discussing the importance of understanding variables in Java and how they can be used effectively to write efficient, maintainable, and readable code. Whether you are a beginner or an experienced Java developer, this post will provide valuable insights and information on the topic of variables in Java.

Must Read:

What are variables in Java?

  • In Java, a variable is a named storage location in the computer’s memory that holds a value of a specific data type.
  • Variables in Java are used to store and manipulate data in a program.
  • They have a name, a data type, and a value.
  • The data type determines the kind of value that can be stored in the variable, such as an integer, a floating-point number, or a character.
  • Variables must be declared before they can be used in a program, and they can be assigned a value using the assignment operator (=).

How to declare the variables in Java?

In Java, variables are declared using the following syntax:

dataType variableName;

For example, to declare an integer variable named “x”, you would use the following code:

int x;

You can also assign a value to a variable when it is declared, like this:

int x = 5;

You can also declare multiple variables of the same data type in one line, like this:

int a, b, c;

(or)

int a = 1, b = 2, c = 3;

How to Initialize the variables in Java?

In Java, variables are initialized by assigning a value to them. There are several ways to initialize variables in Java:

  • Assigning a value at the time of declaration:
int x = 5;
  • Assigning a value later on in the code:
int x;
x = 5;
  • Initializing multiple variables at the time of declaration:
int x = 5, y = 7, z = 9;
  • Initializing a variable using a constructor or a method:
String name = new String("John");
  • Initializing a variable using an expression:
int x = 2 + 3;

It’s important to note that variables in Java must be initialized before they are used. If a variable is not initialized and its value is used, the program will generate a compile-time error.

Also, you can initialize the variable with default value depending on the datatype which is 0 for numbers, false for boolean and null for references.

Rules to be followed while declaring variables in Java:

There are several rules that should be followed while declaring variables in Java:

  1. Variable names in Java must begin with a letter, dollar sign ($), or an underscore (_). Subsequent characters may be letters, digits, dollar signs, or underscores.
  2. Variable names cannot contain whitespace or any special characters other than $ and _.
  3. Variable names are case-sensitive, so “x” and “X” are considered to be two different variables.
  4. Variable names cannot be the same as any of the Java reserved words (such as “int”, “for”, “while”, etc.).
  5. Variable names should be meaningful and should describe the purpose of the variable.
  6. Variable names should follow naming conventions, usually camelCase or snake_case.
  7. In Java, variable names cannot start with a number but can contain numbers.
  8. A variable should be declared with a specific data type like int, String, boolean etc.
  9. A variable can’t be re-declared with the same name within the same scope.
  10. A variable should be initialized before using, otherwise, the program will generate a compile-time error.

By following these rules, you can ensure that your variables are properly declared and can be easily understood by others who may read your code.

How variables in Java are stored?

In Java, variables are stored in different places depending on their type and scope.

  • Primitive variables (such as int, char, and boolean) are stored on the stack. The stack is a part of the memory that is used to store temporary data, such as method arguments and local variables. The stack is created when a program starts and is destroyed when the program ends.
  • Reference variables (such as String, Array, and Object) are stored on the heap. The heap is a part of the memory that is used to store objects. The heap is created when a program starts and is destroyed when the program ends.
  • Instance variables and static variables are stored in the same place as reference variables (on the heap), but they are associated with a class rather than a specific instance of the class.
  • Parameters are stored on the stack like local variables. They are created when a method is called and are destroyed when the method returns.

It’s important to note that the exact location of variables in memory is determined by the Java Virtual Machine (JVM) and may vary from one implementation to another.

What are the different types of variables in Java?

There are three different types of variables in Java:

  • Static variables
  • Instance variables
  • Local variables
types of variables in Java

Static Variables:

In Java, a static variable is a variable that is associated with a class, rather than an instance of the class. This means that there is only one copy of the variable, shared among all instances of the class. The value of a static variable can be accessed by using the class name, rather than an instance of the class.

Here are a few examples of static variables in Java:

  • In the following example, PI is a static variable that is associated with the Math class. It is a constant that represents the value of pi and can be accessed by using the class name, rather than an instance of the class.
public class MyMath {
    public static final double PI = 3.14;
}
  • In the following example, count is a static variable that is associated with the Student class. It keeps track of the number of instances of the class that have been created.
public class Student {
    private String name;
    private static int count = 0;

    public Student(String name) {
        this.name = name;
        count++;
    }

    public static int getCount() {
        return count;
    }
}
  • In the following example, x is a static variable that is associated with the MyClass class. It can be accessed by using the class name, rather than an instance of the class.
public class MyClass {
    public static int x;
}

It’s important to note that, Static variables are class level variable and are shared among all instances of the class and can be accessed by class name. They are initialized before the first object of that class is created and are also initialized before the execution of the main method.

In summary, static variables are associated with a class, rather than an instance of the class. They are only one copy of the variable, shared among all instances of the class. They can be accessed using the class name.

Instance Variables:

In Java, instance variables are variables that are associated with an instance of a class, rather than the class itself. Each instance of the class has its own copy of the instance variable, and the value of the variable can vary between instances.

Here are a few examples of instance variables in Java:

  • In the following example, name and age are instance variables that are associated with the Person class. Each instance of the Person class has its own copy of these variables, and their values can vary between instances.
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}
  • In the following example, balance is an instance variable associated with the Account class. Each instance of the Account class has its own copy of this variable, and the value of the variable can vary between instances.
public class Account {
    private double balance;

    public Account(double balance) {
        this.balance = balance;
    }

    public double getBalance() {
        return balance;
    }
}
  • In the following example, x and y are instance variable that are associated with the MyClass class. Each instance of the MyClass class has its own copy of these variables, and the values of the variables can vary between instances.
public class MyClass {
    public int x;
    public int y;
}

It’s important to note that, Instance variables are object level variable and are unique to each object of the class and they are initialized with default value, when object is not initialized with any value.

In summary, Instance variables are associated with an instance of a class, rather than the class itself. Each instance of the class has its own copy of the variable, and the value of the variable can vary between instances. They are initialized with default value, when object is not initialized with any value.

Local Variables:

In Java, local variables are variables that are defined within a method or block of code. They are only accessible within the scope of the method or block of code in which they are declared and are not accessible from outside of that scope.

Here are a few examples of local variables in Java:

  • In the following example, variable result is a local variable that is declared and initialized within the addNumbers method. It is only accessible within the scope of that method:
public int addNumbers(int a, int b) {
    int result = a + b;
    return result;
}
  • In the following example, variable x and y are local variables that are declared and initialized within the printSum method. They are only accessible within the scope of that method:
public void printSum(int a, int b) {
    int x = a;
    int y = b;
    int sum = x + y;
    System.out.println("The sum is: " + sum);
}
  • In the following example, variable i is local variable that is declared within the for loop and is only accessible within the scope of that loop:
for (int i = 0; i < 10; i++) {
    System.out.println(i);
}

It’s important to note that, local variables are not given default value, so they must be assigned a value before being used.

In summary, Local variables are defined within a method or block of code and are only accessible within that scope. They must be assigned a value before they can be used.

Difference between local, instance and static variables in Java

Here is a table that summarizes the main differences between local, instance, and static variables in Java:

Local VariableInstance VariableStatic Variable
DefinitionVariables defined within a method or a constructorVariables defined within a class but outside of any method or constructorVariables defined within a class but using the static keyword
LifetimeExists only within the scope of the method or constructor where it is definedExists for the lifetime of the object of the classExists for the lifetime of the program
Memory AllocationAllocated on the stackAllocated on the heapAllocated on the heap
AccessibilityAccessible only within the method or constructor where it is definedAccessible throughout the class, but not outside of itAccessible throughout the program, using the class name
Association with an objectNot associated with an objectAssociated with an objectAssociated with a class, not an object
Default ValueNot assigned any default valueAssigned default value (null for objects, 0 for numeric types, false for boolean)Assigned default value (null for objects, 0 for numeric types, false for boolean)

In summary, Local variables are only accessible within the scope of the method or constructor where it is defined, Instance variables are associated with an object, and Static variables are associated with a class, not an object. The memory allocation and default value also differentiates among these three types of variables.

What are Final variables in Java?

In Java, a final variable is a variable that cannot be modified once it has been initialized. Once a final variable has been assigned a value, it cannot be reassigned to a different value.

Here are a few examples of final variables in Java:

  • In the following example, PI is a final variable that represents the value of pi. It is assigned a value of 3.14 at the time of declaration, and it cannot be reassigned to a different value later on.
public class MyClass {
    public static final double PI = 3.14;
}
  • In the following example, name is a final variable that represents the name of a person. It is assigned a value in the constructor, and it cannot be reassigned to a different value later on.
public class Person {
    private final String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}
  • In the following example, maxSpeed is a final variable that represents the maximum speed of a car. It is assigned a value in the constructor, and it cannot be reassigned to a different value later on.
public class Car {
    private final int maxSpeed;

    public Car(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    public int getMaxSpeed() {
        return maxSpeed;
    }
}

It’s important to note that, Final variables must be initialized at the time of declaration or within constructor, as they cannot be reassigned any value later on. Also, They are also known as constants.

In summary, Final variable is a variable that cannot be modified once it has been initialized, it must be initialized at the time of declaration or within constructor, as they cannot be reassigned any value later on and also known as constants.

Follow us on YouTube:

See you soon!

Variables are an essential part of programming in Java and understanding how to use them effectively is crucial for writing efficient, maintainable, and readable code. This blog post has provided an in-depth look at the different types of variables in Java including final variables, local, instance and static variables and the differences between them.

We have also discussed the rules and conventions that must be followed when declaring and initializing variables in Java, and how final variables can be used to create immutable objects.

By understanding the concepts covered in this post, developers can improve their ability to write clear and efficient code that is easy to understand and maintain. It’s also important to note that, variables are not only limited to the ones discussed here, but also other types like transient and volatile variables, that have different characteristics and usage.

Overall, Variables are one of the fundamental concepts in programming, and understanding how to use them effectively in Java is a crucial step in becoming a skilled and proficient Java developer.

Leave a Comment