Intro to Java Web-Notes_Part62

Intro to Java Web-Notes_Part62 - // This loop assigns the...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: // This loop assigns the value 33 to every element in the array. int i : 0; while (i < 5) { arr[i] : 33; i++; i = O; // reset i back to the start of array // This loop prints out the contents of the array. while (i < arr.length) { System.out.println("Index " + i + " + arr[i]); i++; } The above code yields the following output: Index 0: 33 Index I: 33 Index 2: 33 Index 3: 33 Index 4: 33 The Visualization of an array that was shown earlier in this section was highly simplified. Since an array is an object, the name of the array is a reference to that object. A more accurate Visualization of the array created by this line of code int [1 x = new int[4]; would be Note that this means that you can create several references to the same array object, and refer to the array by any of those names: int [1 x : new int[4]; int [1 other; other = x; x[O] = 33; other[l] = 92; Initializing An Array A quick way to create an array and to give the array its initial contents is via a declaration and intialization statement as shown below: int tax = { 7, 10, 15, 20, 33 }; The Java compiler counts the number of values inside the curly braces (in this case there are five numbers) and creates an array of that size, then initializes the array to have the indicated values. That one line of code is equivalent to the following seven lines of code: int [1 tax; tax : new int[5], tax[O] = 7; tax[l] = 10, tax[2] = 15; tax[3] : 20; tax[4] : 3; This kind of initialization can only be done at the time the array is declared. Exercises - Follow the Code Show the output of each of the small programs shown below: L public class ArrFive l public static void main (String args) { int arr = new int[4]; arr[0] : 57; arr[2] : 35; arr[l] : 6; arr[3] = 100; arr[l] = 5; int i : O; // This loop just prints out the contents of the array while (i < arr.length) i System.out.println("Index " + i + ": " + arr[i]); i++; ...
View Full Document

Page1 / 2

Intro to Java Web-Notes_Part62 - // This loop assigns the...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online