class fields Initialization sequence in Java

what is the difference in following two pieces of code:

class B{
  B(){}
}

//1)
class A{
  B b = new B();
}

//2)
class A{
   B b;
  {
   b = new B();
 }
}

what is the difference in initialization in these two ways ? Also if both the statement are in one single class , what would be their sequence of execution and why?

EDIT: Adding some more clarification:

class C{
//1)  
  int i = 5;

 //initializers block
  {
    i =7;
  }

}

What is the sequence of execution for both these two statements ? What is the final value of i ?

Answer

UPDATE FOR THE NEW CLEARER QUESTION:

It sees now that I should have added more text to my question. I wanted to know what would be the sequence of execution in case both these statements(1 and 2) are in one single class for the same variable ?

You are interessted something like this:

   private class Test {
        public String field = new String("1");
        {
            field = new String("2");
        }

    }

At first the field get the value 1, after that the constructor will be called and the init block which was placed in the ctor at compile time will be executed so the value of field is “2”.

See this example:

http://ideone.com/72uxES

See also this Question and answer:

Default constructor vs. inline field initialization


OLD VERSION

I think you mean something like this:

Object obj = new Object() 

Or

Object obj;
{
  obj = new Object();
}

The curly brackets define a scope in which the variable life time is given.

Say we have following example:

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    private static void checkObject(Object obj) {
        if (obj == null)
            System.out.println("Object is null");
        else
            System.out.println("Object is not null");
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        Object obj;
        {
            obj = new Object();
            checkObject(obj);
        }
        checkObject(obj);
    }
}

The Output is:

Object is not null
Object is not null

But if we change it to:

{
  Object obj = new Object();
  checkObject(obj);
}
checkObject(obj);

It will not even compile and give these error msg:

Main.java:22: error: cannot find symbol
        checkObject(obj);
                    ^
  symbol:   variable obj
  location: class Ideone
1 error

The first declares a variable obj and initialize it inside the scope because it was outside declared it can be used after the scope.

If it is declared and initialized only in the scope it can be used only inside the scope. The lifetime is bound to the scope.

If you use the curly brackets to initialize class fields you are able to use more than one statement to initialize them but you can also simply create a final method and call the method to initialize the field.

Example for curly brackets and field initialization:

class A {
 private String field;
 {
   StringBuilder builder = new StringBuilder("Text").append(value)
                                                    .append(" ")
                                                    .append(otherValue);
   //make some computations 
   //append to builder
   //add to field
   field = builder.toString();
 }

Hint:

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

See working example:

http://ideone.com/X42rQI

Leave a Reply

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