Java variable

  • A variable is a container that stores a value while the Java program is running. A variable is assigned with a data type.
  • Variable is a name of memory or data store location. There are three main types of variables in Java: local, instance, and static.
  • A variable is a symbolic name given to a reserved area of memory. In simpler terms, it is an identifier for a memory location.

Declaring (Creating) Variables

To create a variable, you must specify the data type and assign it a value:

Syntax:

data type variable = value; // Next topic will be discuss about data type

Where data type is one of Java’s data type (such as int or double), and variable is the name of the variable (such as x or price ).

The equal sign (=)  is used to assign values to the variable.

To create a variable that can store text, consider the following example:

double price = 4.5; 
System.out.println(price);
Explanation:
  •  Here double is data type and price is variable that store a value.

Types of Variables:

There are three types of variables in Java:

  1. local variable
  2. instance variable
  3. static variable

 

1. Local Variable:

A local variable in Java is a variable that is declared within a method, constructor, or block of code, and its scope is limited to that specific block. Local variables are used to store temporary data that is only needed within the scope of the block where they are declared.

Here are some characteristics of local variables in Java:

  • Scope: The scope of a local variable is defined by the block of code in which it is declared. It starts from the point of declaration and lasts until the end of the block or the method where it is declared.
  • Declaration and Initialization: Local variables must be explicitly declared and initialized before they can be used. They do not have default values like instance variables (class fields).
  • Visibility: Local variables are only visible within the block of code where they are declared. They cannot be accessed from outside that block or from other methods.
  • Memory Allocation: Memory for local variables is allocated on the stack. When the block of code is exited, the memory for the local variables is automatically reclaimed.
Example of Java local variables:
public class LocalVariableExample {

    public void exampleMethod() {
        // This is a local variable 'count' within the method scope
        int count = 5;
        System.out.println("Inside the method: " + count);

        // We can also have local variables inside a block
        if (count > 0) {
            int temp = count * 2;
            System.out.println("Inside the block: " + temp);
        }

        // The variable 'temp' cannot be accessed here, as it's outside the block where it was declared.
        //Removing the comment from the next line will lead to an error.
        // System.out.println("Outside the block: " + temp);
    }

    public static void main(String[] args) {
        LocalVariableExample example = new LocalVariableExample();
        example.exampleMethod();
    }
}
Explanation:
  • In this example, count and temp are both local variables. count is declared within the exampleMethod() scope and can be accessed throughout the method. temp, on the other hand, is a local variable declared inside the if-block and is only accessible within that block.
  • Remember that attempting to access a local variable outside its scope will result in a compilation error.
2. Instance Variable:

A variable declared within a class but outside the body of a method is referred to as an instance variable. It is not defined as static. It is called an instance variable because its value is specific to one instance and is not shared among instances.

Example of Java instance variables:
import java.io.*;
public class Employee {

       // this instance variable is visible for any child class.
       public String name;

       // salary  variable is visible in Employee class only.
       private double salary;

       // The name variable is assigned in the constructor.
       public Employee (String empName) {
          name = empName;
       }

       // The salary variable is assigned a value.
       public void setSalary(double empSal) {
          salary = empSal;
       }

       // This method prints the employee details.
       public void printEmp() {
          System.out.println("name: " + name );
          System.out.println("salary: " + salary);
       }

    public static void main(String[] args) {
         Employee empOne = new Employee("Mariya");
          empOne.setSalary(20000);
          empOne.printEmp();
    
    }

}
Output:

name: Mariya

salary: 20000.0

Explanation:
  • This line imports the java.io package, which is not currently used in the code. The import statement allows you to use classes from other packages without having to write their fully qualified names.
  • This line defines the class named Employee. It serves as the blueprint for generating objects of type Employee.
  • These are the class’s instance variables. name is declared as public, which means it can be accessed directly from outside the class. salary is declared as private, which means it can only be accessed within the Employee class itself.
  • This is a constructor for the Employee class. It is called when a new Employee object is created. It takes a parameter empName, which is used to set the name of the employee.
  • This is a method named setSalary, which takes a parameter empSal. It sets the value of the salary variable to the value passed as an argument.
  • This is a method named printEmp. It prints the name and salary of the employee to the console.
  • This is the main method, which serves as the entry point of the program. It creates a new Employee object called empOne, passing the name “Mariya” to the constructor. Then, it calls the setSalary method to set the salary of the employee to 20000. Finally, it calls the printEmp method to print the employee’s details to the console.
  • Overall, this code demonstrates the basics of class and object creation in Java. It defines an Employee class with a constructor, methods, and instance variables. It then creates an Employee object, sets its salary, and prints its details.
3. Static Variable:

In Java, a static variable is a class-level variable that is shared across all instances of the class. It exists independently of any instances created from the class and is initialized when the class is loaded by the Java Virtual Machine (JVM). Static variables are commonly used to maintain a single value for the entire class, such as constants or properties that should be consistent for all instances. They can be accessed using the class name followed by the dot operator.

Example of Java static variables:
import java.io.*;
public class Employee {
    
     // salary  variable is a private static variable
       private static double salary;

       // DEPARTMENT is a constant
       public static final String DEPARTMENT = "Development ";

    public static void main(String[] args) {
        salary = 20000;
        System.out.println(DEPARTMENT + "average salary:" + salary);

    }

}
Output:

Development average salary: 20000.0

Explanation:
  • public class Employees { … }
  • This line defines the class named Employees. It is the blueprint for creating objects of type Employees.
  • private static double salary;
  • This line declares a private static variable named salary. The variable is of type double, which means it can store floating-point (decimal) numbers. Being declared as static, there will be only one copy of this variable shared among all instances of the class Employees.
  • public static final String DEPARTMENT = “Development “;
  • This line declares a public static final constant variable named DEPARTMENT. It is of type String and is initialized with the value “Development”. Being declared as static and final, this variable is a class-level constant that cannot be changed after initialization.
  • public static void main(String[] args) { … }
  • This is the main method, which serves as the entry point of the program. It is the method that gets executed when you run the Java program.
  • salary = 20000;
  • This line sets the value of the salary variable to 20000.
  • System.out.println(DEPARTMENT + “average salary:” + salary);
  • This line prints the department name along with the average salary to the console. The + operator is used for string concatenation. The constant DEPARTMENT is concatenated with the string “average salary:” and the value of the salary variable, and the result is printed to the console.
  • So, when you run this program, it will output the following line to the console:
  • The output contains “20000.0” because the salary variable is of type double, and by default, the println method prints floating-point numbers with a decimal point. If you want to display it as an integer, you can convert it explicitly or change the salary variable type to int.
Visited 1 times, 1 visit(s) today

Comments are closed.

Close