Java Array
Java Array
Java Arrays
Normally, an array is a collection
of similar type of elements which
has contiguous memory location.
Disadvantages
Size Limit: We can store only the fixed size of
elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework
is used in Java which grows automatically.
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Change an Array Element
To change the value of a specific element, refer to the index number:
Example:
cars[0] = "Opel";
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]); // Now outputs Opel instead of Volvo
Array Length
To find out how many elements an array has, use
the length property:
Example
// Outputs 4
Multidimensional Array in Java
In such case, data is stored in row and column based index (also known as
matrix form).
Let's see the simple example to declare, instantiate, initialize and print the
2Dimensional array.
import java.util.Scanner;
public class ArrayInputExample2
{
public static void main(String args[])
{
int m, n, i, j;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of rows: ");
//taking row as input
m = sc.nextInt();
System.out.print("Enter the number of columns: ");
//taking column as input
n = sc.nextInt();
// Declaring the two-dimensional matrix
int array[][] = new int[m][n];
// Read the matrix values
System.out.println("Enter the elements of the array: ");
//loop for row
for (i = 0; i < m; i++)
//inner for loop for column
for (j = 0; j < n; j++)
array[i][j] = sc.nextInt();
//accessing array elements
System.out.println("Elements of the array are: ");
for (i = 0; i < m; i++)
{ Output
for (j = 0; j < n; j++)
//prints the array elements
System.out.print(array[i][j] + " ");
//throws the cursor to the next line
System.out.println();
}
}
}