Variables in Java

 After learning about Java JDK installation process and selecting our IDE for Java, Lets begin our journey for becoming a proficient Java Developer. In this Tutorial, We'll explore the most Fundamental concept of Java Programming, Variables. The most necessary basic Concept in every Programming Language.

What are Variables?

Variables are actually containers or blocks which hold a specific value assigned to them, during the execution of the Program. They hold the value until the program is terminated or until it has done all its work and printed the output. That's why, they are known as the basic unit of storage in a program. A variable is actually a name of the memory location, where we store the value.

Whenever a variable is declared, it is given a unique name in the computer memory, this unique name is known as an Identifier, They are assigned the memory address of the variable,where the original value is stored. 

Identifiers

These are a descriptive sequence of uppercase/lowercase letters, numbers or the underscore or $ dollar sign. Since Java is case-sensitive, so Hello is different from hello.
Some examples of valid identifiers are:
currentDate    counter    next_month    $dummy    avg_of_2
Invalid identifiers are like:
3digits    hi&there    COVID-19

Literals

A constant value in Java is created by using literal representation of it.
Examples:
12    1.232    'A'    "ProgrammerStudios"
where, 12 - integer literal , 1.232 - float literal , 'A' - character literal and "ProgrammerStudios" is a String literal

Declaring Variables

In Java, each variable has a specific Data Type, which helps in determining the size and properties of the variable declared. The syntax for declaring a variable is as follows:

data_type variable_name = value ; 

This is an optional case, we can even initialise the value later on, depending upon our need. But a variable should must be declared before using it. Also we can change the value that we assigned to the variable during the execution of the program. 

Some of the most used Data-Types in Java are:
  1. int - stores Integer values without decimals
  2. char - stores characters in the form 'a', 'A', '+', '/' etc.(These single qoutes are necessory while initialising a char variable)
  3. float - stores floating point numbers with decimals
  4. double - they also store floating point numbers as float Data-type, but double has a larger Range than floats.
  5. String - stores text strings within double qoutes like "ProgrammerStudios", "Hello" etc.
  6. boolean - stores states - true or false
Examples:

int num = 1 ;    // where int is the data_type and num is the variable_name.
char ch = 'A' ;
float f = 12.3 ;
double d = 1323.232325 ;
String s = "ProgrammerStudios" ;
boolean b = true ;

* You might have noticed this is same as the syntax, we used in C programming while declaring variables. Actually this is the general convention for declaring variables in most of the programming languages.
Whenever a variable is declared it occupies some memory in Stack, it is similar to the Stack concept in Data-Structure, but here it is type of memory used in Java, which follows same rules known as Stack memory.

Naming Convention for Variables

  • In Java, Variable names are case-sensitive, this means they can be any legal identifier having sequence of Unicode letters/numbers or special characters like underscore(_), or Dollar sign($), But it cannot have any special character other than $ and _(underscore), not even white spaces are allowed.
  • Variable name can begin with any letter/digit or underscore/dollar sign but it is a bad practice to start the name with _ or $, avoid using these as the first character of the variable name.
  • The variable name should not be a keyword or reserved word.
  • By convention, the variable name should be a single word, in all small letters, but if more than one word is used in variable name, then Capitalize the first letter of the second word. For example: carSpeed, currentGear, gearRatio etc. This is the most widely used convention while naming variables, this is known as Camel-Case convention.

Types of Variables in Java

In Java, variables are of 3 types:
  • Local variable
  • Instance variable
  • Static variable

Local Variable

Local variables are declared in the body of the method of a class. They are not accessible outside the class, which means if there is another class in our program,then we cannot access these variables there or change their values. They have a limited scope. Also we cannot define local variables using static keyword. Local variables are stored in Stack memory.
Example: 

class main
{
public static void main(String[] args)
{
int i;     // i is a local variable
i=5;
System.out.println(i);
}
}

OUTPUT

5

* System.out.println() is the method used to print something in Java.

Instance Variable

It is a variable which is declared inside the class but outside the body of the method/function. These are actually Non-static fields. The Instance variables are stored in Heap Memory. These are known as Instance variables because, they have a capability of making copies of themselves when assigned for different objects of the same class. They have a default value of 0.

Consider we have a class named number, there a method named printNumber(), outside this method and inside the class number, we declare an instance variable int num = 10 , now inside the method if we create 2 objects(ob1, ob2) of the class number, then on altering the variable using any object( like ob1.num=43 or ob2.num=11), if we print the variables, then only the object in which we did the alteration would print the altered value, while other will display the same value 10.

class number{
int num = 10;   // num is an instance variable
void printNumber()
{
number ob1 = new Number();
number ob2 = new Number();
ob1.num = 30;
System.out.println(ob1.num);
System.out.println(ob2.num);
}
}

OUTPUT

30
10

number ob1 = new Number(); , this is way of creating a class object inside a method. The keyword new allocated the memory for the object to be created.
ob1.num; , We use the period(.) operator, to access the variables through class objects. thatswhy it is written ob1.num, which means we are accessing the num variable through object ob1.

Static Variable

A variable which is common to all the objects or instances of the class, is known as a Static variable. These are also called Class variables. Static variables are declared with the keyword static, inside the class and outside the method of the class. Memory allocation for static variables happens only once, when the class is loaded in the memory or when the execution of the program starts and these are destroyed automatically at the end of the execution of the program.

Static variables have a default value of 0 and for booleans, the default value is false. These are stored in static memory. These are also accessed like the way we access instance variables by using class objects.
Example:

class number{
static int num = 10;        //static variable
void printNumber()
{
number ob1 = new Number();
number ob2 = new Number();
ob1.num = 30;
System.out.println(ob1.num);
System.out.println(ob2.num);
}
}

OUTPUT

30 
30

Here due to the variable num being static, the same copy is shared amongst the objects of the class, any change in one object variable would be reflected in other objects also. Thatswhy the result is 30 for both cases.

final Keyword

In Java, final keyword is used to denote a constant. When we declare a variable as final, then the value initialised to it, acts as a constant value, which means we cannot change that value, by any means. If we tried to change it, the compiler will give us an error.
Example :

class Main
{
  public static void main(String[] args)
  {
    final double PI = 3.14;
    PI = 0;
    System.out.println(PI);
  }
}

OUTPUT

error: cannot assign a value to final variable PI


Ritish

Just a novice blogger

1 Comments

  1. Nice explanation on variables in java. Thanks for sharing.

    https://www.flowerbrackets.com/variables-in-java/
    https://www.flowerbrackets.com/static-keyword-in-java/

    ReplyDelete
Post a Comment
Previous Post Next Post