You are here

Array Creation

15 January, 2016 - 09:02
Available under Creative Commons-ShareAlike 4.0 International License. Download for free at http://cnx.org/contents/402b20ad-c01f-45f1-9743-05eadb1f710e@37.6
  • Array objects, like other objects, are created with new. For example, String[] arrayOfStrings = new String[10];declares a variable whose type is an array of strings, and initializes it to hold a reference to an array object with room for ten references to strings.
  • Another way to initialize array variables is
      int[] arrayOf1To5 = { 1, 2, 3, 4, 5 };
      String[] arrayOfStrings = { "array",
                                  "of",
                                  "String" };
      Widget[] arrayOfWidgets = { new Widget(), new Widget() };
  • Once an array object is created, it never changes length! int[][] arrayOfArrayOfInt = {{ 1, 2 }, { 3, 4 }};
  • The array's length is available as a final instance variable length. For example,
          int[] arrayOf1To5 = { 1, 2, 3, 4, 5 };
      System.out.println(arrayOf1To5.length);

         would print "5".