Introduction to Java Variables

Introduction to Java Variables

1 Comment

Last Updated on June 16, 2019 by Simanta

Introduction to Java Variables

A variable in Java is the name of a memory location. This memory location is used by the Java programs for carrying out the various tasks and calculations. Whenever a Java program is run, some input may be provided to it, or some data might be required to be saved temporarily for usage at a later stage. This is where Java variables come into the picture. Java variables provide Java programs with the storage space for temporarily storing these values.

Primitive Data Types and Java Variables

Since Java is a strongly typed language, every variable in Java is declared using a particular data type. This data type determines the size and layout of the memory which is allocated to the variable by the Java Virtual Machine (JVM). The data type also specifies what kind of values can be stored in that memory location. The data type also defines the set of operations which can be performed on that variable.

There are eight primitive data types in Java programming language. These are int, float, char, double, boolean, byte, short and long. All the other data types are derived from these primitive data types.

Primitives are a special case in Java. Primitives are not considered objects. Thus many argue, Java is not a pure Object Oriented Language. Alternative JVM languages such as Groovy autobox primitives. Meaning even if you do declare a primitive type, it will automatically be treated as the corresponding object type (ie int types become Integers automatically).

The default values and default sizes of all eight primitive data types are given below,

Data TypeDefault ValueDefault Size
booleanfalse1 bit
char‘\u0000’2 byte
byte01 byte
short02 byte
int04 byte
long0L8 byte
float0.0f4 byte
double0.0d8 byte

Declaration of Java Variables

The declaration of a Java variable is a must before that variable can be used in the program. If the variable is used in a program without proper declaration, then the program will throw an error.

A variable can be declared as given below,

data_type variableName = [value];

‘data_type’ gives the data type of the variable being declared, ‘variableName’ is the name of the variable and ‘value’ is the initial value being assigned to that variable. The data type being used for the declaration of the variable can be either a primitive data type or a derived data type.

Reference Variables

If the variable is not a primitive data type in Java, then it is an Object. In this case, the variable becomes a reference pointer to the memory space for the object.

The reference returned by a newly created object must be assigned to a variable and that variable is known as a reference variable. The syntax for declaring a reference is given below,

Class var = new Class();

Here ‘var’ is a reference variable. Here a new object of the class ‘Class’ is created and its reference is stored in ‘var’.

Java Variable Scopes

There are three basic types of variable scopes in Java: local, instance and static. These three differ in terms of the position of their declaration inside a Java program, the access modifiers used with each, and the way they are declared.

Local Variables

A local variable is simply a storage space where a method stores its temporary state. During the execution of a program, a local variable is created when a method is entered and it is destroyed as soon as the method is left. So the local variables are visible only inside the method in which they are declared and they play no role in the rest of the program.

Local variables cannot be accessed outside of the declaring method. Internally, the local variables are implemented at stack level. One of the most important points about the local variables is that they have no default value. Local variables must be initialized before using them for the first time. Consider this example:

public class Sample {
    public void sampleValue () {

        int value = 0;

        value = value + 5;

        System.out.println("The value is:" + value);
    }

    public static void main (String args[]) {

        Sample sample = new Sample();

        sample.sampleValue();
    }
}

In this example, ‘value’ is a local variable. This variable is declared inside the method ‘sampleValue’ and this variable’s scope is limited to this method only. The output of the above code snippet would be,

The value is: 5

The important things to notice here are that the local variable has been declared inside a method, no access modifier has been used for the local variable and also the local variable has been initialized with the value ‘0’. The data type for the local variable in this example is ‘integer’.

If instead of the above code, we had used the code given below,

public class Sample {

    public void sampleValue () {

        int value;

        value = value + 5;

        System.out.println("The value is:" + value);
    }

    public static void main (String args[]) {

        Sample sample = new Sample();

        sample.sampleValue();
    }
}

The Java compiler will not allow you to compile this class. The compiler output would have been the following error,

The variable number might not have been initialized.

Instance Variables

The variables used for representing the state of an object/attribute of a class are called instance variables. The instance variables are the ones which are declared inside a class, but outside the method or the constructor or the block. When an object of the class in which the instance variable has been declared is created, space is allocated for that object in the heap, and a slot for each instance variable value of that class is created in that space. The instance variables are created when a new object of a class is created using the ‘new’ keyword and are destroyed when the object is destroyed. The values which are held by the instance variables are commonly accessed by more than one method during the course of a program.

Access modifiers can be used along with instance variables. The access modifiers define the visibility of the instance variables in the subclasses of the class. Otherwise, the instance variables are visible to all the methods in a particular class by default. The instance variables have default initial values and hence it is not mandatory to initialize them.

Let us take an example to better understand these concepts,

public class Student {

    protected String name;
    private double rollNo;

    public Student (String studentName){
        name = studentName;
    }

    public void setRollNo(double rollNumber){
        rollNo = rollNumber;
    }

    public void printStudent(){
        System.out.println("Name:" + name);
        System.out.println("Roll Number:" + rollNo);
    }

    public static void main(String args[]){
        Student newStudentOne = new Student("Spring Framework Guru");
        newStudentOne.setRollNo(1234);
        newStudentOne.printStudent();
    }
}

As has been shown in the above example, the instance variables can be called anywhere in the class just by using the variable name. The instance variables in this example have not been initialized before using them for the first time and they are being created when the object of the class ‘Student’ is getting created by using the keyword ‘new’. Only after the creation of object and the subsequent creation of instance variables, have the values been assigned. Also for ‘name’, ‘protected’ access modifier has been used which means that this variable will be accessible to all the subclasses of ‘Student’ class. But for ‘rollNo’, ‘private’ access modifier has been used. So this variable will not be directly accessible by the subclasses of the ‘Student’ class.

Static Variables

Static variables are the ones which are declared with the ‘Static’ access modifier. These are also declared in a class outside the method or the constructor or the block. The major use of the static variables is in the declaration of constants. These are the public/private static final variables. Static final variables cannot change from their initial value. These variables are stored in the static memory and are created when the program starts and are destroyed when the program stops. The default values and visibility inside the class for static variables is same as the instance variables. Static variables are initialized at class load time.

Memory Allocation and Garbage Collection in Java

Memory allocation for Java variables is done dynamically in the heap memory in the Java Virtual Machine. Whenever a new object is created, it’s reference is stored as a variable in the heap. When the same object is no longer in use, it is called a dead object or dereferenced. As a programmer, you can no longer access these objects. The memory occupied by a variable referring to a dead object is no longer needed and it is reclaimed for further reuse by a mechanism in Java called Garbage Collection.

In garbage collection, all the objects which are live are tracked and rest all the objects are declared to be dead. Then the memory being used by the variables for these dead objects is reclaimed for reuse for the creation of new variables. This way, the programmers never have to worry about the allocation and availability of memory for creating new variables in Java.

Naming of Java Variables

Java Variable Naming Conventions

Just like other programming languages, Java also has some rules for the kind of names one can use. So we have to follow certain guidelines when we name our variables. First thing one should remember is that the Java variables are case-sensitive. A variable name can begin with a dollar sign ‘$’, an underscore ‘_’ or with a letter. But as per standard programming conventions, it is best to have your variable name, to begin with a letter. In certain cases an underscore may be used. Technically we can use these signs but it is best to avoid them. Also, blank spaces are not allowed in variable names.

Other than the first character, the rest of the characters can be letters, digits, underscore sign or even the dollar sign. While it is acceptable, you should follow generally accepted programming conventions. You should use full, meaningful words with a camel case (camelCase) convention. This will make your code easier to understand by others.

If the variable is a static variable then the convention to be used should be each letter capital with each word separated by an underscore, something like ‘USER_AGE’. Underscore character should never be used elsewhere.

Java Reserved Words

Oracle has defined a number of keywords which cannot be used as variable names. In programming, these keywords are also often referred to as reserved words. In the table below, you can review the reserved words in Java. You can see that these words are programming constructs.

abstractcontinuefornewswitch
assertdefaultgotopackagesynchronized
booleandoifprivatethis
breakdoubleimplementsprotectedthrow
byteelseimportpublicthrows
enuminstanceofreturntransient
catchextendsintshorttry
charfinalinterfacestaticvoid
classfinallylongstrictfpvolatile
constfloatnativesuperwhile

Conclusion

Java variables are one of the most fundamental parts of the Java programming language. Java primitives are a special case where the variable is the memory space for the value. Everything else in Java is an object, and the variable becomes a pointer to the memory space of the object. Every variable in Java has a life cycle. Memory is allocated when the variable is created. When an object in Java is not longer referenced it becomes available for garbage collection. Remember, the memory used by the variable is not released until garbage collection occurs.

 

About jt

    You May Also Like

    One comment

    1. November 12, 2018 at 9:51 am

      Ps the style’s of tables make them almost impossible to read 🙂

      Reply

    Leave a Reply

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

    This site uses Akismet to reduce spam. Learn how your comment data is processed.