14

The output of this code is 7 20.

Why does 7 print first and 20 is printed after that?

public class Television 
{
    private int channel = setChannel(7);
    public Television(int channel) 
    {
        this.channel = channel;
        System.out.print(channel +"");
    }

    public int setChannel(int channel) 
    {
        this.channel = channel;
        System.out.print(channel + "");
        return channel;
    }

    public static void main(String args[])
    {
        new Television(20);
    }
}
4
  • 1
    1º private field is initialized & 2º the constructor is called Commented Apr 24, 2014 at 8:16
  • Did you think the output should be different somehow? Doesn't the output basically prove what happens? Commented Apr 24, 2014 at 16:17
  • Questions like this are asked here all the time. I can't seem to find them right now though Commented Apr 24, 2014 at 17:48
  • 2
    Fun fact: in C# the equivalent code would be illegal. C# does not allow an instance field initializer to call an instance method precisely because the method might be using a field before the constructor body executes. Commented Apr 24, 2014 at 18:48

7 Answers 7

15

When the object is created, its fields are created. You have a class member:

private int channel = setChannel(7);

When you do:

new Television(20);

The field is initialized and setChannel is called before calling the constructor and 7 gets printed from there.

All fields of the object are created and populated with the provided values (or default values if no value is specified). You can think of that as preparation of the instance. After these members are ready and initialized, the constructor is called.

See the JLS for further and detailed information.

Sign up to request clarification or add additional context in comments.

Comments

14

Because that's the order of initialization in Java. In short:

  1. Static members and blocks
  2. Instance members and blocks
  3. Contructor body

3 Comments

@bhutto Short answer is good too. Looking at the time, it's possible the link to the JLS wasn't in Maroun²'s answer when endriu_l started his answer.
@ArlaudPierre thanks for standing up for me. Indeed first answer was missing JLS link and - in my opinion - specifying initialization steps in numbered list is more readable
@bhutto If you look at the time of answers, you notice that sometimes people start answering a question at the same time.
6

The answer is available in the Java Language Specification:

Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure:

  1. Assign the arguments for the constructor to newly created parameter variables for this constructor invocation.

  2. If this constructor begins with an explicit constructor invocation (§8.8.7.1) of another constructor in the same class (using this)...

  3. ... If this constructor is for a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (using super)...

  4. Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5.

  5. Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.

To sum it up, if a constructor does not call another constructor (using this) and it does not call any superclass constructor (using super) then the instance variables are initialized before executing the code of the constructor.

Comments

5

First, the private field is initialized and then the constructor is called.

So the output is 7 20.

In java, the following process occured when instantiate a new object:

  • All the private field of the object are valuated.
  • Then and only then, the constructor is called.

2 Comments

so it means constructor first intialise variables which are defined in a class
@user2534106 No, Java does this, then the constructor is called. It's not the constructor which does this.
4

You initialize your field 'channel' outside the class construsctor, so this initialisation is called before it.

This is what appends when you call new Television(20):

1/this.channel set to 7 (init step)
2/Calling constructor
3/this.chennel set to 20 (constructor code)

2 Comments

is Maroun Maroun answer is not enough , instead of giving vote why you people answer agian
@bhutto Because we were certainly writing our answer at the same time. So please stop posting useless comments
3

Because the setChannel in your initialization of the variable channel is called first to init the class, and the method in the constructor after that.

Comments

3

When you create an instance of an object , first you create its data members (i.e. first that line is executed private int channel = setChannel(7); ) and only then the Constructor public Television(int channel) {...} creates the object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.