digitization, transformation, binary

Variables in Java

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 change 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.The value should be of the type variable. When a variable declaration is executed, memory is allocated for the variable.Also, this 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 the right side.

The computer can only understand binary(0/1)So we need to convey the computer what is the meaning of a 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 namespace rules apply 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.

The general form of the variable declaration:


type variableName// for single variable
type variableName1,variableName2,variableName3...variableNameN //for multiple variables
 

Where Does Java Store Variables and Objects? Or Where Storage lives?

The java storage is divided into the below parts:

  • Register
  • The stack-RAM
  • The heap-RAM
  • Static Storage
  • Constant Storage
  • Non-RAM storage

Register:

The register is the fastest of all storage(inside processor). Mainly registers are limited so are allocated based on the need of compiler.Users have no direct access or control over these memory devices.The only compiler can use them as needed.

The stack-RAM:

This is the general RAM(Random Access Memory) area and acts as a bridge between compiler and users. User can allocate and access space in the Stack-RAM area. There is a stack pointer to allocate or deallocate the storage. The stack pointer is moved down to create a new memory and moved up to release the memory.It is slower and cheaper than register but a cost-effective and faster way to allocate or deallocate memory.As the java compiler must know while it is creating the program, the exact size and lifetime of all the data that is stored on the stack because it must allocate or deallocate accordingly, it puts a constraint as the limit of flexibility.All variables, methods, local variables are stored here.

The heap-RAM:

It is a pool of memory(in RAM area) where all Java objects live.Unlike the stack, the compiler does not need to know how much storage, it needs to allocate from the heap or how long the storage must stay on the heap.Thus there is flexibility in using storage on the heap. Whenever we need to create an object we write using new but takes sometimes to allocate heap storage. It is slower than the stack.

Static Storage:

Static storage refers to a fixed location of RAM.Static storage contains data that is available for the entire time of the program execution.Some certain elements of objects are static but java objects are not static.

Constant Storage:

Constant values are often placed directly in the code itself.They are safe as they do not change.Sometimes constants are cordoned off by themselves so they can be optionally placed in a ROM.(Read-Only Memory mainly in Embedded Systems ).

Non RAM storage:

In this case, java data lives completely outside of a program.The data still can exist while the program is not running.They are outside the control of the program.

Example-

Streamed Objects:

Where objects are tuned into streams of bytes. Generally, we use this technique to send to another machine.

Persistent Objects:

Where the objects are placed on the disk. So they will hold the state even when the program is not running.Turning an object into a flat file or something that can exist or some other medium. They can be restructured and restored into regular RAM-based object.

Java provides support for lightweight persistence and mechanism (JDBC, Hibernate etc) to support for storing and retrieving objects.

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 the following ways:

  1. By using assignment expression (assign values during declaration) like int a=2;or int x=y=z=3;
  2. By using a read statement
  3. By dividing the expression into 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 is…

  • 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.

READ  Array Concept Simplified in Java

Scope determines both the visibility and lifetime of the variables defined within the scope.In java, the 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 a variable of the same type we can use the same line to declare them.


int age,rollNumber,noOfPens;
 

If we have a 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 variable in Java are data elements or object references that can change its 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.

The variables when declared as a member of a class (but outside of class method) are referred to as an instance variable. Whenever we create objects of the class these many times the instance variables get copied to the objects.

These variables automatically get initialized to zero. If they are numeric in case they are Boolean, They are initialized to false. In case if they are objects(reference variables), They are initialized to null. We can access these variables using the object name and dot( .) operator.

Objects store their 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 an instance variable when we want the fields in an object to have a unique value. This is as per Object specification. The set of values of an object’s instance variable is known as it states. Thus Instance variables can be initialized and subsequently modified so that the state of the object can be the 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 talk about the class or instance variables in java rules.
A class variable also a variable 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.

These variables are similar to instance variables, but having a static modifier before the data type. Static variables are global variables to a class and its objects. The default value is the same as the instance variable.They can only access static data or static method. We cannot use them in this or super( ) method.

In this case, the variable is specific to the class and not to an 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 outside 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 a numeric type is zero. Boolean is false, char is Unicode zero and Objects are null. This kind of variable exists independently irrespective of the method and can be accessed in another 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 the 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 the local variable. The scope of the variable is inside the execution window of the method only.

If a variable is declared inside a method is known as a local variable. These variables are not auto initialized.

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 initialized 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 the nested block variable as follows:

  1. Variable is the upper block like x can be accessed from child block.
  2. We can not redeclare any of the variables in other blocks.
  3. The scope of the variable is inside a block. They are not accessible from any other blocks.
READ  File Concept Simplified In Java

It is legal to have a local variable or a formal parameter that has the same name as a 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 the 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, 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 constructors, methods, try-catch blocks. The argument passed to the method(including constructor) when invoked, matches the parameter list in its declaration. If a 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 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 and 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 the local variable and instance variable? In this post, I am trying to explain the difference between them.

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. Let us 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. let us 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 are 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-

Stack Heap Comments
sum,x,a,b No heap entry Creates 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:

Stack Heap Comments
display,x f(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 the heap and gets initialized to zero.
Account() the constructor will create a block in the heap and provides name as a reference.
sum,x,a,b No heap entry Creates 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, the display is flushed from the stack. Then the sum() will be executed. Once that is over the stack is flushed again. All the variables have 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 Variable Instance Variable
The local variable will not get any value by default Depending on the data type Instance variable will get the default value. Like-boolean will get false
int will get 0 etc
The scope of the local variable is very limited ..only inside the block (function) The scope is global
It is mandated to initialize the local variable to perform any action As by default it will get some value hence it is not mandated to initialize any value to the variable.
Mostly we will get a compile-time error if something goes wrong with Local variable Mostly we will get run time error if something goes wrong with the 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:

Stack Points to Heap Points to Heap
parent —-> child —-> c=0
d=0
main e=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 the 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 have 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.

How Variable Initialization Takes place in Java ??

 

What is a Variable in Java?

Variables – a piece of memory to store data. It can be divided into two types:

  • Primitive
  • Reference
READ  Vector Class Simplified in Java

Example int x =10. a block of memory which contains data.
Sring str = “abc”; Here String being the class and str being the object or reference variable…
str is going to store the memory address which points to “abc”.

Before building a big building we first create an image or diagram of it. The diagram may have building dimensions, number of doors, windows, size. When we build a build, we follow this diagram. So the diagram may be analogues to class and actual building is analogues to objects.


Class Dog{
String breed;
String color;
//properties /data of the class .
}

Dog obj=New Dog()
//we are creating object of Dog.Obj is a reference variable
// that point to the new object created of type-Dog
//Behavior is represented as method
Void bark ( ) {
System.out.println("vow vow");
}
Void walk ( ) { 
System.out.println("Gentle");

Internal memory Structure

The main memory is divided into two parts.

  • In Heap- All objects are stored.
  • In stack- Local variables and object references are stored.

Variable Scope—Lifetime of the variable.

This keyword-objects are stored in heap. Inside the object, only variables are stored not the methods. The methods are stored separately. There is only one copy of the method which is shared by all the objects. When the objects are created, they will have only variables, not the method.

How the methods are bound to object?

This keyword: every non-static method has this keyword associated with it. If we do not explicitly mention it, the compiler will place one for us, so compiler by default does it.

This will be then replaced by the object reference variable


class test {
int a;
int b;
void m(int v1,intv2){
a= v1//=>this.a= v1;
b=v2//=>this.b= v2;
}
void m2( ){
System.out.Prinln(a);
System.out.Prinln(b);
}
Class TestTheTestClass{
Public static void main (string args[ ] ){
Test obj1= new test();
obj1.mi( 2 , 3 )//While executing this will be replaced by
// the object reference variable So during execution 
//the method will look like
void m1(int v1,int v2){
obj 1.a=v1;
anObj1.b=v2;
}
Test obj2=new test( );
obj2.mi( 3,4);
//that implies
obj2.a=v1 ;
obj2.b=v2

Initialization in Java

Java has implemented two important concepts. They are as follows:

    1. Initialization via constructor
    2. cleanup via Garbage collector and finalize method

If we have a separate method for initialization named initializer() for every class we create. Then we need to explicitly write that method for every class and that needs to be called before we create an object of the class and use. It is then an overhead for the coder. Java has come up with a simple concept called the constructor. If we want to create an object of that class compiler just calls the constructor of the class. If we have a constructor, it is good otherwise the compiler will provide us with a default one and continue to construct an object during the object creation process. This reduces the overhead from developers.

The naming concept:

If we give any name for the constructor, then the name may clash as the same method could be a member of the class itself. Again as the compiler is responsible for the call(to the constructor), it must know the method name beforehand.

To resolve these issues, java has come up with the concept as the constructor name should be same as the class name. So the same method will be called automatically on initialization.


class MyClass{
MyClass()
{
System.out.println("Default constructor and creating the class object ")
}
}
public class TestConstructor{
public static void main(String args[])
{
for(int i=0;i<100;i++)
{
new MyClass();
} 
}
}
 

When an object is created using the new operator, the storage is allocated and the constructor is called. This mechanism guarantees the object is properly initiated before we can work with it.
The traditional convention of making the method’s first letter in lower case and the first word of the subsequent words in upper case is ignored here as it has to match exactly with the class name.
Follow this link to get more details about the constructors.

Member Initialization:

Java guarantees that each variable is properly initialized before it is used.

Case-I for Local Variables:

If the variable is defined in a method and not initialized, the compiler will throw an error stating the variable may not have been initialized.


void myFunc()
{
int i;
i++;
}
 

In this case, the compiler will throw an error for the line where we have mentioned int i. The compiler could have given a default value but as it is more likely a programmer’s error. If compiler gives any value it may also produce a different result in a different time. Hence it forces the coder to produce an initial value. This reduces potential bugs.

Case-II for primitive Variables:

If the variable is primitive and a member of the class, in that case, any method can use or initialize the data. So it may not be suitable to force the user to provide the initial value. It is also potentially unsafe to leave them with garbage value. So each primitive value if they are a member of the class initialized with their default values. In this way, they get an initial value.


public class TestInitialValues{
public static void main(String []args){
MyClass mc=new MyClass();
mc.print();
}
}
class MyClass{
boolean t;
char c;
short s;
float f;
int i;
double d;
byte b;
long l;
Class obj;
void print(){
System.out.println("Datatype-->InitialValue n"+
"boolean->"+t+"n"+
"char->"+c+"n"+
"short-->"+s+"n"+
"float-->"+f+"n"+
"int-->"+i+"n"+
"double-->"+d+"n"+
"byte-->"+b+"n"+
"long-->"+l+"n"+
"class-->"+obj+"n"
);
}
}

The output of the code:
$javac TestInitialValues.java
$java -Xmx128M -Xms16M TestInitialValues
Datatype–>InitialValue
boolean->false
char->
short–>0
float–>0.0
int–>0
double–>0.0
byte–>0
long–>0
class–>null
Even if there is no value are specified, they automatically get initialized. At least there is no garbage value assigned to them. Even the class reference that is an object is initialized to null

Specifying Initial Values:

It may also happen that we need to specify the initial values sometimes.

Case-I: Direct value assignment:

We can directly provide or assign the values to the variables:


class MyClass{
boolean t=false;;
char c='x';
short s=oxff;
float f=3.14f;
int i=44;;
double d=3.1415;
byte b=47;
long l=1.0l;
}

Case-II: Direct value assignment for class object:


Myclass mc=new MyClass();
 

If we have not given any initial value and later if we try to use the same object we will get a null pointer Exception.As all object reference is initialized to null(refer case-I).

Case-III: Value assignment from a function:

We can use a function call to initialize the value of a variable.


class MyClass{
int i=MyFunction();
}
 

This method may also contain argument and those arguments can not be other class members that have not been initialized.
Allowed Case:



class MyClass{
int i=MyFunction();
int j=MyAnotherFunction(i);
}
 

The below-written code snippet is not allowed:


class MyClass{
int j=MyAnotherFunction(i);
int i=MyFunction();
}
 

We will get an error message from the compiler that I may have not initialized. Forward referencing is not possible in java.

Constructor Initialization:

The constructor as we discussed at the beginning of the post can be used to perform initialization. It has given much more clarity and provides better flexibility among all the methods. It can assign values.


class MyClass{
private int i;
private int j
MyClass(){
i=MyFunction();
j=MyAnotherFunction(i);
}
}
 

In this case, int i and j are initialized to 0 first and then to the respective output of the method calls. The compiler does not force us to initialize the elements here but may ask before they are used.

Share and Enjoy !

Leave a Comment

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