Major differences with C/C++ arrays:
• Java arrays are references
• Java arrays know their size
• Java checks the bounds of an array when accessed
• Java multidimensional arrays need not be rectangular
• Java array elements are initialized
Example 1:)
public class SimpleReferenceExample{public static void main( String args[] )
{// Reference allocated, no array space allocatedfloat[] sampleArray;//allocate array locations on heapsampleArray = new float[ 12 ];// Indexing starts at 0 like C/C++sampleArray[ 0 ] = 3.2F;int[] integerArray = new int[ 3 ];
// Reference refers to new array.// Old array available for garbage collectionsampleArray = new float[ 2 ];}
} Example 2:)
public class ArrayExamples{public static void main( String args[] )
{// Two locations to place [ ]int integerArray[ ];int[ ] alias;integerArray = new int[ 10 ]; // Indexed from 0 to 9// Note use of .length to get array sizefor ( int index = 0; index < integerArray.length; index++ )
integerArray[ index ] = 5;alias = integerArray; // Arrays are referencesalias[ 3 ] = 10;System.out.println( integerArray[ 3 ] ); //Prints 10
integerArray = new int[ 8 ];System.out.println( integerArray[ 3 ] ); //Prints 0, Why?System.out.println( alias[ 3 ] ); //Prints 10System.out.println( integerArray ); //Prints [I@5e300868}}
No comments:
Post a Comment