GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||
GeezerVison is showing en.wikiversity.org — Java Programming/Arrays - Wikiversity About ArraysAn array is a group of variables of the same data type and referred to by a common name. An array is contiguous block of memory locations referred by a common name. i.e. To store 500 integer values in the variable multipleInt , you type this. int[] multipleInt = new int[500]; //You just created a variable multipleInt[]. //But right now it only contains 500 0s. Types of ArraysOne-dimensional arraysOne-dimensional array is a list of variables of the same data type. Syntax to declare a one dimensional array//To create an one-dimensional array, you type this type arrayName [] = new type[length];// type is like int, char, double, etc. // ; length is how many of that type you will store
For e.g. String designations[] = {"General Manager", "Managing Director"}; Things you can do with arraysYou can print out all the values in the array. For e.g. int[] anArray = new int[10]; // creates a new integer array with a length of 10 for(int fillUp= 0; fillUp<anArray.length-1;fillUp++) // This will fill the array //with numbers anArray[fillUp] = (int)(Math.random()*20 +1);// fills each spot in the //array with random numbers from 1 to 20 for(int fillUp= 0; fillUp<anArray.length-1;fillUp++)// a '''for loop''' System.out.println(anArray[fillUp]);// prints out the array A possible output of the above will be: 20 2 Notice this part of the code for(int fillUp= 0; fillUp<anArray.length-1;fillUp++) Notice that in this part of that code: fillUp<anArray.length-1 , the variable fillUp must be one less the length of the array. Why do we have to do this? You may ask. Remember, the index 0 is the first value in an array/String. So if the length was 11, and the program searched for the 12th value, it would not find it, and there would be an error that says something like this: Index Out of Range . Two-dimensional arraysTo declare two-dimensional arrays, you need to specify multiple square brackets after the array name. Syntax to declare a two dimensional arraytype array_name = new type[rows][cols]; Advantages/* 1. You can refer to a large number of elements by just specifying the index number and the name of the array. 2. These make it easy to do calculations in a loop.*/ Other Types of ArraysYou can also declare arrays like int[][][] arrayexample = new int[2][2][2]; int[][][][] example2 = new int[2][2][2][2]; but it will make programming with these arrays very complicated. The 1 dimensional array and the 2 dimensional arrays are the most commonly used
| ||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |