The JavaTM Tutorial
Trail: Learning the Java Language Lesson: Object Basics and Simple Data Objects Here's a simple program, called Declaring a Variable to Refer to an ArrayThis line of code from the sample program declares an array variable:Like declarations for variables of other types, an array declaration has two components: the array's type and the array's name. An array's type is writtenint[] anArray; // declare an array of integers Creating an ArrayYou create an array explicitly using Java's Array InitializersYou can use a shortcut syntax for creating and initializing an array. Here�s an example:The length of the array is determined by the number of values provided between { and }.boolean[] answers = { true, false, true, true, false }; Accessing an Array ElementNow that some memory has been allocated for the array, the program assign values to the array elements:This part of the code shows that to refer to an array element, either to assign a value to it or to get its value, you append brackets to the array name. The value between the brackets indicates (with a variable or other expression) the index of the element to access.for (int i = 0; i < anArray.length; i++) { anArray[i] = i; System.out.print(anArray[i] + " "); } Getting the Size of an ArrayTo get the size of an array, you writearrayname.length
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved. What would be the correct syntax to declare an array with 10 integer values?Array Initialization in Java
int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable. Java populates our array with default values depending on the element type - 0 for integers, false for booleans, null for objects, etc.
What is the valid range of index values for an array of size 10?The elements of arrays are numbered starting at 0. The following declaration creates an array of 10 elements: double[] values = new double[10]; An index can be any integer ranging from 0 to 9.
What is an integer array?An array of integers is a sequence of integers in successive words of memory. The number of integers in the array is also a value kept in memory. In assembly language, an array of integers is declared using the directive . word followed by a list of comma separated integers.
Which one of the following statements is true about passing arrays to a method?Which one of the following statements is true about passing arrays to a method? By default, arrays are passed by reference to a method.
|