for (int i = 0; i < list.length; i++) ...
int negativeIndex = -1; boolean noNegative = true; for (int i = 0; i < list.length && noNegative; i++) if (list[i] < 0) { negativeIndex = i; noNegative = false; }
In this way, you can see not only what the values are but where they are located.for (int i = 0; i < list.length; i++) System.out.println("list[" + i + "] = " + list[i]);
first creates list, a reference to an int array and then creates an array of int values (all initialized to 0) with the variable list acting as a reference to the array. The two operations can be (and usually are) combined into one statementint [] list; list = new int[10];
but you should be clear about the two operations that are being performed by this single statement. If you forget to allocate space for the array, the compiler will catch you. For example, the fragmentint [] list = new int[10]
will cause the compiler to produce the message:double [] list; list [0] = 1;
variable list may not have been initialized
will compile without warning but will cause Java to throw a Null- PointerException when it attempts execution. The problem is that new here creates an array of null references. An attempt to use the instance method equals when list[0] is not referring to an instance of an object naturally causes Java to get upset.Object[] list = new Object [10] ; System.out.println(list[O].equals(list[1]);
|