Skip to main content

Posts

Showing posts with the label for loop

How To Deal with Array Exception in Java

Remember that array indexes start at 0. So, for an array with five locations, the indexes would be 0,1,2,3,4. Check that FOR loops and the results of any calculated indexes take this into account. Also, make sure that a value is checked before it is incremented. String[] bob = new String[10]; for(int i=1 ; i<10 ; i++) The index should start at 0, and go to 9 { bob[i]="bob" The error will point to this line } In the first program, the error is caused by the FOR loop having the wrong parameters. This causes the error in another place.

What Are Restrictions for Enchanced For Loop?

You can not use "Enhanced For Loop" to remove elements from a collect or an array. Also, you can not modify the current slot in a collect or an array. It is not usable for loops where you need to replace elements in a list or array as you traverse it. For example, class Program { public static void main(String[] args) { Collection<String> c = new ArrayList<String>(); c.add("A"); c.add("B"); c.add("C"); for(String name : c) { name = "CHANGED"; } for(String name : c){ System.out.print(name); } } } You will see that the ouput still "ABC". All you have done is modified the local reference variable name.