Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
51 views

Java 8 Array

Uploaded by

amaleshmsc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Java 8 Array

Uploaded by

amaleshmsc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Java Arrays

Arrays are used to store multiple values in a single variable, instead of


declaring separate variables for each value.

To declare an array, define the variable type with square brackets:

String[] cars;

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

Normally, an array is a collection of similar type of elements which has


contiguous memory location.
Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can
store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the
0th index, 2nd element is stored on 1st index and so on.
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[3]);
}
}

Advantages
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.

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.

Types of Array in java


There are two types of array.

Single Dimensional Array

Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];

//Java Program to illustrate how to declare, instantiate, initialize


//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}} it Now
Output:
10
20
70
40
50
Declaration, Instantiation and Initialization of Java
Array
We can declare, instantiate and initialize the java array together by:
Basically, the length of an array is the total number of the elements
which is contained by all the dimensions of that array. Syntax:
public int Length { get; } Property Value: This property returns the
total number of elements in all the dimensions of the Array.
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Test it Now

Output:
33
3
4
5

For-each Loop for Java Array


We can also print the Java array using for-each loop. The Java for-each
loop prints the array elements one by one. It holds an array element in a
variable, then executes the body of the loop.
The syntax of the for-each loop is given below:
for(data_type variable:array){
//body of the loop
}
Let us see the example of print the elements of Java array using the for-
each loop.
//Java Program to print the array elements using for-each loop
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);
}}
Output:
33
3
4
k5

Passing Array to a Method in Java


We can pass the java array to method so that we can reuse the same
logic on any array.
Let's see the simple example to get the minimum number of an array
using a method.
//Java Program to demonstrate the way of passing an array
//to method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];

System.out.println(min);
}

public static void main(String args[]){


int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}
Output:
3

Anonymous Array in Java


Java supports the feature of an anonymous array, so you don't need to
declare the array while passing an array to the method.
//Java Program to demonstrate the way of passing an anonymous array
//to method.
public class TestAnonymousArray{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}

public static void main(String args[]){


printArray(new int[]{10,22,44,66});//passing anonymous array to method
}}
Test it Now

Output:
10
22
44
6-6

Returning Array from the Method


We can also return an array from the method in Java.
//Java Program to return an array from the method
class TestReturnArray{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}

public static void main(String args[]){


//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}}
Test it Now

Output:
10
30
50
90
60

ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an
ArrayIndexOutOfBoundsException if length of the array in negative, equal
to the array size or greater than the array size while traversing the array.
//Java Program to demonstrate the case of
//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80

Multidimensional Arrays
A multidimensional array is an array of arrays.
Multidimensional arrays are useful when you want to store data as a tabular
form, like a table with rows and columns.

To create a two-dimensional array, add each array within its own set of curly
braces:

Syntax to Declare Multidimensional Array in Java


dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java


int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java


arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its elements.

Access Elements
To access the elements of the myNumbers array, specify two indexes: one
for the array, and one for the element inside that array. This example
accesses the third element (2) in the second array (1) of myNumbers:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

System.out.println(myNumbers[1][2]); // Outputs 7

Remember that: Array indexes start with 0: [0] is the first element. [1] is
the second element, etc.

Change Element Values


You can also change the value of an element:

Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers[1][2] = 9;

System.out.println(myNumbers[1][2]); // Outputs 9 instead of

Loop Through a Multi-Dimensional


Array
We can also use a for loop inside another for loop to get the elements of a
two-dimensional array (we still have to point to the two indexes):

Example
public class Main {

public static void main(String[] args) {

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

for (int i = 0; i < myNumbers.length; ++i) {


for(int j = 0; j < myNumbers[i].length; ++j) {

System.out.println(myNumbers[i][j]);

}
}

Output:

1
2
3
4
5
6
7

Example of Multidimensional Java Array


Let's see the simple example to declare, instantiate, initialize and print
the 2Dimensional array.
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Output:
1 2 3
2 4 5
4 4 5

Jagged Array in Java


If we are creating odd number of columns in a 2D array, it is known as a
jagged array. In other words, it is an array of arrays with different number
of columns.
//Java Program to illustrate the jagged array
class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;

//printing the data of a jagged array


for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}
Output:
0 1 2
3 4 5 6
7 8
Addition of 2 Matrices in Java
Let's see a simple example that adds two matrices.
//Java Program to demonstrate the addition of two matrices in Java
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[2][3];

//adding and printing addition of 2 matrices


for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}

}}
Output:
2 6 8
6 8 10

You might also like