Expected:0 why because "in theory" when a object gets created JVM supplies a default constructor and it sets the values to zero's and nulls,Not the values that were loaded in by the class loader. Did i get it wrong or what??
zoheb hassan wrote:... when a object gets created JVM supplies a default constructor and it sets the values to zero's and nulls...
No. The only thing a default constructor does is to call it's parent's no arg constructor. It doesn't initialise any variables.
If you had not assigned a value to 'a' then it would have had the default value of zero, but you did assign a value and so that is the value it will have.
When you create a new instance of Example3, it first sets 'a' to 10. Then, because you called the default constructor, it sets 'a' to 20, which is why it outputs 20. If the line 'a=20;' were not there, then the output to your program would be '10'.
Yeah, a variable in java will change it's value if you declare it to different value.
int a = 10;
a = 20;
You changed the value of the variable int a. It first represented 10, and then you changed the value to 20. If you want something else to represent 20, besides a, you can give it a different name. For example:
int a = 10;
int b = 20;
or declare it and initialize it in two different steps:
int a, int b;
a = 10;
b = 20 ;
That way it doesn't over ride the value of a.
In your code, you shouldn't declare a again. You should be able to simply use a, which represent 10. You don't have to tell the compiler that a = 10 again once it's been declared.