How Variable Initialization Takes place in Java ??

0
50
Spread the love
  • 12
  • 12
  • 15
  • 12
  •  
  •  
  •  
  • 10
  •  
  •  
    61
    Shares

Variable Initialization in Java
Variable Initialization 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

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 build a big building we first create a image or diagram of it. The diagram may have building dimensions, number of doors, windows, size. When we actually 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, it will have only variables not method.

How the methods are binded to object?

This keyword :every non static method has a 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 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 a overhead for the coder. Java has come up with a simple concept called 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 compiler will provide us a default one and continue to construct an object during object creation process. This reduce 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 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 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 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 , compiler will throw an error stating the variable may not have been initialized.


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

In this case compiler will throw an error for the line where we have mentioned int i.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 different result in different time.Hence it forces the coder to produce an initial value.This reduces the 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 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 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:

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
  • 12
  • 12
  • 15
  • 12
  •  
  •  
  •  
  • 10
  •  
  •  
    61
    Shares

LEAVE A REPLY

Please enter your comment!
Please enter your name here