Variables in Java

Spread the love

Variables in Java:

Variables in Java 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(including an instance). So variables are place holder and changes its value over time.Variables are pointers to an object.Simply declaring a variable does not create storage for the variable.This post also talks about variables in java rules.

Value is the thing that is stored in a variable.Value should be of type variable. 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.

Variables in Java name can be chosen by the coder in a meaningful way so that it can reflect what it represents in the program.In an assignment statement,the thing is being assigned always on the left side of the equal(=) sign and the value is right side.

Computer can only understand binary(0/1)So we need to convey the computer what is the meaning of sequence of binary. This gives the concept of type. A type of a variable is the range of values that the variable is capable to store.

The name space rules applies to packages,classes and members within classes.

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.
  1. White space inside a variable name is not allowed.
  2. 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

Variables in Java 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.If we have variable of same type we can use same line to declare them.


int age,rollNumber,noOfPens;
 

If we have variable of different types we need to declare separately.


int age,rollNumber;
float salary;
 

we can give variables their starting values during declaration:


int age=10;
float Salary=1000.43;
 

Variables can be initialized once at starting but can be assigned many times.
 

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 also a variables in Java 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:variables in java example


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. variables in java example

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:variables in java example

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.

variables in java example


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:

The subsequent paragraphs talks about class or instance variables in java rules.
A class variable also a variables in Java 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..
class variables in java example


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.

class variables in java example


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:

The below paragraphs talks about Local variables in java rules

A Variables in Java 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.

Local variables do not have globally unique hierarchical names. They do not have access modifiers like public and private. They are different from class variables.

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.

local variables in java example


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.

local variables in java example


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.

local variables in java example


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:

The below paragraphs talks about the parameter variables in java rules.

Parameters in a method body definition are called formal parameter or dummy parameters.They are also Variables in Java.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;
}

Difference Between Local Variable And Instance Variable in Java?

As we go deep into java the question arises is what is the difference between local variable and instance variable? In this post I am trying to explain the difference between them.


In my last post here I have shown different types of variables. In this post we will check what is the main difference between Instance and Local variable.

Instance Variables

Variables in Java or Instance variables are declared inside a class but not inside a method.Lets see in details about instance variables in java rules


class MyClass{
int rollNumber;//instance variable
}

Local Variables

Variables in Java or Local variables are declared inside a method including method arguments.lets see more about the local variables in java rules


public void sum(int a,int b)
{
int x;
x=a+b;//x,a,b are local variable
}

Internal structure and work done by java

When java sees a method with arguments and local variables, It creates a stack. A frame will be created from the method. In the same stack,a variable or variables are placed.


public void sum(int a,int b)
{
int x;
x=a+b;//x,a,b are local variable
}

for this code the stack will look like-

StackHeapComments
sum,x,a,bNo heap entryCreates a frame in the stack having the method name

Now if the method sum ,calling another method display(), then one more entry will be created on top of sum().
Code:


public void sum(int a,int b)
{
int x;
x=a+b;//x,a,b are local variable
display(x);
}
public void display(int i)
{
Account f=new Account();
f.add(i);
}

Account class structure:


class Account{
int a,b;
}

The stack and heap view will be:

StackHeapComments
display,xf(Account)
a=0
b=0
Since f is an instance of Account class, the object will go to heap.a and b
being Instance variable will go to heap and gets initialized to zero.
Account() the constructor will create a block in the heap and provides name as reference.
sum,x,a,bNo heap entryCreates a frame in the stack having the method name

The assignment ‘=’ will make a reference variable point to the object in heap.During execution once the display() method is completed,display is flushed from the stack.Then the sum() will be executed. Once that is over the stack is flushed again.All the variables are vanished for the respective methods once the stack is flashed. This is how the scope is defined. Once the display() is over, there is no active reference variable pointing to heap’s reference variable or block.The block is eligible for garbage collection.



Local VariableInstance Variable
Local variable will not get any value bydefaultDepending on the data type Instance variable will get default value.Like-bollean will get false
int will get 0 etc
The scope of local variable is very limited ..only inside the block (function)The scope is global
It is mandate to initialize the local variable to performa any actionAs by default it will get some value hence it is not mandate to initialize any value to the variable.
Mostly we will get compile time error if something goes wrong with Local variableMostly we will get run time error if something goes wrong with Instance variable



What happens when one object is calling another object


class MyClass{
public static void main(String args[]){
A parent=new A();
}
class A{
B child=new B();
int e;
}
class B{
int c;
int d;
}
 

The equivalent structure will be:

StackPoints toHeapPoints toHeap
parent—->child—->c=0
d=0
maine=0

So we can say in the heap, there is a stack created for the objects and variables.

Points to remember:

  • When a method is called a frame is created on the top of the stack.
  • Once execution is completed for a method,the control returns to the calling method.The corresponding stack is flushed.
  • Local variables are created inside the stack. They are vanished once the stack is flushed.
  • Instance variables are created in a Heap and they are part of the object they belong to.
  • Reference variables are created in the stack.

 

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.


Spread the love
  •  
    1
    Share
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a Comment

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

Scroll to Top