Java Variable Type

Keywords: Java Back-end

In the Java language, all variables must be declared before they can be used. The basic format for declaring variables is as follows:

type identifier [ = value][, identifier [= value] ...] ;

Format description: Typee is a Java data type. identifier is the variable name. You can declare multiple variables of the same type separated by commas.

Some examples of variable declarations are listed below. Note that some include the initialization process.

int a, b, c;             // Declare three integers of type int: a, b, c
int d = 3, e = 4, f = 5; // Declare three integers and assign initial values 
byte z = 22;             // Declare and initialize z
String s = "runoob";     // Declare and initialize string s 
double pi = 3.14159;     // Declares the double-precision floating-point variable pi
char x = 'x';            // The value of the declared variable x is the character'x'.

The types of variables supported by the Java language are:

  • Class variables: Variables independent of methods, modified with static.
  • Instance variable: A variable independent of the method, but without a static modifier.
  • Local variable: A variable in a class's method.

Example

public class Variable{ 

    static int allClicks=0; // Class variable
 
    String str="hello world"; // Instance variable

    public void method(){ 

        int i =0; // local variable

    } 
}

Java Local Variables

  • Local variables are declared in a method, construction method, or statement block;
  • Local variables are created when a method, construction method, or statement block is executed, and when they are executed, the variable is destroyed.
  • Access modifiers cannot be used for local variables;
  • Local variables are only visible in the method, construction method, or statement block that declares them;
  • Local variables are allocated on the stack.
  • Local variables have no default values, so they must be initialized before they can be used after they are declared.

Instance 1

In the following example, age is a local variable. Defined in the pupAge() method, its scope is limited to that method.

package com.runoob.test;
 
public class Test{ 
   public void pupAge(){
      int age = 0;
      age = age + 7;
      System.out.println("The puppy's age is: " + age);
   }
   
   public static void main(String[] args){
      Test test = new Test();
      test.pupAge();
   }
}

The above example compiles and runs as follows:

The puppy's age is: 7

Instance 2

In the following example, the age variable was not initialized, so an error occurred during compilation:

package com.runoob.test;
 
public class Test{ 
   public void pupAge(){
      int age;
      age = age + 7;
      System.out.println("The puppy's age is : " + age);
   }
   
   public static void main(String[] args){
      Test test = new Test();
      test.pupAge();
   }
}

The above example compiles and runs as follows:

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

Instance variable

  • Instance variables are declared in a class, but outside methods, constructors, and statement blocks;
  • When an object is instantiated, the value of each instance variable is determined.
  • Instance variables are created when objects are created and destroyed when objects are destroyed.
  • The value of an instance variable should be referenced by at least one method, construction method, or statement block so that information about the instance variable can be obtained externally.
  • Instance variables can be declared before or after use;
  • Access modifiers can modify instance variables;
  • Instance variables are visible to methods, constructors, or statement blocks in a class. In general, instance variables should be made private. You can make instance variables visible to subclasses by using access modifiers;
  • Instance variables have default values. The default values for numeric variables are 0, Boolean variables are false, and reference type variables are null. The value of a variable can be specified at the time of declaration or in a construction method.
  • Instance variables can be accessed directly from the variable name. However, in static methods and other classes, the fully qualified name should be used: ObejectReference.VariableName.

Example

Employee.java file code:

import java.io.*;
public class Employee{
   // This instance variable is visible to subclasses
   public String name;
   // Private variable, visible only in this class
   private double salary;
   //Assigning a name in a constructor
   public Employee (String empName){
      name = empName;
   }
   //Set salary value
   public void setSalary(double empSal){
      salary = empSal;
   }  
   // Print Information
   public void printEmp(){
      System.out.println("Name : " + name );
      System.out.println("salary : " + salary);
   }
 
   public static void main(String[] args){
      Employee empOne = new Employee("RUNOOB");
      empOne.setSalary(1000.0);
      empOne.printEmp();
   }
}

The above example compiles and runs as follows:

$ javac Employee.java 
$ java Employee
 Name : RUNOOB
 salary : 1000.0

Class variable (static variable)

  • Class variables, also known as static variables, are declared in the class with the static keyword but must be outside the method.
  • No matter how many objects a class creates, it only has a copy of the class variables.
  • Static variables are rarely used except when they are declared as constants. Static variables are variables of type public/private, final, and static. Static variables cannot be changed after initialization.
  • Static variables are stored in static storage. Often declared as constants, variables are rarely declared using static alone.
  • Static variables are created the first time they are accessed and destroyed at the end of the program.
  • Similar visibility to the instance variable. However, for the sake of being visible to users of classes, most static variables are declared of type public.
  • Default values are similar to instance variables. The default values are 0 for numeric variables, false for Boolean variables, and null for reference types. The value of a variable can be specified either when declared or in a construction method. In addition, static variables can be initialized in static statement blocks.
  • Static variables can be accessed by: ClassName.VariableName.
  • When class variables are declared as public static final, uppercase letters are generally recommended for class variable names. If static variables are not of type public and final, they are named in the same way as instance variables and local variables.

Example:

//Employee.java file code:
import java.io.*;
 
public class Employee {
    //salary is a static private variable
    private static double salary;
    // DEPARTMENT is a constant
    public static final String DEPARTMENT = "Developer";
    public static void main(String[] args){
    salary = 10000;
        System.out.println(DEPARTMENT+"average wage:"+salary);
    }
}

The above example compiles and runs as follows:

Average developer salary:10000.0

Posted by lill77 on Sat, 04 Dec 2021 10:08:46 -0800