Java Array Variables

Java Array Variables

  • An array is a special type of object that can hold a collection of equal elements.
  • Type of the elements of the array is called the base type of the array.
  • The number of elements an array contains, is a fixed attribute called its length.
  • Java supports arrays that can contain any primitive types or reference types.
  • We can create an array of a specified length, or access the elements with the index operator, [ ].
  • We first declare a variable of the appropriate type and then use the new operator to create an instance of it.
    Array defining examples:
    ...
     int [] arrayOfInts;  // preferred
     int arrayOfInts [];  // C-style and ok
     String [] someStrings;
    
     arrayOfInts = new int [42];
     arrayOfInts[0]=23;
     someStrings = new String [number + 2];
     someStrings [1] = "Boofa";
    ...
  • Java supports C-style curly braces {} to construct the initialized values for an array.
    Array with initializing examples:
    ...
    int [] primes = { 1, 2, 3, 5, 7, 7+4 }; // e.g., primes[2] = 3 
    String [] verbs = { "run", "jump", someWord.toString(  ) };
    Button [] controls={stopButton, new Button("Forwards"), new Button("Backwards")};
    // All types are subtypes of Object
    Object [] objects = { stopButton, "A word", null };
    ...
  • You can create a multidimensional array using multiple bracket pairs, one for each dimension.
    Multidimensional Array defining examples:
    ...
      ChessPiece [][] chessBoard;
      chessBoard = new ChessPiece [8][8];
      chessBoard[0][0] = new ChessPiece.Rook;
      chessBoard[1][0] = new ChessPiece.Pawn;
    ...
  • Of course, you can create arrays with more than two dimensions.
    Here are some examples:
    ...
     byte[][] smallArray = { { 10, 11, 12, 13 }, { 20, 21, 22, 23 },
            { 30, 31, 32, 33 }, { 40, 41, 42, 43 } };
     Object events[][] = { { new Integer(1452), new String("Italy") },
            { new Integer(1472), new String("b.jpg") },
            { new Integer(1483), new String("Hr") },
            { new Integer(1495), new String("Pte") },
            { new Integer(1503), new String("m.jpg") },
            { new Integer(1519), new String("F") } };
    ...
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.