All Courses
Variables in Java

Variables in Java

May 1st, 2019 Java

Variables in Java

Variables are names of the memory locations. It is just like a storage container for holding data. But before assigning any value to the variable, we must specify the type of data that variable is going to hold. There are many types which are called Data Types, which we will discuss as our next topic.

Syntax:

Datatype Variable_name=value;
‘=’ is known as ‘Assignment Operator’ here. An assignment operator fetches the value given in the right of ‘=’ and allot it to the variable which is on the left of ‘=’.

Example:

int number = 10;
Here, ‘int’ is the short form of ‘integer’ data type, ‘number’ is the variable name. It means that the value ‘10’ is assigned(allotted) to the variable ‘number’ which can hold ‘integer’ type of data, which also means 10 is an integer value.

Number Convention for Variable:

  • Variable names can contain alphabets, numbers, underscore and dollar symbol.
  • Variable names can start with lowercase letter or underscore or dollar symbol.
  • Variable names can not contain whitespace.
  • Keywords(Reserved Words) cannot be used as variable names.

There are 3 types of variables :

  • Local Variables.
  • Instance Variables.
  • Static Variables.

Local Variables :

Local Variables are declared inside a method. Therefore, the scope (lifetime) of the variable lies within the curly braces of the method. The variable and its value doesn’t last outside the method. These variables are accessed when the method is called.

Example:

public void display()
{
int number=10;
----
}

Instance Variables :

Instance variables are declared inside a class. Therefore, the scope of the variable lies throughout the class. If the class contains any non-static methods(normal methods), there also the variable has its accessibility. These variables are accessed using objects of the class. For each object of the class separate copies of this variable is maintained.

Example:

class Sample
{
int digit=5;
----
public void sum()
{__ __
}
}

Static Variables :

Static variables are declared within the class with the keyword ‘static’. It means this variable belongs to the class. These static variables can be accessed within static methods. The scope of this variable lies throughout the class. This variable is loaded during runtime. No objects can be used to access it. We may use class name to access static variables. Only one copy of this variable is maintained throughout the class and wherever this class is used.

Example:

class Sample{
int digit=5;
static int id=101;
_ _
}
Social Share:

0 responses on "Variables in Java"

Leave a Message

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