- Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type.
- An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
- Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
- This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.
Declaring Array Variables
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:
dataType[] arrayRefVar;
or
dataType arrayRefVar[];
Creating Arrays:
You can create an array by using the new operator with the following syntax −
Syntax:
arrayRefVar = new dataType[arraySize];
ADVANTAGES:
- We can access any element randomly by using indexes provided by arrays.
- Primitive type to wrapper classes object conversion will not happen so it is fast.
- Array can store many number of elements at a time.
Disadvantages:
- Arrays are Strongly Typed.
- Arrays does not have add or remove methods.
- We need to mention the size of the array. Fixed length.
- So there is a chance of memory wastage.
- To delete an element in an array we need to traverse through out the array so this will reduce performance.