Home Javatutorials Java Field Initialisation - Java Tutorials



Java Field Initialisation - Java Tutorials
Posted on: April 18, 2011 at 12:00 AM
This page discusses - Java Field Initialisation - Java Tutorials

Java Field Initialization

The fields/variable initialization in any programming language is very important. Every programmer does this in different ways. It is performed to provide some default value.

The java programmer can initialize the field in different fashion like some declares the fields and then initializes that. some initializes with their declaration.

public class FieldInitialization{
	private int count;
	private int i;
	private String url;
	
	public FieldInitialization(){
		
	}
	
	public FieldInitialization(int x, String y){
		this.i=x;
		this.url=y;
	}
}

In an object oriented programming language a constructor is used for initialization. Consider a class given below

public class InitializationDemo {
	private int i = 0; // not necessary to initialize here
	private boolean b = false; // not necessary to initialize here

	public InitializationDemo(int x, boolean y) {
		this.i = x;
		this.b = y;
	}
}

In the above code you might me thinking that what is the necessity to initialize the variable above. But when you compile the above code and then decompile. Then you will see the class something like this

public class InitializationDemo {
	  public InitializationDemo(boolean flag, int j) {
	    b = true;
	    i = 0;
	    b = flag;
	    i = j;
	  }
	  private int i;
	  private boolean b;
}

The compiler uses all the filed initializer into its default Constructor. So if you have more than constructor in a class, that all the initialization code is copied into all the constructor. For Example

public class SampleInitializer {
	{
		System.out.println("Testing Field Initialization");
	}
	private int field=10;

	public SampleInitializer() {

	}

	public SampleInitializer(int x) {
		this.field = x;
	}

}

Then the decompiled class would be something like this.

public class SampleInitializer {
	private int field;;

	public SampleInitializer() {
		System.out.println("Testing Field Initialization");
		field=10;
	}

	public SampleInitializer(int x) {
		System.out.println("Testing Field Initialization");
		this.field = x;
	}
}

Related Tags for Java Field Initialisation - Java Tutorials:


More Tutorials from this section

Ask Questions?    Discuss: Java Field Initialisation - Java Tutorials  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.