Variable and Access Modifier

What is variable in java?

In simple terms, variables are just containers for storing values. In java, those containers must have names and types to specify what type of values those containers are going to hold. In other words, all variables must have a name and type (java cares about type).

In the above example, this age variable is capable of holding one numeric value.

Variables come in two flavors: primitive and object reference.

Primitive

Primitive types are the basic data types supported by java. Primitive variables store the actual value that has been assigned.

There are 8 primitive data types –

Data Type Description Example
byteThis is for the whole numeric value. It has a minimum value of -2^7(-128) and a maximum value of 2^7-1(127).byte var = 100;
shortThis is for the whole numeric value. It has a minimum value of -2^15 and a maximum value of 2^15-1.short var = 100;
intThis is for the whole numeric value. It has a minimum value of -2^31 and a maximum value of 2^31-1.int var = 100;
longThis is for the whole numeric value. It has a minimum value of -2^63 and a maximum value of 2^63-1.long var = 100;
floatThis is for floating point numbers that can hold a number with its fractional part.float var = 100.01f;
doubleThis is for floating point numbers that can hold a number with its fractional part. Size of a float variable is 64 bits. double can hold a larger value than float.double var = 100.01d;
booleanThe boolean data type has only two possible values: true and false.boolean var = true;
charThe char data type is a single 16-bit Unicode character.char var = ‘A’;

If you try something like below, you will get a compile time error in the second line.

int var = 20;
byte age = var;    ⇐ Compile time error here

You might ask, why is that happening? byte is capable of holding value from -128 to 127. The reason is, essentially you are trying to pour something from a larger container to a smaller container. So there is a possibility that there won’t be enough space in the smaller container to accommodate value from the larger container. Compiler is just trying to eliminate that possibility.

Now the question is, is there any way to achieve this? The answer is yes. You can explicitly ask java to convert int to byte and then assign the value.

int var = 20;
byte age = (byte) var;

As the value of int variable is 20, this is fine. But let’s assume the value is bigger than the byte max value –

int var = 140;
byte age = (byte) var;

Even this will not give any error, but if you print the value of age, you will see -116. Strange right? The reason is, when the value exceeds the max value, the next value starts from min value.

  1. 126 → byte value 126
  2. 127 → byte value 127
  3. 128 → byte value -128
  4. 129 → byte value -127
  5. 130 → byte value -126
  6. 140 → byte value -116
Object Reference

Object reference or reference variable can be used to refer to any object that has been created. It stores the reference of the object they refer to, not the actual object. The actual object resides in the heap memory.

Consider a reference variable like a remote and the actual object like a TV. Using the remote (reference variable) you can operate on TV (actual object).

As you know, primitive variables store the actual value that has been assigned, so if you try something like below, variable a will print 123 and b will print 456.

int a = 123;
int b = a;
b = 456;
System.out.println(a);
System.out.println(b);

Explanation:

  1. First a is assigned with value 123.
  2. Then b is assigned with the same value that a holds (i.e. 123).
  3. When we change the value of b to 456, the value of variable a remains as it is.
  4. So, at the end, the value of a is 123 and value of b is 456.

Now consider a similar scenario with reference variables. Let’s assume we have a Bike class as show below –

public class Bike {
     String color;

     String getColor() {
          return color;
     }

     public void setColor(String color) {
          this.color = color;
     }
}

Now, if you try below, both b1.getColor() and b2.getColor() will print Black.

Bike b1 = new Bike();
b1.setColor("Red");

Bike b2 = b1;
b2.setColor("Black");

System.out.println(b1.getColor());
System.out.println(b2.getColor());

Explanation:

  1. First a new Bike object is created in heap and the reference variable b1 holds the reference of that object.
  2. Using this reference variable we set the object color to Red in heap memory.
  3. When we assign reference variable b1 to b2, the actual object doesn’t get assigned to b2, only the reference of that object is assigned. So, there will be only one Bike object in the heap, both b1 and b2 will refer to the same object.
  4. Then when we change the color to Black using the reference variable b2 (or b1), the actual heap object is updated with color Black.
  5. Now if we try to print the color of the object using b1 or b2, as both are referring to the same object in the heap, both will print Black.
How to name a variable

There are couple of simple rules –

  1. It must start with a letter, underscore(_), or dollar sign ($). You can’t start a name with a number.
  2. After the first character, you can use numbers as well.
  3. The variable name can be anything you like, as long as it isn’t Java’s reserved keywords.
Types of variables

Variables can be categorized in three types –

Local Variables: Local variable is declared inside the body of a method. You can use this variable only within that method and the other methods in the class aren’t even aware that the variable exists.

public class Bike {
    public void start() {
        int speed = 10; ⇐ speed is local variable
    }
}

Instance variable: This is declared inside the class but outside the body of any method. It is not declared as static. Instance variables are not shared among different instances of a class.

public class Bike {
    String color= "red";  ⇐ color is instance variable
}

Static variable: This is declared inside the class but outside the body of any method. It is declared as static. Static variables are shared among different instances of a class.

public class Bike {
    static String model = "Hero XX";   ⇐ model is static variable
}

Instance variables always get a default value. If you don’t explicitly assign a value to an instance variable, the instance variable will be assigned with a default value.

  • For integers, the default value is ⇒ 0
  • For floating points, the default value is ⇒ 0.0
  • For boolean, the default value is ⇒ false
  • For references, the default value is ⇒ null

Local variables do not get a default value like instance variables and must be initialized before use. 

Arrays

An array is a container that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed and cannot be changed. Each item in an array is called an element, and each element is accessed by its numerical index. The index starts from 0. Let’s check below example –

public class Bike {
    public static void main(String[] args) {
        int[] intArray = new int[4];
        intArray[0] = 100;
        intArray[1] = 200;
        intArray[2] = 300;
        intArray[3] = 400;
        System.out.println(intArray[2]); ⇐ get third element
    }
}

Output : 300
Access Modifiers

The access modifiers in Java specify the access level of fields, constructors, methods, and class by applying the access modifier on it. There are four types of access modifiers – public, private, protected and default (when no access modifier is specified).

Based on access modifiers, a method or instance variable etc. may only be accessible within the same class or from subclass etc. Below table will summarize the access level based on the access modifiers used.

Visibilitydefaultpublicprotectedprivate
Same classYesYesYesYes
Non subclass in same packageYesYesYesNo
Subclass in same packageYesYesYesNo
Subclass in different packageNoYesYesNo
Non subclass in different packageNoYesNoNo

We will discuss about package later.