-6

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 ?

pjain
  • 1,149
  • 2
  • 14
  • 28
  • 2
    Could you please post code that compiles? – Sergey Kalinichenko Apr 22 '15 at 09:19
  • 2
    Yes, your code won't even compile as it stands now. – Tim Biegeleisen Apr 22 '15 at 09:19
  • The code that you have written is not a valid java code. Kindly edit the same and post again. – Blip Apr 22 '15 at 09:21
  • For case 2, you have not assigned `b` to anything, you have created a separate variable `B b` local to the instance initializer. If you meant `b = new B();` then the first and second example would be equivalent. – Oli Apr 22 '15 at 09:27
  • In both examples, th intialization of the member variables is carried out after the implicit call to `super()` in the implicitly created no-args constructor `A()`. – Oli Apr 22 '15 at 09:29
  • do you mean to say that 2nd code the `b=new B()` is in some method of `A`? – Blip Apr 22 '15 at 09:40
  • @Blip, no its not a method , its in initializers block. – pjain Apr 22 '15 at 09:41
  • @Oli,thanks for your answer. 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 ? – pjain Apr 22 '15 at 09:44

3 Answers3

2

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

Community
  • 1
  • 1
Zelldon
  • 5,396
  • 3
  • 34
  • 46
1

As you know that the constructor is called when we instantiate a class. Also all classes have top level Class as Object in JAVA. Now whenever we call the constructor of any class for your case A as new A() it leads us to call first super() leading to Object's constructor.

Now in your example1 your variable b is declared and initialised in the class itself. So before the constructor of class A is executed the variable b is initialised i.e. all the code that you write in public A() will be executed after b has been initialised.

In your example2 your variable b is declared in the class but is being initialised in the constructor of A. If you have some code before the line b = new B(); that code would be executed first then the b would be initialised.

See the example below :

Class A{
   B b = new B();

   public A(){
      b == null; //FALSE as it has been already initialised.
   }
}

But

Class A{
   B b ;

   public A(){
      b == null; //TRUE as it has not been initialised.
      b = new B();
      b == null; //FALSE as it has been just initialised.
   }
}
Blip
  • 3,061
  • 5
  • 22
  • 50
0

I assume it has to do with the following:

Initializing Instance Members

Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.

Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:

{
    // whatever code is needed for initialization goes here
}

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

https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

Basically it means that all instance variables that are between the brackets will be initialized for all constructors. Even though your classes dont have multiple constructors

added example with multiple constructors

class A{
  B b;
  int index;
  String result;
  {
    b = new B();
    index = 0;
  }

  public A(int temp){
    // nothing
  }

  public A(int temp, String test){
    this.result = test;
  }

  public int getIndex(){
    return index;
  }
}

It doesnt matter here which constructor you use, as the initialization between the brackets is copied into both constructors. a.getIndex() will always return '0'

W vd L
  • 625
  • 9
  • 26
  • @W vd L , I know about Initializer blocks. I wanted to know the difference if 1) we create our obeject(in class declaration) outside of any block and 2) we create an object in Initializer block. – pjain Apr 22 '15 at 09:36
  • See my last sentence.. the init block is for simplifieing your code when using multiple (overloading) constructors. Let me add an example – W vd L Apr 22 '15 at 09:38