Sunday 7 June 2015

Multidimensional Arrays

public class multidimensionalArraysDemo {

        public static void main(String[] args) {

                /* In the Java programming language,
                 * a multidimensional array is an array whose components
                 * are themselves arrays.
                 * 
                 * This is like a box which contains several boxes. Each of which
                 * contains several more boxes. Which contain an item or value.
                 */

                String[][] names = {
                                {"Mr. ","Mrs. ","Ms. "},
                                {"Smith","Jones"}
                };

                /* We reference the array in the same way as before.
                 * But this time we have two indeces instead of one.
                 */
                System.out.println(names[0][0] + names[1][0]); // Mr. Smith
                System.out.println(names[0][1] + names[1][0]); // Mrs. Smith
                System.out.println(names[0][2] + names[1][0]); // Ms. Smith
                System.out.println(names[0][0] + names[1][1]); // Mr. Jones
                System.out.println(names[0][1] + names[1][1]); // Mrs. Jones
                System.out.println(names[0][2] + names[1][1]); // Ms. Jones

                /* We can also print the length of the array using the
                 * length property.
                 */
                System.out.println("\nLength of names: " + names.length);
                System.out.println("Length of names index 0: " + names[0].length);
                System.out.println("Length of names index 1: " + names[1].length);
        }
}

No comments:

Post a Comment

Translate