Google
    Custom Search

    How to Define and Use A Java Array

    by Nancy Sewell

    Beginner Java: Simple array

    Java Arrays are data structures containing objects of the same type. A String array can only contain Strings and a Car array can only contain car objects. Arrays are used to store objects that you want to use in other calculations or want to reference to. For example, an array can contain grades that can be averaged or referenced.

    Things You'll Need:

    • Java IDE
    • Beginner working knowldge of java

    1.
    When you declare a Java array, you need to give it a data type when you declare it just like you would give a variable a datatype.

    For example, we will declare an integer array containing five elements which we will name arrayName

          int[] arrayName = new int[5];

    2.
    When you need to access an element of the array you can do so directly :

          System.out.println(arrayName[3] );

    or you can print out the entire array using a for loop - first put some values in it so we can see what is going on. Remember arrays start numbering with 0 so an array with a length of five has elements numbered from 0-4 and not 1-5.

          arrayName[0] = 000;
          arrayName[1] = 111;
          arrayName[2] = 222;
          arrayName[3] = 333;
          arrayName[4] = 444;

    To print out the entire array (five is the size of the array):

          for (int i=0; i<5; i++)
           {
            System.out.println(arrayName[i]);
           } // end for

    This will print out the following:

      0
      111
      222
      333
      444

    3.
    When you declare arrays, they are a fixed length and cannot be any other size. If you need to increase the size of an array, you can declare a new array that is a larger size and copy the first array into it using a loop. You then re-declare an array using the first array name making it the same size (or larger) than the second array and copying it back into the new array (that has the same name as the original array) You can place this code into a method and call it whenever we need to increase the array size. This is a work around for using an array that needs to grow. The best solution is to use an ArrayList which can grow as needed although that is beyond the scope of this beginner Java article.

    
    
    Return to HorsesNW.com

    Privacy Policy