0

I read this question while studying model questions for exams.

class Was { private int a=show(); private int b=5; private int show() { return b; } public static void main(String args[]) { System.out.println((new Was()).a); } } 

I compiled this,it prints as 0. Why it is not print as '5' ?

1
  • Because the initializers are evaluated in the order they appear. Commented Dec 22, 2013 at 19:25

2 Answers 2

4

Field initialization happens when a constructor is invoked and in order of declaration. This field

private int a=show(); 

is initialized before

private int b=5; 

It is initialized with the value returned by show(). At that time b has yet to be initialized to 5. Its default value is 0. So show() returns 0. That value is assigned to a.

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

3 Comments

Thank you @Sotirios Delimanolis.But,at the time of calling show(), b is unknown field,how it can be returned?
@anavaraslamurep The field is known, it has just been given the default value for int primitives, which is 0.
Java object fields go through two steps. Before any constructor or initializer execution, each is initialized to a default value that depends only on its type, 0 for numeric fields, null for references, false for booleans. That value can be changed later by an initializer or by constructor code.
1
private int a=show(); 

By the time you calling show() method the value of b not yet set and hence the default value of integer is 0 results.

To see desired output

private int b=5; private int a=show(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.