Java: ArraysArrays are treated differently than in C++. In fact, an array is an object in java. Declaring ArraysHere are some examples:char s[]; int array[]; String Names[]; Button B[]; Creating Array ObjectsTo create an array you must use the new operator to create the instance. An Array is an object itself in Java. You can create Arrays that are arrays of objects like Integer or of primitive types like int. Some examples:String[] Names = new String[50]; /*an array of strings storing names*/ Button[] B = new Button[3]; /*an array of 3 Buttons*/ //The following two Arrays contain primitive types of int and char //respectively rather than using the objects of Integer and Character int[] array= new int[100]; /* 100 times can be stored in array*/ char[] x = new char[10]; /*an array of 10 x values*/Note that if you want to only store a single name then you do not need an array of Strings but, just one String. NOTE: When you are creating an array
of Objects, you must not only create the array but, for each
Step 1: Step 2:
The Length of an ArrayYou can always test the number of elements stored in an array by looking at the value stored in the variable called length that is a member of any kind of array. For example,System.out.println("The number of names is " + Names.length); Multidimensional ArraysThese are declared just as you would guess. For example, to declare a 2D array with 10 by 3 values you would:int Image[][] = new int[10][3];Note that Image[0].length tells you the number of elements in the 0th row of the image.
Initializing ArraysThere are three ways to initialize an array. For all Arrays of Objects with the exception of Strings, you must first declare the array and for each element call the class's constructor as shown in example 1. For String Arrays and primitive type Arrays (e.g. arrays or int or float), you can either initialize the array at the same time you create it or afterwards. Examples 2 and 3 show these later methods.
You can not declare arrays as you did in C++. This you can NOT DO:int list[50];Example |
||||||