Introduction to arrays in java

Introduction to arrays

An array is a collection of similar type of elements which have a contiguous memory location.

Array in java is an object which contains elements of similar data type .

Array in java is index based,  the first element of the array is stored at 0th index and second element store in the 1st index.

There are some following important point about the java

  • In java all arrays are dynamically allocated.
  • Since arrays are object in java , we can find their length using member length.
  • The size of array must be specified by an int value and not long or short.
  • The direct super class of an array type is object.
  • Java array variable can also be declared like other variable with [] after the data type. 
array

Declaration of array variable

To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable −

Syntax

//most preferred way
dataType[] arrayRefVar;
or
//less preferred way
datatype arrayRefVar[];

Creation of array

Array in java is an abject so, here we can create an array by using the new operator with the following syntax

Syntax

 //this syntax is valid when you already declare the array
arrayRefVar = new datatype[arraySize];

//when u do not declare array before so you can declare array and create array in one statement
dataType[] arrayRefVar = new dataType[arraySize];

 

Advantage of array

  • Code  Optimization: it makes the code optimized, we can retrieve or sort the data efficiently.
  • Random Access: We can get any data located at an index position.

Disadvantage of array

  • Size Limit: We can store only the fixed size of elements in the array. it does not grow its size at runtime. to solve this problem, collection framework is used in java with grows automatically.