The Wayback Machine - https://web.archive.org/web/20240926000255/https://www.geeksforgeeks.org/arrays-in-java/
Open In App

Arrays in Java

Last Updated : 02 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Arrays are fundamental structures in Java that allow us to store multiple values of the same type in a single variable. They are useful for managing collections of data efficiently. Arrays in Java work differently than they do in C/C++. This article covers the basics and in-depth explanations with examples of array declaration, creation, and manipulation in Java.

Basics of Arrays in Java

Array Declaration

To declare an array in Java, use the following syntax:

type[] arrayName;
  • type: The data type of the array elements (e.g., int, String).
  • arrayName: The name of the array.

Array Declaration Example:

Here’s an example of declaring an integer array:

int[] numbers; // Declaring an integer array
  • This statement declares an array named numbers that will hold integers. Note: The array is not yet initialized.

Create an Array

To create an array, you need to allocate memory for it using the new keyword:

numbers = new int[5]; // Creating an array of 5 integers
  • This statement initializes the numbers array to hold 5 integers. The default value for each element is 0.

Access an Element of an Array

We can access array elements using their index, which starts from 0:

numbers[0] = 10; // Setting the first element of the array
int firstElement = numbers[0]; // Accessing the first element
  • The first line sets the value of the first element to 10. The second line retrieves the value of the first element.

Change an Array Element

To change an element, assign a new value to a specific index:

numbers[0] = 20; // Changing the first element to 20
  • This statement updates the value of the first element from 10 to 20.

Array Length

We can get the length of an array using the length property:

int length = numbers.length; // Getting the length of the array

This retrieves the number of elements in the numbers array, which is 5 in this case.

The above are the basic details of Arrays in Java. Now, if you want to go through the in-depth concepts of Java Arrays, then scroll down below and go through the diagrams, examples, and explanations.

In-depth Concepts of Java Array

Following are some important points about Java arrays. 

Arrays in Java

  • In Java, all arrays are dynamically allocated.
  • Arrays may be stored in contiguous memory [consecutive memory locations].
  • Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++, where we find length using size of.
  • A Java array variable can also be declared like other variables with [] after the data type.
  • The variables in the array are ordered, and each has an index beginning with 0.
  • Java array can also be used as a static field, a local variable, or a method parameter.

An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class, depending on the definition of the array. In the case of primitive data types, the actual values might be stored in contiguous memory locations (JVM does not guarantee this behavior). In the case of class objects, the actual objects are stored in a heap segment. To learn more about Java Array, go through Java programming course here.

Java Arrays

Note: This storage of arrays helps us randomly access the elements of an array [Support Random Access].

Creating, Initializing, and Accessing an Arrays in Java

The general form of array declaration is 

-- type var-name[];
-- type[] var-name;
  • An array declaration has two components: the type and the name.
  • type declares the element type of the array.
  • The element type determines the data type of each element that comprises the array.
  • Like an array of integers, we can also create an array of other primitive data types like char, float, double, etc., or user-defined data types (objects of a class).
  • Thus, the element type for the array determines what type of data the array will hold. 

Example: 

// both are valid declarations
int intArray[];
int[] intArray;
// similar to int we can declare
// byte , short, boolean, long, float
// double, char
// an array of references to objects of
// the class MyClass (a class created by user)
MyClass myClassArray[];
// array of Object
Object[] ao,
// array of Collection
// of unknown type
Collection[] ca;
  • Although the first declaration establishes that int Array is an array variable, no actual array exists.
  • It merely tells the compiler that this variable (int Array) will hold an array of the integer type.
  • To link int Array with an actual, physical array of integers, you must allocate one using new and assign it to int Array. 

Instantiating an Array in Java

When an array is declared, only a reference of an array is created. To create or give memory to the array, you create an array like this: The general form of new as it applies to one-dimensional arrays appears as follows: 

var-name = new type [size];

Here, type specifies the type of data being allocated, size determines the number of elements in the array, and var-name is the name of the array variable that is linked to the array. To use new to allocate an array, you must specify the type and number of elements to allocate.

Example: 

//declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in one
int[] intArray = new int[20];

Note: The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types). Do refer to default array values in Java.

Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.

Array Literal in Java

In a situation where the size of the array and variables of the array are already known, array literals can be used. 

// Declaring array literal 
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
  • The length of this array determines the length of the created array.
  • There is no need to write the new int[] part in the latest versions of Java.

Accessing Java Array Elements using for Loop

Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All the elements of array can be accessed using Java for Loop.

 // accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);

Implementation:

Java
// Java program to illustrate creating an array
// of integers,  puts some values in the array,
// and prints each value to standard output.

class GFG {
    public static void main(String[] args)
    {
        // declares an Array of integers.
        int[] arr;

        // allocating memory for 5 integers.
        arr = new int[5];

        // initialize the first elements of the array
        arr[0] = 10;

        // initialize the second elements of the array
        arr[1] = 20;

        // so on...
        arr[2] = 30;
        arr[3] = 40;
        arr[4] = 50;

        // accessing the elements of the specified array
        for (int i = 0; i < arr.length; i++)
            System.out.println("Element at index " + i
                               + " : " + arr[i]);
    }
}

Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

Complexity of the above method:

Time Complexity: O(n)
Auxiliary Space: O(1)

Types of Arrays in Java

Java supports different types of arrays:

1. Single-Dimensional Arrays

These are the most common type of arrays, where elements are stored in a linear order.

int[] singleDimArray = {1, 2, 3, 4, 5}; // A single-dimensional array
Single Dimensional Array in Java

2. Multi-Dimensional Arrays

Arrays with more than one dimension, such as two-dimensional arrays (matrices).

int[][] multiDimArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}; // A 2D array (matrix)

You can also access java arrays using for each loops

Arrays of Objects in Java

An array of objects is created like an array of primitive-type data items in the following way. 

Student[] arr = new Student[5]; //Student is a user-defined class

Syntax:

-- data type[] arrName;
-- datatype arrName[];
-- datatype [] arrName;

Example of Arrays of Objects

Example 1:

Below is the implementation of the above mentioned topic:

Java
import java.io.*;

class GFG {
    public static void main (String[] args) {
       
      int [] arr=new int [4];
      // 4 is the size of arr
      
      System.out.println("Array Size:"+arr.length);
    }
}

Output
Array Size:4
  • The Student Array contains five memory spaces each of the size of Student class in which the address of five Student objects can be stored.
  • The Student objects have to be instantiated using the constructor of the Student class, and their references should be assigned to the array elements in the following way. 

Example 2:

Below is the implementation of the above mentioned topic:

Java
// Java program to illustrate creating
//  an array of objects

class Student {
    public int roll_no;
    public String name;
    Student(int roll_no, String name)
    {
        this.roll_no = roll_no;
        this.name = name;
    }
}

// Elements of the array are objects of a class Student.
public class GFG {
    public static void main(String[] args)
    {
        // declares an Array of Student
        Student[] arr;

        // allocating memory for 5 objects of type Student.
        arr = new Student[5];

        // initialize the first elements of the array
        arr[0] = new Student(1, "aman");

        // initialize the second elements of the array
        arr[1] = new Student(2, "vaibhav");

        // so on...
        arr[2] = new Student(3, "shikar");
        arr[3] = new Student(4, "dharmesh");
        arr[4] = new Student(5, "mohit");

        // accessing the elements of the specified array
        for (int i = 0; i < arr.length; i++)
            System.out.println("Element at " + i + " : "
                               + arr[i].roll_no + " "
                               + arr[i].name);
    }
}

Output
Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit

Complexity of the above method:

Time Complexity: O(n)
Auxiliary Space : O(1)

Example 3:

An array of objects is also created like : 

Java
// Java program to illustrate creating
//  an array of objects
  
class Student
{
   
    public String name;
    Student(String name)
    {
        this.name = name;
    }
      @Override
    public String toString(){
        return name;
    }
}
  
// Elements of the array are objects of a class Student.
public class GFG
{
    public static void main (String[] args)
    {
           // declares an Array and initializing  the elements of the array
        Student[] myStudents = new Student[]{new Student("Dharma"),new Student("sanvi"),new Student("Rupa"),new Student("Ajay")};
  
        // accessing the elements of the specified array
        for(Student m:myStudents){    
            System.out.println(m);
        }
    }
}

Output
Dharma
sanvi
Rupa
Ajay

What happens if we try to access elements outside the array size?

JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of an array.

Below code shows what happens if we try to access elements outside the array size:

Java
// Code for showing error "ArrayIndexOutOfBoundsException"

public class GFG {
    public static void main(String[] args)
    {
        int[] arr = new int[4];
        arr[0] = 10;
        arr[1] = 20;
        arr[2] = 30;
        arr[3] = 40;

        System.out.println(
            "Trying to access element outside the size of array");
        System.out.println(arr[5]);
    }
}

Output

Trying to access element outside the size of array
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4
at GFG.main(GFG.java:13)

Example (Iterating the array):

Java
public class GFG {
    public static void main(String[] args)
    {
        int[] arr = new int[2];
        arr[0] = 10;
        arr[1] = 20;

        for (int i = 0; i < arr.length; i++)
            System.out.println(arr[i]);
    }
}

Output
10
20

Complexity of the above method:

Time Complexity: O(n),here n is size of array.
Auxiliary Space: O(1), since no extra space required.

Multidimensional Arrays in Java

Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other arrays. These are also known as Jagged Arrays. A multidimensional array is created by appending one set of square brackets ([]) per dimension. 

Syntax:

There are 2 methods to declare Java Multidimensional Arrays as mentioned below:

datatype [][] arrayrefvariable;
datatype arrayrefvariable[][];
Multi-Dimensional Array

Declaration:

int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array

Java Multidimensional Arrays Examples

Example 1:

Java
// Java Program to demonstrate
// Java Multidimensional Array
import java.io.*;

// Driver class
class GFG {
    public static void main(String[] args)
    {
        // Syntax
        int[][] arr = new int[3][3];
        // 3 row and 3 column

          // Number of Rows
        System.out.println("Number of Rows:"+
                           arr.length);
      
          // Number of Columns
        System.out.println("Number of Columns:"+
                           arr[0].length);
    }
}

Output
Number of Rows:3
Number of Columns:3

Example 2:

Java
// Java Program to Multidimensional Array

// Driver Class
public class multiDimensional {
      // main function
    public static void main(String args[])
    {
        // declaring and initializing 2D array
        int arr[][]
            = { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };

        // 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
2 7 9 
3 6 1 
7 4 2 

Passing Arrays to Methods

Like variables, we can also pass arrays to methods. For example, the below program passes the array to method sum to calculate the sum of the array’s values.

Java
// Java program to demonstrate
// passing of array to method

public class Test {
    // Driver method
    public static void main(String args[])
    {
        int arr[] = { 3, 1, 2, 5, 4 };

        // passing array to method m1
        sum(arr);
    }

    public static void sum(int[] arr)
    {
        // getting sum of array values
        int sum = 0;

        for (int i = 0; i < arr.length; i++)
            sum += arr[i];

        System.out.println("sum of array values : " + sum);
    }
}

Output
sum of array values : 15

Complexity of the above method:

Time Complexity: O(n)
Auxiliary Space : O(1)

Returning Arrays from Methods

As usual, a method can also return an array. For example, the below program returns an array from method m1

Java
// Java program to demonstrate
// return of array from method

class Test {
    // Driver method
    public static void main(String args[])
    {
        int arr[] = m1();

        for (int i = 0; i < arr.length; i++)
            System.out.print(arr[i] + " ");
    }

    public static int[] m1()
    {
        // returning  array
        return new int[] { 1, 2, 3 };
    }
}

Output
1 2 3 

Complexity of the above method:

Time Complexity: O(n) 
Auxiliary Space : O(1)

Class Objects for Arrays

Every array has an associated Class object, shared with all other arrays with the same component type. 

Java
// Java program to demonstrate
// Class Objects for Arrays

class Test {
    public static void main(String args[])
    {
        int intArray[] = new int[3];
        byte byteArray[] = new byte[3];
        short shortsArray[] = new short[3];

        // array of Strings
        String[] strArray = new String[3];

        System.out.println(intArray.getClass());
        System.out.println(
            intArray.getClass().getSuperclass());
        System.out.println(byteArray.getClass());
        System.out.println(shortsArray.getClass());
        System.out.println(strArray.getClass());
    }
}

Output
class [I
class java.lang.Object
class [B
class [S
class [Ljava.lang.String;

Explanation of the above method:

  • The string “[I” is the run-time type signature for the class object “array with component type int.”
  • The only direct superclass of an array type is java.lang.Object.
  • The string “[B” is the run-time type signature for the class object “array with component type byte.”
  • The string “[S” is the run-time type signature for the class object “array with component type short.”
  • The string “[L” is the run-time type signature for the class object “array with component type of a Class.” The Class name is then followed.

Java Array Members

Now, as you know that arrays are objects of a class, and a direct superclass of arrays is a class Object. The members of an array type are all of the following: 

  • The public final field length contains the number of components of the array. Length may be positive or zero.
  • All the members are inherited from class Object; the only method of Object that is not inherited is its clone method.
  • The public method clone() overrides the clone method in class Object and throws no checked exceptions.

Arrays Types and Their Allowed Element Types

Array TypesAllowed Element Types
Primitive Type ArraysAny type which can be implicitly promoted to declared type.
Object Type ArraysEither declared type objects or it’s child class objects.
Abstract Class Type ArraysIts child-class objects are allowed.
Interface Type ArraysIts implementation class objects are allowed.

Cloning of Single-Dimensional Array in Java

When you clone a single-dimensional array, such as Object[], a shallow copy is performed. This means that the new array contains references to the original array’s elements rather than copies of the objects themselves. A deep copy occurs only with arrays containing primitive data types, where the actual values are copied.

Below is the implementation of the above method:

Java
// Java program to demonstrate
// cloning of one-dimensional arrays

class Test {
    public static void main(String args[])
    {
        int intArray[] = { 1, 2, 3 };

        int cloneArray[] = intArray.clone();

        // will print false as shallow copy is created
        System.out.println(intArray == cloneArray);

        for (int i = 0; i < cloneArray.length; i++) {
            System.out.print(cloneArray[i] + " ");
        }
    }
}

Output
false
1 2 3 

Explanation of the above Program:

  • In this example, intArray and cloneArray are not the same object (intArray == cloneArray is false), but they share the same contents because primitive values are deeply copied.
  • For arrays containing objects, the references are copied, so the objects themselves are not duplicated.

Clone-of-Array

Cloning Multidimensional Array in Java

A clone of a multi-dimensional array (like Object[][]) is a “shallow copy,” however, which is to say that it creates only a single new array with each element array a reference to an original element array, but subarrays are shared. 

Java
// Java program to demonstrate
// cloning of multi-dimensional arrays

class Test {
    public static void main(String args[])
    {
        int intArray[][] = { { 1, 2, 3 }, { 4, 5 } };

        int cloneArray[][] = intArray.clone();

        // will print false
        System.out.println(intArray == cloneArray);

        // will print true as shallow copy is created
        // i.e. sub-arrays are shared
        System.out.println(intArray[0] == cloneArray[0]);
        System.out.println(intArray[1] == cloneArray[1]);
    }
}

Output
false
true
true

Multidimensional-Array-Clone

Advantages of Java Arrays

  • Efficient Access: Accessing an element by its index is fast and has constant time complexity, O(1).
  • Memory Management: Arrays have fixed size, which makes memory management straightforward and predictable.
  • Data Organization: Arrays help organize data in a structured manner, making it easier to manage related elements.

Disadvantages of Java Arrays

  • Fixed Size: Once an array is created, its size cannot be changed, which can lead to memory waste if the size is overestimated or insufficient storage if underestimated.
  • Type Homogeneity: Arrays can only store elements of the same data type, which may require additional handling for mixed types of data.
  • Insertion and Deletion: Inserting or deleting elements, especially in the middle of an array, can be costly as it may require shifting elements.

Frequently Asked Questions – Java Arrays

How can we initialize an array in Java?

Arrays in Java can be initialized in several ways:

  • Static Initialization: int[] arr = {1, 2, 3};
  • Dynamic Initialization: int[] arr = new int[5];
  • Initialization with a loop: for (int i = 0; i < arr.length; i++) { arr[i] = i + 1; }

Can we use an array of primitive types in Java?

Yes, Java supports arrays of primitive types such as int, char, boolean, etc., as well as arrays of objects.

How are multidimensional arrays represented in Java?

Multidimensional arrays in Java are represented as arrays of arrays. For example, a two-dimensional array is declared as int[][] array, and it is effectively an array where each element is another array.

Can we change the size of an array after it is created in Java?

No, the size of an array in Java cannot be changed once it is initialized. Arrays are fixed-size. To work with a dynamically sized collection, consider using classes from the java.util package, such as ArrayList.

Can we specify the size of an array as long in Java?

No, we cannot specify the size of an array as long. The size of an array must be specified as an int. If a larger size is required, it must be handled using collections or other data structures.

What is the direct superclass of an array in Java?

The direct superclass of an array in Java is Object . Arrays inherit methods from the Object class, including toString(), equals(), and hashCode().

Which interfaces are implemented by arrays in Java?

All arrays in Java implement two interfaces:

  • Cloneable: Allows the array to be cloned using the clone() method.
  • java.io.Serializable: Enables arrays to be serialized.


Previous Article
Next Article

Similar Reads

Java.util.Arrays.parallelSetAll(), Arrays.setAll() in Java
Prerequisites : Lambda Expression in Java 8IntUnaryOperator Interface parallelSetAll and setAll are introduced in Arrays class in java 8. parallelSetAll(): It set all the element in the specified array in parallel by the function which compute each element. Syntax: public static void parallelSetAll(double[] arr, IntToDoubleFunction g) Parameters :
5 min read
Difference Between Arrays.toString() and Arrays.deepToString() in Java
The deepToString() method of the Arrays class returns the string representation of the deep contents of the specified Object array. Unlike Arrays. toString(), if the array contains other arrays as elements, the string representation includes their contents, and so on. Arrays.toString(): Returns a string representation of the contents of the specifi
3 min read
How to Sort an Arrays of Object using Arrays.sort()
To sort the array of objects in both ascending and descending order in Java, we can use the Arrays.sort() method with the Comparator. In this article, we will learn how to sort an array of objects using Arrays.sort(). Sorting an Array of ObjectWith Array of Object what it really means is an array storing any type of object can be Integer, String or
3 min read
Java.util.Arrays.equals() in Java with Examples
Today we are going to discuss the simplest way to check whether two arrays are equal or not. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two arra
4 min read
Java.util.Arrays.deepEquals() in Java
Arrays.deepEquals() is used to check whether two arrays of single dimensional or multi-dimensional arrays are equal or not. It can compare two nested arrays (i.e. multidimensional array), irrespective of its dimension. Two array references are considered deeply equal if both are null, or if they refer to arrays that contain the same number of eleme
4 min read
Java.util.Arrays.copyOfRange() in Java
This method creates a copy of elements, within a specified range of the original array.Syntax : public static int[] copyOfRange(int[] original_array, int from_index, int to_index) original_array : Array to be copied fromfrom_index : Starting index of range to be copiedto_end : the final index of the range to be copied, exclusive. (This index may li
4 min read
Java.util.Arrays.parallelPrefix in Java 8
Prerequisites: Lambda Expressions in Java 8Stream In Java The parallelPrefix method is introduced to the Arrays class in java 8. The parallelPrefix method performs a given mathematical function on the elements of the array cumulatively, and then modifies the array concurrently. Syntax : parallelPrefix(int[] array, IntBinaryOperator op) Parameters :
6 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java | Arrays | Question 1
Which of the following is FALSE about arrays in Java? (A) A java array is always an object (B) Length of array can be changed after creation of array (C) Arrays in Java are always allocated on heap Answer: (B)Explanation: In Java, arrays are objects, they have members like length. The length member is final and cannot be changed. All objects are al
1 min read
Java | Arrays | Question 2
Predict the output? // file name: Main.java public class Main { public static void main(String args[]) { int arr[] = {10, 20, 30, 40, 50}; for(int i=0; i &lt; arr.length; i++) { System.out.print(&quot; &quot; + arr[i]); } } } (A) 10 20 30 40 50 (B) Compiler Error (C) 10 20 30 40 Answer: (A) Explanation: It is a simple program where an array is firs
1 min read
Java | Arrays | Question 3
class Test { public static void main(String args[]) { int arr[2]; System.out.println(arr[0]); System.out.println(arr[1]); } } (A) 0 0 (B) garbage value garbage value (C) Compiler Error (D) Exception Answer: (C) Explanation: In Java, it is not allowed to put the size of the array in the declaration because an array declaration specifies only the ele
1 min read
Java | Arrays | Question 4
class Test { public static void main(String args[]) { int arr[] = new int[2]; System.out.println(arr[0]); System.out.println(arr[1]); } } (A) 0 0 (B) garbage value garbage value (C) Compiler Error (D) Exception Answer: (A) Explanation: Java arrays are first class objects and all members of objects are initialized with default values like o, null.Qu
1 min read
Java | Arrays | Question 5
public class Main { public static void main(String args[]) { int arr[][] = new int[4][]; arr[0] = new int[1]; arr[1] = new int[2]; arr[2] = new int[3]; arr[3] = new int[4]; int i, j, k = 0; for (i = 0; i &lt; 4; i++) { for (j = 0; j &lt; i + 1; j++) { arr[i][j] = k; k++; } } for (i = 0; i &lt; 4; i++) { for (j = 0; j &lt; i + 1; j++) { System.out.p
1 min read
Java | Arrays | Question 6
Output of following Java program? class Test { public static void main (String[] args) { int arr1[] = {1, 2, 3}; int arr2[] = {1, 2, 3}; if (arr1 == arr2) System.out.println(&quot;Same&quot;); else System.out.println(&quot;Not same&quot;); } } (A) Same (B) Not Same Answer: (B) Explanation: See https://www.geeksforgeeks.org/compare-two-arrays-java/Q
1 min read
Java | Arrays | Question 7
Output of following Java program? import java.util.Arrays; class Test { public static void main (String[] args) { int arr1[] = {1, 2, 3}; int arr2[] = {1, 2, 3}; if (Arrays.equals(arr1, arr2)) System.out.println(&quot;Same&quot;); else System.out.println(&quot;Not same&quot;); } } (A) Same (B) Not Same Answer: (A) Explanation: See https://www.geeks
1 min read
Java | Arrays | Question 8
class Test { public static void main (String[] args) { int arr1[] = {1, 2, 3}; int arr2[] = {1, 2, 3}; if (arr1.equals(arr2)) System.out.println(&quot;Same&quot;); else System.out.println(&quot;Not same&quot;); } } (A) Same (B) Not same Answer: (B) Explanation: arr1.equals(arr2) is same as (arr1 == arr2) Quiz of this Question
1 min read
Difference between Stream.of() and Arrays.stream() method in Java
Arrays.stream() The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Example: Java Code // Java program to demonstrate Arrays.stream() method import java.uti
5 min read
Flatten a Stream of Arrays in Java using forEach loop
Given a Stream of Arrays in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: arr[][] = {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: arr[][] = {{'G', 'e', 'e', 'k', 's'}, {'F', 'o', 'r'}} Output: [G, e, e, k, s, F, o, r] Approach: Get the Arrays in the form of 2D array. Create an
3 min read
Arrays stream() method in Java
stream(T[] array) The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Syntax: public static &lt;T&gt; Stream&lt;T&gt; stream(T[] array) Parameters: This met
3 min read
Arrays asList() method in Java with Examples
The asList() method of java.util.Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess. Tip: This runs in O(1) time. Syntax: public static List
3 min read
util.Arrays vs reflect.Array in Java with Examples
Array class in java.lang.reflect package is a part of the Java Reflection. This class provides static methods to create and access Java arrays dynamically. It is a final class, which means it can’t be instantiated or changed. Only the methods of this class can be used by the class name itself. On the other hand, Arrays class in java.util package is
2 min read
Check whether array has all identical elements using Arrays.asList() and HashSet in Java
Given an array arr[] of N elements, the task is to check whether the array have all same (identical) elements or not without using the loop. If all elements are same then print Yes otherwise print No. Examples: Input: arr[] = {2, 2, 2, 2, 2} Output: Yes The given array has all identical elements i.e. 2. Input: arr[] = {2, 3, 3, 3, 3, 2, 2} Output:
2 min read
Java ArrayList of Arrays
ArrayList of arrays can be created just like any other objects using ArrayList constructor. In 2D arrays, it might happen that most of the part in the array is empty. For optimizing the space complexity, Arraylist of arrays can be used. ArrayList&lt;String[ ] &gt; geeks = new ArrayList&lt;String[ ] &gt;(); Example: Input :int array1[] = {1, 2, 3},
2 min read
Sorting Elements of Arrays and Wrapper Classes that Already Implements Comparable in Java
Java provides the Comparable interface to sort objects using data members of the class. The Comparable interface contains only one method compareTo() that compares two objects to impose an order between them. It returns a negative integer, zero, or positive integer to indicate if the input object is less than, equal to, or greater than the current
4 min read
String Arrays in Java
In programming, an array is a collection of the homogeneous types of data stored in a consecutive memory location and each data can be accessed using its index. In the Java programming language, we have a String data type. The string is nothing but an object representing a sequence of char values. Strings are immutable in java. Immutable means stri
5 min read
Where is the memory allocated for Arrays in Java?
Each time an array is declared in the program, contiguous memory is allocated to it. Array base address: The address of the first array element is called the array base address. Each element will occupy the memory space required to accommodate the values for its type, i.e.; depending on the data type of the elements, 1, 4, or 8 bytes of memory are
3 min read
25 Interesting Facts about Arrays in Java
Java arrays are the workhorses of many programs, offering a structured way to store and manipulate data. While arrays are a fundamental concept, there are intriguing facts that developers may not be aware of for Java Arrays. In this blog post, we'll explore 25 interesting facts about arrays in Java, shedding light on their nuances and capabilities.
8 min read
Compare Two Arrays in Java
While comparing two arrays we can not use "==" operator as it will compare the addresses of the memory block to which both the arrays are pointing. If we want to compare the elements inside the array we need to figure out other ways instead of using arithmetic operators. As we all know arrays data structures possess the property of containing eleme
6 min read
Arrays class in Java
The Arrays class in java.util package is a part of the Java Collection Framework. This class provides static methods to dynamically create and access Java arrays. It consists of only static methods and the methods of Object class. The methods of this class can be used by the class name itself. The class hierarchy is as follows: java.lang.Object ? j
13 min read
Arrays.fill() in Java with Examples
java.util.Arrays.fill() method is in java.util.Arrays class. This method assigns the specified data type value to each element of the specified range of the specified array. Syntax: // Makes all elements of a[] equal to "val" public static void fill(int[] a, int val) // Makes elements from from_Index (inclusive) to to_Index // (exclusive) equal to
3 min read
Article Tags :
Practice Tags :