Here you get compiler error because the compiler thinks that variable ref might have not get any value, the if statement that assigns the value to it may never run, hence using it would give error, in your second example you didnt attempt to use variable y so no error.
It doesnt give any error for y, we are using y w/o initializing.. Howcome?
Can anyone tell how advance for loop works internally, especially exactly how index of an array is used. as per my understandings E.g for(int i: n), here i refers to individual element in array n and not an index. If I want to use index for this array n, using this for loop method, how to go abt it?
If i want to use decrementing adv. for loop, is it possible? if yes how.
Shaily, This is enhanced for loop in java so for (int i: arr) implies that i will have the value of arr and arr will go to next array value. So as for the below example-:
int []arr = {1,2,3,4}; for ( int i : arr ) { arr[i] = 0; } for ( int i : arr ) { System.out.println(i); }
Loop goes as-: 1st-: for(int i:arr)=>i=arr[0], i=1 and in for loop arr[i] = 0;=> arr[1]=0 2nd-: for(int i:arr)=>i=arr[1], i=0 and in for loop arr[i] = 0;=> arr[0]=0 3rd-: for(int i:arr)=>i=arr[2], i=3 and in for loop arr[i] = 0;=> arr[3]=0 4rth-:for(int i:arr)=>i=arr[3], i=0 and in for loop arr[i] = 0;=> arr[0]=0