Java – Variable Types

All the source code can be checkout here

A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable’s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

You must declare all variables before they can be used. Following is the basic form of a variable declaration −

datatype variable [ = value][, variable [ = value] ...] ;

Here data type is one of Java’s datatypes and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list.

The Java programming language defines the following kinds of variables:

  • Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in “non-static fields”, that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.
  • Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change.
  • Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

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

  • Local variables
  • Instance variables
  • Class/Static variables

Local Variables

  • Local variables are declared in methods, constructors, or blocks.
  • Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
  • Access modifiers cannot be used for local variables.
  • Local variables are visible only within the declared method, constructor, or block.
  • Local variables are implemented at stack level internally.
  • There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.

Example

following example shows you how to define local variable:

package variable.localVariable;

public class DefineVariable {
    //variable defined in constructor
    public DefineVariable() {
        //variable define and initialized
        int demo1 = 123;
        //variable define without initialized but will cause a problem
        int demo3;
    }

    //variable defined in block
    {
        float demo2 = 234.3f;
    }

    //variable defined in method
    public void variableInMethod() {
        int a, b, c;         // Declares three ints, a, b, and c.
        int a1 = 10, b1 = 10;  // Example of initialization
        byte B = 22;         // initializes a byte type variable B.
        double pi = 3.14159; // declares and assigns a value of PI.
        char a2 = 'a';        // the char variable a iis initialized with value 'a'
    }


    public static void main(String[] args) {

    }
}

Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this method.

package variable.local;

public class LocalVariable {
    public void pupAge() {
        //must give age an initial value before first time use
        int age = 0;
        age = age + 7;
        System.out.println("Puppy age is : " + age);
    }

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

This will produce the following result −

Output

Puppy age is: 7

Example

Following example uses age without initializing it, so it would give an error at the time of compilation.

package variable.local;

public class LocalVariable {
    public void pupAge() {
        //must give age an initial value before first time use
        int age;
        age = age + 7;
        System.out.println("Puppy age is : " + age);
    }

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

This will produce the following error while compiling it −

Output

Error:(7, 15) java: variable age might not have been initialized

Instance Variables

  • Instance variables are declared in a class, but outside a method, constructor or any block.
  • When a space is allocated for an object in the heap, a slot for each instance variable value is created.
  • Instance variables are created when an object is created with the use of the keyword ‘new’ and destroyed when the object is destroyed.
  • Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object’s state that must be present throughout the class.
  • Instance variables can be declared in class level before or after use.
  • Access modifiers can be given for instance variables.
  • The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers.
  • Instance variables have default values. 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.
  • Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName.

Example

Click here to checkout the source Code.

/*
* get more info from www.andrew-deng.com
**/
package variable.instance;
public class Student {

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

    // age  variable is visible in Student class only.
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }


    public static void main(String args[]) {
        Student john = new Student("John", 6);
        Student dave = new Student("Dave", 7);
        Student juli = new Student("juli", 5);

        System.out.println("john name=" + john.name + " john age=" + john.age);
        System.out.println("dave name=" + dave.name + " dave age=" + dave.age);
        System.out.println("juli name=" + juli.name + " juli age=" + juli.age);


    }
}

This will produce the following result −

Output

john name=John john age=6
dave name=Dave dave age=7
juli name=juli juli age=5

Class/Static Variables

  • Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
  • There would only be 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 other than declared final and 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 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 with 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.

each dog instance has its own instance variables but only they all share the same static variable “breed”

Example

package variable.staticVariable;

public class Dog {

    // breed  variable is a private static variable
    private static String breed = "Blackback";
    private String name;

    public Dog(String name) {
        this.name = name;
    }


    public static void main(String args[]) {
        Dog fido = new Dog("Fido");
        Dog rover = new Dog("Rover");
        Dog spot = new Dog("Spot");

        System.out.println(fido.breed);
        System.out.println(rover.breed);
        System.out.println(spot.breed);
    }
}

This will produce the following result −

Output

Blackback
Blackback
Blackback

Change the static variable

if we change the static variable all the instance breed will be changed.

package variable.staticVariable;

public class Dog {

    // breed  variable is a private static variable
    private static String breed = "Blackback";
    private String name;

    public Dog(String name) {
        this.name = name;
    }


    public static void main(String args[]) {
        Dog fido = new Dog("Fido");
        Dog rover = new Dog("Rover");
        Dog spot = new Dog("Spot");

        System.out.println(fido.breed);
        System.out.println(rover.breed);
        System.out.println(spot.breed);

        //here we change the breed to Mutt which would change all the instance breed value
        System.out.println("Dog breed change to Mutt");
        Dog.breed = "Mutt";
        System.out.println(fido.breed);
        System.out.println(rover.breed);
        System.out.println(spot.breed);
    }
}

This will produce the following result −

Output

Blackback
Blackback
Blackback
Dog breed change to Mutt
Mutt
Mutt
Mutt

What is Next?

You already have used access modifiers (public & private) in this chapter. The next chapter will explain Access Modifiers and Non-Access Modifiers in detail.

Leave a Reply

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