In the first one, x is not initialized at all. Only y is assigned 0.
If that statement is within a method, you will get compilation errors - variable x might not have been initialized.
I dont think there is anything wrong with the second one.Thats perfect.
I'm not clear on why you got compilation errors. If you provide some code you've used, we can help.
rewati raman wrote:double x,y=0;
in first case you have declared x but not initialized. it can be done dome thing like this.
double x=y=0;
That's not the same at all! It would be interpreted as:
double x = (y = 0); Which would assign 0 to both x and y, but would not declare y. It will only compile if y is already declared.
both CASES i.e. 1 and 2 are different in this manner. each codes written in CASE 2 i.e. a and b all are same. and differ from CASE 1.
in CASE 1, you are trying to declare x but not initializing it and after that declaring and initializing y.
this code will compile in main method; but will cause ERROR! when ever they will be LOCAL VARIABLES. Because, LOCAL variable must me initialized before their use.
But, in CASE 2; you are trying to declare and initialize both in the same line or different lines. So, this will easily compile in all scope either as an instance variable or as a LOCAL Variable.
Vishal Kashyap wrote: . . . But, in CASE 2; you are trying to declare and initialize both in the same line or different lines. So, this will easily compile in all scope either as an instance variable or as a LOCAL Variable.
Not quite. In case 2 you are actually initialising the value of y, and later initialising x to the same value as y. That is different from case 3.
I would say that both case 1 and case 2 are writing code difficult to understand.
Ritchie Wrote : Not quite. In case 2 you are actually initialising the value of y, and later initialising x to the same value as y. That is different from case 3.
I would say that both case 1 and case 2 are writing code difficult to understand.
Ritchie,
Sorry, their is no any difficulty in understanding codes. initializing at first or at last doesn't matter here. ultimately, code will compile or not, is the question.
So, in my opinion CASE 2 will easily compile and as I've written there will be the compilation error in CASE 1.
Vishal Kashyap wrote:
Sorry, their is no any difficulty in understanding codes. initializing at first or at last doesn't matter here. ultimately, code will compile or not, is the question.
So, in my opinion CASE 2 will easily compile and as I've written there will be the compilation error in CASE 1.
No. Case 2(a) wont compile either, unless you have declared 'y' previously. Thats exactly why its difficult to understand such code. You yourself fell for it - thinking it might compile.
Please have a look at Mathew Brown's post above.