Java variable

  • A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type.
  • Variable is a name of memory or data store location. There are three types of variables in java: local, instance and static.
  • A variable is the name of a reserved area allocated in memory. In other words, it is a name of the 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 should store text, look at 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.
        // Uncommenting the next line will result in 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 inside the class but outside the body of the method is called 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 is the blueprint for creating 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:
  • Class variables, which are also known as static variables, are declared with the static keyword in a class, but not within a method, constructor, or block.
  • There will be only one copy of each class variable per class, regardless of how many objects are created from it.
  • Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value.
  • Static variables are stored in the static memory. It is rare to use static variables that are not declared final and are used as either public or private constants.
  • Static variables are created when the program starts and destroyed when the program stops.
  • Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
  • Default values are the same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks.
  • Static variables can be accessed by calling the class name ClassName.VariableName.
  • When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.
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