Introduction
Java Fundamentals
Java Flow Control
Object Oriented Programming
Arrays in Java With Examples
Array in java is a group of like-typed variables referred to by a common name.Java provides a data structure, named as array, which stores a fixed-size sequential collection of elements of the same type. In this tutorial, we will learn how to declare, initialize, and access array elements with the help of examples.
An array is a collection of similar types of data. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. An array is a finite set of homogenous elements stored at contiguous memory locations. Like other variables, an array needs to be declared before it is used, so the compiler would know the type of the array, and the number of elements that can be stored in it. Each item in an array is called an element, and each element is accessed by its numerical index.
Java Array Syntax:
dataType[] a;
dataType []a;
dataType a[];
- An array can store elements of any data type, but all elements in an array must be of the same type.
- Naming rules for an array are the same as those for any variable.
- The maximum number of elements that can be stored in the array needs to be specified in the operator.
- It is also called the upper bound or the size of an array. It must be a positive integer.
Java Array Example:
int marks[10];
float temp [size];
double a[20];
String name[20];
- The square bracket identities it as an array.
- In the example above, an array has been defined as int marks10.
- The name of the array is marks and it's an array of 10 int values.
- Memory allocation to it will be 10*4=40 bytes.
Type of Arrays in Java:
1. Single-Dimensional Arrays: Single-Dimensional Arrays are arrays with one dimension. It stores the elements directly while declaring them itself.
2. Multi-Dimensional Arrays: A multidimensional array is also known as an array of arrays. It contains one or more arrays i.e. each element of a multi-dimensional array is another array.
Drawbacks of Arrays in Java:
- While declaring an Array, the number of elements to be stored in it should be known.
- It is static.
- Insertion and Deletion of elements in an array are quite difficult.
- Allocation of memory more or less than the required space leads to a problem