Arrays in Java Programming
Previous | Home | Next |
Arrays is a collection of same type of elements.An array store multiple items of same data type.in a contiguous block of memory divided into slots.to declare an array write a data type followed by [] followed by the identifier name. arrays may be one dimensional ,two dimensional and multidimensional arrays.
java.util is a class of java . lang .object package which contains various methods used for manipulating arrays.this
class also contains static factory that allows arrays to be viewed as list.
Allocation
Once an array is declared, it must be allocated. You probably noticed that the size of the arrays has not been specified
in the examples so far. This is because, in Java, all arrays must be allocated with new. Declaring the following array would have resulted in a compile-time error:
int intArray[10]; // this is an error
Initialization
An alternative way of allocating a Java array is to specify a list of element initializers when the array is declared.
Array Access
Items in a Java array are known as the components of the array. You can access a component at runtime by enclosing the component number you want to access with brackets.
ALLOCATION OF ARRAY
//To allocate an array you use new, as shown in the following examples:
int intArray[] = new int[400];
float floatArray[];
floatArray = new float[400];
long [] longArray = new long[400];
double [][] doubleArray = new double[20][20];
INITIALIZATION OF ARRAY
int intArray[] = {1,2,3,4,};
char [] charArray = {'a', 'b', 'c'};
String [] stringArray = {"A", "Four", "Element", "Array"};
//In this case, intArray will be a four-element array holding the values 1
//through 4. The three-element array charArray will hold the characters 'a', 'b', and 'c'.
//Finally, stringArray will hold the strings shown.
ACCESS OF ARRAY
int intArray[] = {100, 200, 300, 400, 500};
int a = intArray[0]; // a will be equal to 100
int b = intArray[1]; // b will be equal to 200
int c = intArray[2]; // c will be equal to 300
int d = intArray[3]; // d will be equal to 400
int e = intArray[4]; // e will be equal to 500
Previous | Home | Next |