Variable Concept Simplified in Java



Variables are user defined tokens or identifier in java programming that denotes a storage location used to store data value.When a constant remains unchanged during the execution,a variable can take different values. When a variable declaration is executed,memory is allocated for the variable.Also these memory needs to contain some definite value before the variable can be used as an expression.In java there are five types of variables available for usage.They follow the Access Specification. Details of Access Specification is given here.The area of the program where the variable is accessible is called its scope.
A variable name can be chosen by the coder in a meaningful way so that it can reflect what it represents in the program.
What happens when we define the variable:
  1. It tells the compiler what is the variable name.
  2. It specifies what type of data the variable will hold.
  3. It also defines the scope of the variable.
  4. It also tells the compiler how much memory it has to reserve to operate on this variable.
The general rule to define a variable as follows:
  1. It may consist of alphabets,digits ,underscore and dollar.
  2. They can not begin with a digit.
  3. Uppercase and lowercase are distinct so Age,age and AGE are there different variables.
  4. It should not be a reserved keyword.
  5. White space inside a variable name is not allowed.
  6. Variable length can be of any length but we need to choose one which is lengthy as elaborate the purpose and short to read and understand.
General form of the variable declaration:

type variableName// for single variable
type variableName1,variableName2,variableName3...variableNameN //for multiple variables
 
Assignment of a variable:
A variable must be given a value after it has been declared and before it is used in an execution. This can be done in following ways:

  1. By using assignment expression (assign values during decleration) like int a=2;or int x=y=z=3;
  2. By using a read statement
  3. By dividing the expression in two parts like int a;a=2 ;
Scope of a variable:

The concept of the lifetime of a variable occupies a significant portion of the programming effort. The question are..
  • How long the variable lasts?
  • When  shall we destroy the variables?
confusion over the lifetime of the variable can lead to many defects.However, in this paragraph, I tried to explain very basic rules of the scope of a variable.
Scope determines both the visibility and lifetime of the variables defined within the scope.In java scope is determined by the curly braces {}

//first block
{
int x=0;
int y=0;
//x,y are available
  {
//second block 
   int m=0;
   int n=0;
//x,y,m,n are available
  }
//only x,y are avaialble
  {
//third block
   int p=0;
   int q=0;
//x,y,p,q are available
  }
}
//x,y are out of scope
 
A variable defined within the scope is available only to the end of that scope.Java being a free form language , the extra spaces,tabs and carriage return do not affect results of the code.

Classification of the variables:

The classification of Variable is as follows:
  1. Instance Variable
  2. Class Variable
  3. Local variables
  4. Parameters

Instance Variable: 
Instance variables are data elements or object references that can change it's value.An object variable is called fields in java.These variables are declared at the beginning of the class definition.Instance variables are mostly private in nature and non static. Objects store their individual state in the Instance variable,so their values are unique to the object.Instance variables must be declared before they are used.Instance variables are created when objects are instantiated and they are associated with the object. 
Instance variables are initialized in the following 4 ways:

  • Instance variables can be declared and initialized in the same statement.
Like:

private String firstName="abc";
//or
private String firstName; //declare the variable and allocate some memory space for it.
firstName="abc"; //initial value is assigned
 
it can also be an expression too.And it is legal to initialize several variables in one declaration statement.

int x,y=1;
int n=3,m=n+1;
//this feature is common in loop too
int i=5;
for(i=5;i<10;i++){}
  • In practice, Instance variables are often  initialized by a constructor call.

Class MyClass{
private String firstName;
public MyClass()
{
this.firstName="abc";
}
public MyClass(String firstName)
{
this.firstName=firstName;
}
}
 
  • There is also a third possibility to use a separate public method to initialize them:

Class MyClass{
private String firstName;
public void setFirstName(String firstName)
{
this.firstName=firstName;
}
}
 
  • Also if it a public member then creating an instance of the class and instance.variable_name

We use instance variable when we want the fields in an object to have unique value.This is as per Object specification.The set of values of an object's instance variable is known as it's state. Thus Instance variables can be initialized and subsequently modified so that the state of the object can be same or different from other objects of the same class.

Class MyClass{
public String firstName;
}
public class MyTestClass{
public static void main(String args[])
{
MyClass mc=new MyClass();
mc.firstName="abc";
}
 
Class Variable/static variables:
A class variable is created as soon as the class is loaded by java interpreter.Initialization is also done at the same time.If we want the value of a field to be shared that is same for all instance of the class,In that case, those variables are called Class Variables.In this case the variable is specific to the class and not to instance of the class.If a class variable is changed the value,the updated value will be reflected across all instances.Class variable known as static fields. Only one copy of the variable across instances irrespective of how many instances we create for the class.Only one memory location is allocated for class variables.Class variables can be accessed out side of the class by providing <ClassName>.<VariableName>.In case class variables are not initialized, the java will always initialize the variable based on the type. The default for numeric type is zero. Boolean is false,char is Unicode zero and Objects are null. These kind of variable exists independently irrespective of the method and can be accessed in other part of the code.So the scope of this variable is the entire class where it is defined..

public class Student{
private static int rollNumber=0;
public void addStudent(String firstName)
{
Student s=new Student(firstName,getRollNumber());
}
private int getRollNumber()
{
return rollNumber++;
}
}
 
In case of a member variable,it is not simply an abbreviation for a declaration followed by an assignment statement.Declaration statements are only type of statement that can occur outside of the method or function. However the assignment statement has to be part of the method.

public class Student{
static int rollNumber;
rollNumber=01104;//Illegal can not outside of a method or a function.
}
This is because declaration of member variables often include initial value.If no initial value is given,java provides a default initial value.
 
Local Variable:
A variable that is declared inside a body of a method is called local variable.The scope of the variable is inside execution window of the method only. That is when the execution of the method completes its execution,all local variables are destroyed.They become out of scope.Local variables are only visible to the method in which they are declared.They are not accessible from other members of the class.Local variables must be initialized by code developer.

Class MyClass{
private String firstName;
public void setFirstName(String firstName)
{
//This is a local variable
private String firstName;
private String CollName;
//private String CollName="BCREC"
this.firstName=firstName+collName;
}
}
 
However this method won't compile as variable colName is not initialized.Once we provide the initialize value it will work.
Local variables can also be declared inside program blocks that are defined between an opening and closing bracket.{}.We can have nested blocks (a block inside another block) in the code.

//first block
{
int x=0;
int y=0;
  {
//second block
   int m=0;
   int n=0;
  }
  {
//third block
   int p=0;
   int q=0;
  }
}
 
The rule for nested block variable as follows:

  1. Variable is the upper block like x can be accessed from child block.
  2. We can not re declare any of the variable in other blocks.
  3. The scope of the variable is inside a block.They are not accessible from any other blocks.  
It is legal to have a local variable or a formal parameter that has the same name as member variable.In that case,within the scope of the local variables or parameter,the member variable is hidden.

public class MyClass{
static int count;//member variable
static void MyClass()
{
int count; 
....
//it is perfectly fine to declare a local variable with the same name as member variable.member variables are hidden if a local variable of the same name is found.However the the scope is the method.
....
}
//Member variable is visible here.
}
 
It is also possible to declare a loop control variable like:

for(int i=0;i<10;i++){}
 
In that case the scope of such deceleration is considered as a special case.It is valid within the bracket{}.And it does not extend to the remaining code block that contains the for block.
it is not legal to redefine the same name of the formal parameter or local variable within its scope even inside the nested block.

void divide(int x)
{
int y;
while(x>0)
{
int y;
//Error as y is already defined
}
} 
however the below is perfectly legal as the scope for y is ended with the while loop block.


void divide(int x)
{

while(x>0)
{
int y;
-----
-----
}
int y;
} 

Parameters:
Parameters in a method body definition are called formal parameter or dummy parameters.The parameters that are passed to a subroutine or function is called actual parameter or arguments.
Parameters variables are given to a constructors,methods,try catch blocks. The argument passed to the method(including constructor) when invoked,matches the parameter list in its declaration.If match is found it will execute that method otherwise the compiler throws an error.Parameters can not be explicitly initialized in the declaration of the method or in a constructor as they are implicitly initialized to the arguments passed to the method or constructor when it is called.

Class MyClass{
private String firstName;
//parameter is passed
public void setFirstName(String firstName)
{
//This is a local variable
private String firstName;
private String CollName;
//private String CollName="BCREC"
this.firstName=firstName+collName;
}
}
 
local variable names can hide under method names.There is no rule that variables and subroutines have different names.Java can always understand the difference between variable ans subroutine.As the subroutine name is always followed by a left parenthesis(() .It is perfectly ok to have variable name and subroutine name same in a class.

void name(String fName){
name=fName;
}
Variable Concept Simplified in Java Variable Concept Simplified in Java Reviewed by Animesh Chatterjee on October 03, 2018 Rating: 5

No comments:

Powered by Blogger.