Java Arrays

Programming languages or concepts
0

 Java Arrays

In this tutorial, we will learn about java array and how it work in Java. We will learn to declaration, initialization, and access array elements with the help of examples.

Java Arrays

An array is a collection of same types of elements.

An array is used to store multiple values ​​in a single variable instead of declaring separate variables for each value.

Normally, an array is a collection of similar elements to which memory space is attached / contiguous memory location.

A Java array is an object that contains elements of the same data type. It is a data structure where we store the same elements. We can only keep a fixed set of elements in a Java array.

Java arrays is a index-based, in java array the first element stored on the 0th index, the 2nd element is stored on the 1st index and so on

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the sizeof operator.

An array in Java is a set of identical-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays. 


In Java, all arrays are dynamically allocated.

Since an array is an object in Java, we can find their length using the object property length. This is different from C/C++, where we find length using sizeof.

Java array variables can also be declared as other variables with [] after the data type.

The variables in the array are sorted and the index of each starts from 0.

Java arrays can also be used as static fields, local variables or method parameters.

The size of the array should be specified by int or short value and should not be long.

An array type is a direct superclass object.

Each array type applies Cloneable and java.io.Serializable interfaces.


An array can have primitive (int, four, etc.) and object (or non-primitive) references to the class according to the definition of an array. In the case of primitive data types, the actual values ​​are stored in the attached memory locations. In the case of class objects, the actual objects are stored in the heap segment.


Arrays in Java

For example, if we want to store the names of 1000 peoples then we can create an array of the string type that can store 1000 names.


String[] arr = new String[1000];


We have now declared a variable ( arr ) that holds an array of strings types. To insert values to the variable, we can use an array literal - place the values in a comma - separated list, inside curly braces as showing in following examples


String[] languages = {"C", "Cpp", "Java", "python"};

To create an array of integers, you could write:


int[] num = {97, 98, 100, 99};


Access the Elements of an Array

we can access an array elements by using referring to the index number.


This statement accesses the value of the first element in programming languages:


Example

String[] languages = {"C", "Cpp", "Java", "python"};

System.out.println(languages[2]);


outpout:

                Java



Change an Array Element

To change the value of a especial element, with refer to the index number:


Example

 languages[0] = "C#";

Example

String[] languages = {"C", "Cpp", "Java", "python"};

languages[0] = "C#";

System.out.println( languages[0] );


How to declare an array in Java?

In Java, here is how we can declare an array.


dataType[] arrayName;

dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects

arrayName - it is an identifier

For example,


int[] rollNumber;



How to Initialize Arrays in Java?

In Java, we can also initialize arrays during declaration. 

For example,


//declare and initialize and array at same time

int[] numbers = {2, 4, 6, 8, 10};

Now, we have created an array named as numbers and initialized it with the values inside the curly brackets and the values are Separate using commas.



How to Access Elements of an Array in Java?

We can access the elements of an array using the index numbers. 

below is the syntax for accessing elements of an array,


// access array elements

array[index]

Let's see an example of accessing array elements using index numbers.


Example: Access Array Elements

class Main {

 public static void main(String[] args) {

  

   // create an array

   int[] numbers = {2, 4, 6, 8, 10};


   // access each array elements

   System.out.println("Accessing Elements of Array:");

   System.out.println("First Element: " + numbers[0]);

   System.out.println("Second Element: " + numbers[1]);

   System.out.println("Third Element: " + numbers[2]);

   System.out.println("Fourth Element: " + numbers[3]);

   System.out.println("Fifth Element: " + numbers[4]);

 }

}



Looping Through Array Elements

In Java, we can also loop through each element of the array. For example,


Example: Using For Loop

class Main {

 public static void main(String[] args) {

  

   // create an array

   int[] numbers = {2, 4, 6,8,10};


   // loop through the array

   // using for loop

   System.out.println("Using for Loop:");

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

     System.out.println(numbers[i]);

   }

 }

}



Multidimensional Arrays

Arrays we have mentioned till now are called one-dimensional arrays. However, we can declare multidimensional arrays in Java.


A multidimensional array is an array of arrays. That is, each element of a multidimensional array is an array itself. For example,


double[][] matrix = {{1.2, 4.3, 4.0}, 

      {4.1, -1.1}

};



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];  

Example of Java Array

Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array.


//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]);  

}

}  



Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:


int a[]={33,3,4,5};//declaration, instantiation and initialization  

Let's see the simple example to print this array.



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]);  

    }

}  



Multidimensional Array in Java

In such case, data is stored in row and column based index (also known as matrix form).


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 of Multidimensional Java Array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional 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();  

                    }  

          }

}  


Tags:

Post a Comment

0Comments

Post a Comment (0)
close