Variables in Java

In this tutorial, we will learn about variables in Java programming. A variable is a container in Java that holds data or value during the execution of a program. In other words, a variable is a named location in the memory of the computer where the values are stored. It has a name, a type and a value.

Each variable is associated with a data type that determines the kind of data or value it can store. For example, if you define a variable to store an integer value, you can’t use it to store a decimal fraction value, such as 0.50. Note that a variable can store only one value at a time. If the value is reassigned, the previous value is overwritten.

Variables in Java

Declaration of Variables in Java

To use a variable in a Java program, you must first declare it. The declaration involves specifying the name of variable, and data type of the variable. Each variable must be declared with a specific data type before you use it. The general syntax for declaring variables in Java is as follows:

data_type variable_name;

Here’s some example:

int age; // name of variable is age and data type is int.
String name; // name of variable is name and data type is String.
boolean isAbsent; // name of variable is isAbsent and data type is boolean.
float x, y, z;

Initialization of Variables in Java

After declaring a variable in a Java program, you must assign it with a value before using it in any expression. There are the following ways bu which you can initialize variables in Java programming. Here are the common methods:

1. Direct Initialization

This is the simplest method where you can directly initialize a value to a variable. The general syntax to assign a value to the variable is as follows:

data_type variable_name = variable_value;

Here are some examples of the initialization of variables with values:

int number = 10; // name of variable is number, data type is int and initialized value is 10. 
String language = "Java Programming"; // name of variable is language, data type is String and initialized value is Java programming.
String name = "John"; // name of variable is name, data type is String and initialized value is John.

2. Initialization of Variables using Constructor

You can initialize instance variables in Java by using a class constructor. Let’s take an example in which we will initialize a value to the variable using a class constructor.

// Define a class named Test.
public class Test {
// Declare an instance variable named number.
   int number;

// Declare a constructor to initialize the value of the variable. 
   public Test(int num) {
        this.number = num;
   }
// Main method.
public static void main(String[] args) {
// Create an object of class Test and pass the value to its constructor.
   Test obj = new Test(10);
// Displaying the value of variable.
   System.out.println(obj.number);
  }
}
Output: 
    10

3. Initialization of Variables using a Method

We can initialize values to variables through methods in Java. This approach is useful for setting or updating values of instance variables or static variables based on program logic, user input, or other external factors. Look at the below simple example.

public class Test {
  int number;

// Declare a method to initialize the variable. 
   public void setNumber(int num) {
     this.number = num;
   }
public static void main(String[] args) {
   Test obj = new Test();
   obj.setNumber(20); // Initializing the variable through a method.
   System.out.println("Number: " + obj.number);
  }
}
Output:
     20

4. Initialization of Variables using Instance Block

You can initialize instance variables using an instance block in Java. Here’s a simple example of it.

public class Test {
 int number;
// Declare an instance block.
 {
   number = 10; // Initializing.
 }
public static void main(String[] args) {
   Test obj = new Test();
   System.out.println(obj.number);
  }
}
Output:
     20

5. Initializing Variables using Default Values

Instance and static variables in Java are automatically initialized with default values, if you have not explicitly initialized them. This default initialization ensures that they have valid values even if you don’t explicitly assign them. The default values for an instance and static variables in Java are as follows:

  • Integer types (byte, short, int, long): Default value is 0.
  • Floating-point (float, double): Default value is 0.0.
  • Character (char): Default value is ‘\u0000’ (null character).
  • Boolean: Default value is false.
  • Reference types (like objects, arrays, or String): Default value is null.
public class DefaultValues {
// Declaring instance variables.
  int number;     // Default: 0
  double decimal; // Default: 0.0
  char character; // Default: '\u0000'
  boolean flag;   // Default: false
  String text;    // Default: null

// Declare a static variable.
static int staticNumber; // Default: 0 (shared across all instances)

public static void main(String[] args) {
// Creating an object of class DefaultValues.
  DefaultValues obj = new DefaultValues();

// Displaying the output.
  System.out.println("Instance Variable 'number': " + obj.number);
  System.out.println("Static Variable 'staticNumber': " + DefaultValues.staticNumber);
  System.out.println("Reference Type 'text': " + obj.text);
  }
}
Output:
     Instance Variable 'number': 0
     Static Variable 'staticNumber': 0
     Reference Type 'text': null

6. Initializing Variables Using Constants

If you declare a variable with a final keyword, it must be initialized either at the time of declaration or in the constructor.

public class Example {
// Declare a final variable.
    final int CONSTANT = 20; // Initialized during declaration.
}

Rules for Naming Variables in Java

There are the following rules of naming or defining variables in Java that you should remember while creating. They are as follows:

  • A variable name in Java can only start with a letter, an underscore (_), or a dollar sign ($). For example, myVar, my_var, $value.
  • Variable name can not start with a number. value1 is a valid variable name, but 1valid is an invalid variable name.
  • A variable name can be a combination of letters, digits, underscores, and dollar sign.
  • After the first character, you may include any letter or number.
  • Variable names cannot be a reserved keyword in Java. For example, int, class, static, etc. cannot be name of variables because there are Java keywords.
  • Since Java language is case-sensitive in nature, therefore, the lowercase variable is different from uppercase and vice versa. For example, myVar and MyVar will be treated as two different variables in Java. Look at the below example.
public class CaseSensitiveExample {
public static void main(String[] args) {
  int myVar = 10;
  int MyVar = 20;

  System.out.println("Value of myVar: " + myVar); 
  System.out.println("Value of MyVar: " + MyVar);
  }
}
Output:
      Value of myVar: 10
      Value of MyVar: 20

In this example, myVar and MyVar are considered as two completely separate variables because of their difference in case. This proves that Java is a case-sensitive programming language.

  • You cannot declare two variables with the same name in the same scope.
int num = 5;
int num = 10; // Error: Duplicate variable declaration.

Camel Case for Variable Names

You should use camelCase for naming regular variables, where the first word starts with a lowercase letter, and subsequent words start with an uppercase letter. For example:

int studentName;
double maxScore;
boolean isActive;

Uppercase with Underscores for Final Constants

You can use the uppercase with underscores for constants declared with the final keyword. This makes them easily distinguishable as constants. Look at the below examples.

final double PI = 3.14159;
final int MAX_VALUE = 100;

These naming conventions improve readability of the Java code and maintain consistency, making it easier for others (and yourself) to understand the purpose and type of variables in your code.

Types of Variables in Java

We can broadly categorize Java variables into three categories based on their scope and lifetime. They are as:

  • Local variables
  • Instance variables
  • Static variables

You will learn about local, instance, and static variables in Java in the further tutorial one by one with the help of various examples.

Please Share Your Love.

Leave a Reply

Your email address will not be published. Required fields are marked *