Outputs:10
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??
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
9
posted
0
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'.
SCJP 6 || SCWCD 5
John de Michele
Rancher
Joined: Mar 09, 2009
Posts: 600
posted
0
Zoheb,
In your constructor, you change the value of a to 20. That's why you get 20 as output.
John.
Ashley Perry
Greenhorn
Joined: Jun 21, 2009
Posts: 4
posted
0
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.
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32675
4
posted
0
Reply to "Hello World", it says
Hello, Zoheb Hassan.
Please use a thread title which tells us what the thread is about; I can't see anything about Hello World in your thread.