Java variable type

Variables provide named storage that programs can manipulate. Every variable in Java has a type, which determines the size and layout of the variable's memory; the range of values ​​that can be stored in that memory; and the set of operations that can be applied to the variable.

Variables need to be declared before they can be used, following is the basic form of variable declaration −

data type variable [ = value][, variable [ = value] ...] ;
 
Here data typeis one of Java's data types and variableis the name of the variable. To declare multiple variables of the same type, a comma-separated list can be used.

Following is an example of variable declaration and initialization in Java −

int a, b, c;         //declared vairables
int a = 10, b = 10;  // assigned values
byte B = 22;         // Declare and initialize a variable of type byte: B
double pi = 3.14159; // Declare and assign a variable of type double: PI
char a = 'a';        // Declare a char type variable a, and initialize the value to: 'a'
 

This chapter will explain the various variable types in the Java language. There are three kinds of variables in Java −

  • local variable
  • instance variable
  • class/static variable

1. Local variables

  • Local variables are generally declared within methods, constructors or blocks.
  • Local variables are created when a program enters a method, constructor, or block, and are destroyed once the method, constructor, or block exits.
  • Access modifiers cannot be used on local variables.
  • Local variables are only visible within the declared method, constructor or block.
  • Local variables implement stack levels internally.
  • Local variables do not have default values, so after declaring a local variable, assign it an initial value before using it for the first time.

Example

Here, ageis a local variable. This is dogAge()defined in a method and its scope is limited to this method.

public class Test {
   public void dogAge() {
      int age = 0;
      age = age + 5;
      System.out.println("Dog age is : " + age);
   }

   public static void main(String args[]) {
      Test test = new Test();
      test.dogAge();
   }
}

Execute the above sample code and get the following results:

Dog age is : 5
Shell

Example

The following example uses a variable age, but does not initialize it, so an error occurs at compile time.

public class Test {
   public void dogAge() {
      int age;
      age = age + 5;
      System.out.println("Dog age is : " + age);
   }

   public static void main(String args[]) {
      Test test = new Test();
      test.dogAge();
   }
}
 

Execute the above sample code and get the following result (error):

Test.java:4:variable number might not have been initialized
age = age + 5;
         ^
1 error
Shell

 

2. Instance variables

  • Instance variables are declared within a class, but outside a method, constructor, or block.
  • When space is allocated for an object in the heap, a slot is created for each instance variable value.
  • newInstance variables are created when an object is created using keywords and are destroyed when the object is destroyed.
  • Instance variables contain values ​​referenced by multiple methods, constructors, or blocks, or essential parts of an object's state that exist throughout the class.
  • Instance variables can be declared at the class level before or after use.
  • Access modifiers can be given for instance variables.
  • Instance variables are visible to all methods, constructors and blocks in the class. In general, it is recommended to make these variables private (access level). However, access modifiers can be used to provide subclass visibility to these variables.
  • Instance variables have default values. The default is for numbers, it is 0for booleans, and it is falsefor object references null. Values ​​can be specified during declaration or in the constructor.
  • Instance variables can be accessed directly by calling the variable name in the class. However, in static methods (when instance variables have accessibility), they should be called using fully qualified names like: ObjectReference.VariableName

 

import java.io.*;
public class Employee {

   // This instance variable is visible to subclasses.
   public String name;

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

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

   // assign a value to the salary variable
   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("Maxsu");
      empOne. setSalary(15999);
      empOne. printEmp();
   }
}

 

Output:

name  : Maxsu
salary :15999.0
 

3. Classes/static variables

  • Class variables (also known as static variables) are staticdeclared using the keyword within a class, but outside a method, constructor, or block.
  • There is only one copy of each class variable per class, no matter how many objects are created from it.
  • Static variables are rarely used except when declared as constants. Constants are variables declared as public/private, finaland . staticThe initial value of a constant cannot be changed.
  • Static variables are stored in static memory. Static variables are rarely used other than declared ones finaland used as public or private constants.
  • Static variables are created when the program starts and are destroyed when the program stops.
  • Visibility is similar to instance variables. However, most static variables are public because they must be available to users of that class.
  • Defaults are the same as instance variables. For numbers, the default is 0; for boolean types, the default is false; for object references, the default is null. Values ​​can be specified during declaration or in the constructor. Additionally, values ​​can be assigned in special static initializer blocks.
  • ClassName.VariableNameStatic variables can be accessed by calling them with the class name .
  • When public static finaldeclaring , the variable names (constants) are all uppercase. If the static variable is not publicand final, the naming syntax is the same as instance and local variable naming rules.

 

Example

 

import java.io.*;
public class Employee {

   // the salary variable is a private static variable
   private static double salary;

   // DEPARTMENT is a constant
   public static final String DEPARTMENT = "R&D Department";

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

Output:

R&D department average salary:19999