Java Array – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Wed, 11 Oct 2023 19:15:50 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Java Array – Java2Blog https://java2blog.com 32 32 Create Array from 1 to n in Java https://java2blog.com/create-array-from-1-to-n-java/?utm_source=rss&utm_medium=rss&utm_campaign=create-array-from-1-to-n-java https://java2blog.com/create-array-from-1-to-n-java/#respond Tue, 25 Oct 2022 12:59:47 +0000 https://java2blog.com/?p=20974 Introduction

In this article, we will look at How to Create an Array from 1 to n in Java. We need to Initialize Arrays in a sequence of values ranging from 1 to number N.

Knowing how we can initialize arrays in different ways will give us deeper insights into Array in Java and allow us to gain more experience with handling arrays under critical situations. Let us have a quick peek at the concept of Arrays in Java.

Array in Java

Arrays are a collection of homogenous data i.e. stores values of the same data type. In Java, we create arrays with the new keyword and allocate memory dynamically similar to the concept of Objects in Java. They can be of primitive type or an Object type.

Syntax to create Array:

int arr[] = new int[10];

Here, we create an array arr of type int and size 10.

Create Array from 1 to N in Java

Now, let us discuss in detail different ways to Create Arrays from 1 to N in Java and initialize them with a sequence of values.

Using Simple For loop in Java

When it comes to initializing arrays with a sequence of values, what better than a For loop to perform an action in a sequence.

Important points to note:

  • Use for loop and initialize each index of our array with the value: index + 1
  • This ensures that when iterating over the current index the array fills its values from 1 to a given number N.
  • Print the arrays using the Arrays.toString() method, which gives a String representation of an array object.

Let us look at the code snippet.

import java.util.*;

public class Java2Blog {

    public static void main(String[] args) {

    System.out.println("Enter Input N:");
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();

    //Create Array of Size N
    int arr[] = new int[n];
    for(int i=0;i<n;i++)
    {
        //we fill array with values starting from 1 to 10
        arr[i] = i+1;
    }
    System.out.println("Array with values 1 to "+n);
    System.out.println(Arrays.toString(arr));

    }

}

Output:

Using IntStream.range() method of Stream API in Java

With the advent of Java 8, the Stream API was introduced in java which brought into the picture the aspects and functionalities of Functional programming. This reduced code redundancy as well.

We will use the range() method of IntStream class that generates a sequence of increasing values between start and end of Integral values which is exclusive of the range value.

Important points to note:

  • If we want to create a stream of numbers from 1 to 10 we need to pass values into the range() method as -> range(1,11).
  • This will create a stream of integers that can be returned as an array using the toArray() method.

Note: JDK version 8 or higher must be installed to locate this approach.

Let us look at the code.

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;

public class Java2Blog {

    public static void main(String[] args) {

    System.out.println("Enter Input N:");
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();

    //Stream Range end = n+1 to include value n in array
    int arr[] = IntStream.range(1, n+1).toArray();;

    System.out.println("Array with values 1 to "+n+" using IntStream.range() method");
    System.out.println(Arrays.toString(arr));

    }

}

Output:

Using IntStream.rangeClosed() method of Stream API in Java

The rangeClosed() method is a variation of the range() method of the IntStream class as shown in the above example. It has similar properties to its counterpart. The only difference is that the method creates a Stream of Integers inclusive of the range value.

Hence, if we want to create a stream of numbers from 1 to 10 we need to pass values into the rangeClosed() method as -> rangeClosed(1,10).

Let us look at the code snippet for this method.

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;

public class Java2Blog {

    public static void main(String[] args) {

    System.out.println("Enter Input N:");
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();

    //Stream Range end = n to include value n
    int arr[] = IntStream.rangeClosed(1,n).toArray();;

    System.out.println("Array with values 1 to "+n+" using IntStream.rangeClosed() method");
    // Printing String Representation of Array.
    System.out.println(Arrays.toString(arr));

    }

}

Output:

Using IntStream.iterate() method of Stream API in Java

The IntStream class provides the iterate() method with the same functionality as a for-loop. It iterates over a given value and generates a sequence of numbers in increasing order.

Important points to note:

  • If we need to generate a sequence of values we call the IntStream.iterate() method and we determine the increment value for the sequence like IntStream.iterate( 1, i -> i + 1), where 1 indicates the starting number of the sequence.
  • This ensures that the values follow a sequence. Now, to generate the number up to a certain limit we use the limit() method with the iterate() method sequence as -> limit(n), where n is the input size.
  • Next, we collect the generated sequence of integers using the toArray() method. The IntStream class by default returns an Integer []
    i.e. an Integer Wrapper class type array so there is no need to typecast the array.

Now, let us have a look at the code implementation for this approach as well.

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;

public class Java2Blog {

    public static void main(String[] args) {

        System.out.println("Enter Input N:");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        // Determine increment for i = i+1 then limit output to n
        int[] arr = IntStream.iterate(1, i -> i + 1).limit(n).toArray();

        System.out.println("Array with values 1 to "+n+" using IntStream.iterate() method");
        // Printing String Representation of Array.
        System.out.println(Arrays.toString(arr));

    }

}

Output:

In Java 9, the overloaded version of the iterate() method was introduced that provided an argument for the predicate to determine when the stream must terminate or to limit the sequence stream.

Features of this iterate() method in Java 9:

  • This eliminates the concern to use the limit() method as we now add the predicate to limit the number of elements to n in the stream.
  • Hence, to use this iterate() method with the limiting functionality we define it like this: iterate( 1, i  -> i <= n, i -> i+1), where 1 indicates the starting number of the sequence.

Let us have a quick look at this code snippet as well.

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;

public class Java2Blog {

public static void main(String[] args) {

System.out.println("Enter Input N:");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();

//Adding predicate to terminate the stream when it reaches value n
int[] arr = IntStream.iterate(1, i -> i<=n, i -> i + 1).toArray();

System.out.println("Array with values 1 to "+n+" using Java 9 - IntStream.iterate() method");
// Printing String Representation of Array.
System.out.println(Arrays.toString(arr));

}

}

Output:

Using the Stream class of Stream API in Java

We can also use the Stream class as an alternative to the above-discussed ways with the IntStream class. We can use the iterate() method of the Stream class in the same way we use the IntStream.iterate() method.

Important points to note:

  • We will use an array of Integer Wrapper class type then use the limit() method to terminate the stream and collect the stream into an array using the toArray() method.
  • The toArray() method of the Stream class returns an Object[] i.e. Object class type array by default. Hence, It becomes necessary to typecast this Object[] into an Integer[] type.
  • We typecast the generated stream to Integer[] type using the toArray() method like this: toArray(Integer[]::new) . This converts the returned array to an Integer array.

Let us look at the code implementation below.

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Stream;

public class Java2Blog {

    public static void main(String[] args) {

        System.out.println("Enter Input N:");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        //We iterate over stream and return Integer type array by type casting with new keyword
        Integer[] arr = Stream.iterate(1, i -> i + 1).limit(n).toArray(Integer[]::new);

        System.out.println("Array with values 1 to "+n+" using Stream API: ");
        // Printing String Representation of Array.
        System.out.println(Arrays.toString(arr));

    }

}

Output:

Using Arrays.setAll() method in Java

In Java 8, the setAll() method was introduced in the Arrays class. It is a very useful method to set the array elements with sequential integers or a fixed value through the entire length of the array.

Important points to note:

  • It accepts two arguments – the array and the predicate that computes the value for each index and returns nothing as it is a setter method.
  • Using the setAll() method, we can set the array with a fixed value as well. Here we write a predicate that generates a sequence of integers and call the method as setAll(arr, i -> i+1), where arr is the array to fill.

Let us look at the code implementation for this approach.

import java.util.Arrays;
import java.util.Scanner;

public class Java2Blog {

    public static void main(String[] args) {

        System.out.println("Enter Input N:");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        // we define an array of size n.
        int arr[] = new int [n];
        //We call the setall() method pass the array and the condition for sequence
        Arrays.setAll(arr, i -> i +1);

        System.out.println("Array with values 1 to "+n+" using Arrays.setAll() method: ");
        // Printing String Representation of Array.
        System.out.println(Arrays.toString(arr));

    }

}

Output:

Using Eclipse Collections Framework in Java

The Eclipse Collections Framework is a powerful framework that provides its own Collection framework in Java. It provides powerful and reusable Java components, dependencies and API’s that we can embed into our applications and programs.

Here, we can use the Interval class of org.eclipse.collections.impl library by importing its dependency into our Java application. For ease, we will use the JAR file component of the Eclipse Collections Impl package.

To setup the JAR file component for this package we follow these steps:

  1. Download the Eclipse Collection Main Library JAR and the Eclipse Collections API JAR component.
  2. Download only the JAR component from the above two links, as we need both jars to import two components into our Java application(Version might vary according to the latest updates).
  3. Go to your IDE (Eclipse EE/IntelliJ) then right-click on the package name and go to -> Configure Build Path.
  4. Go to libraries -> Click on Classpath -> Add External JAR’s.
  5. Select both the Eclipse Collection Main Library and API JAR file – eclipse collections-11.1.0 and eclipse-collections-api-11.1.0, then click Apply and close. 

The JAR will then be added to your Java Application after this we can just import the required classes from this package. Now, let us look into the implementation.

We need to basically import two classes :

  1. LazyIterable class from Eclipse Collections API JAR. Package specification – import org.eclipse.collections.api.LazyIterable 
  2. Interval class from Eclipse Collections Main Library. Package specification – import org.eclipse.collections.impl.list.Interval;

Important Points for implementation:

  • We will use the oneTo() method of the Interval class to generate a sequence of increasing numbers. It accepts only one argument – the limiting end of the sequence.
  • We will provide N, the array size as an input to this method.
  • The method returns a collection of type Interval which we can convert to an array using the toArray() method but we need to use Integer Wrapper class type array i.e. Integer[].

Let us look at the implementation in the code.

import java.util.Arrays;
import java.util.Scanner;
import org.eclipse.collections.api.LazyIterable;
import org.eclipse.collections.impl.list.Interval;


public class Java2Blog {

	public static void main(String[] args) {
	
		System.out.println("Enter Input N:");
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		// Call the method that return array of sequence
		Integer arr[] = makeSequence(n);
		
		System.out.println("Array with values 1 to "+n+" using Eclipse Collection API : ");
		// Printing String Representation of Array.
		System.out.println(Arrays.toString(arr));
		
	}
	
	public static Integer[] makeSequence(int n) {
		// use the oneTo method and convert it to Array
	    return Interval.oneTo(n).toArray();
	}

}

Output:

Using Google Guava Library in Java

The Google Guava API Library is an open-source set of common core Java libraries, mainly developed by Google engineers that provide powerful and reusable Java components and dependencies that we can embed into our Java applications.

You can use the Google Guava Library on any maven project as below.
Here is the dependency which you need to add for guava in pom.xml.


			com.google.guava
			guava
			29.0-jre
		

Here, we will use the combination of RangeDiscreteDomainContiguousSet, and Ints from Guava or from the Google Common package to create a sequence of integers and initialize our array with it up to a given value N.

We can import the dependency as well but here we will use the JAR component for clarity.

Once we have added the dependency, we can import the required classes from this package. We basically need to import four classes from this package.

  1. ContiguousSet class
  2. DiscreteDomain class
  3. Range class
  4. Ints class.

Important points for implementation:

  • Create a Contiguous Set or a sequence of integers using the ContiguousSet.create() method wherein we can specify the range with a start and end value using the Range.closed() method.
  • Pass the start and end value to the closed() method which is exclusive of the end value like this: Range.closed(1, n), where 1 is the start of the sequence and n is the end.
  • Specify type of value or the Domain using the DiscreteDomain.integers() method in ContiguousSet.create()method
  • Get our Contiguous Set and then convert it into an array using the Ints.toArray() method by passing the set as an argument.

Now let us look at the implementation of this approach.

import java.util.Arrays;
import java.util.Scanner;
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.Range;
import com.google.common.primitives.Ints;

public class Java2Blog {

	public static void main(String[] args) {
	
		System.out.println("Enter Input N:");
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		// Create Contiguous Set
		ContiguousSet conSet= ContiguousSet.create(Range.closed(1, n), DiscreteDomain.integers());
		// then convert to array
		int arr[] = Ints.toArray(conSet);
		
		System.out.println("Array with values 1 to "+n+" using Google Guava Library : ");
		// Printing String Representation of Array.
		System.out.println(Arrays.toString(arr));
		
	}

}

Output:

That’s all for the article we had a look over 8 ways to Create an Array from 1 to N in Java with working examples from basic to advanced levels. You can try out these examples in your local IDE and follow the explanations in detail.

Feel free to reach out to us for any suggestions/doubts.

 

]]>
https://java2blog.com/create-array-from-1-to-n-java/feed/ 0
How to Print 2D Array in Java https://java2blog.com/print-2d-array-java/?utm_source=rss&utm_medium=rss&utm_campaign=print-2d-array-java https://java2blog.com/print-2d-array-java/#respond Mon, 19 Sep 2022 13:16:16 +0000 https://java2blog.com/?p=20474 Introduction

In this article, we get a look on How to print a 2D or Two Dimensional array in java. Arrays are one of the most useful data structures when it comes to data storage. Arrays provide random access to the elements via their index basing which makes both accessing and storing the most efficient.

Hence, it is trivial to know the different ways one can use to print these arrays. So, we will look at different ways to print a 2D array in java with working examples to get a deeper look at Two-dimensional arrays in java.

What is a 2-dimensional array or matrix in java?

A 2D Array or Two-dimensional array, simply put is a representation of elements along the two axes i.e. X axis and the Y axis respectively, typically in the form of a Matrix having elements across the columns of each row. Unlike a 1D array which uses only a single index to store and access elements, A 2D array or a 2D matrix uses two indices to represent an array in memory.

We access elements in a 2D array like this:  arr[row][column]

A typical 2D array representation has 3 rows and 3 columns:

In the 2D array arr, the first square bracket contains the row index value and the second bracket contains the column index value similar to a matrix. In Java, arrays are allocated memory dynamically with the new keyword and we need to specify the size of the rows and columns at the time of declaration of the array. We declare the 2D array like this:

int arr[][] = new int[10][10];

Here, 10 is the total number of rows and columns in the matrix respectively. We can also have a matrix or 2D array with varying sizes of rows and columns.

How to print a 2D array in java?

Here we outline 5 possible methods to Print a 2D array in Java:

  • Simple Traversal using for and while loop.
  • Using For-each loop
  • Using the toString() method of Arrays Class
  • Using deepToString() method of Arrays Class.
  • Using Streams in Java 8.

Let us have a look at each of these methods in detail.

Simple Traversal using for and while loop

Using this method, we first traverse through each row i of the 2D matrix then we print the value at each column j like arr[i][j]. Hence, we require two Nested For loops to traverse the 2D array. This is a commonly used method to print the 2D array.

Important Points to note:

  1. In Java, we can use the length field to get the length of the array. So, for a 2D array arr, we can use arr.length to get the total number of rows.
  2. Now, since each row of the 2D array is an array itself, so we can use arr[i].length to get the length of each row i.e. the total number of columns in the 2D Array, i is the row index of the array.
  3. This assumption will help us in traversing through the 2D array when the row size and column size are not known or when the rows and columns are different in length i.e. Total number of rows ≠ Total number of Columns

Let us look at the code implementation.

public class Java2Blog {
    
    static void print2DArray(int arr[][])
    {
        System.out.println("The 2D Array is : ");
        System.out.println();
        // Loop through all rows
        for (int i = 0; i < arr.length; i++) // we use arr.length to get rows
        {
            // Loop through all elements of current row with arr[i].length to get size of each row array
            for (int j = 0; j < arr[i].length; j++) 
            {
              System.out.print(arr[i][j] + " ");
            }    
         System.out.println();       // Add a line break after printing each row
         
        }        
    }
 
    public static void main(String args[])
    {
        int arr[][] =  { { 1, 2, 3 },
                         { 4, 5, 6 },   // we declare a 2D array with 3 rows & 3 columns.
                         { 7, 8, 9 } 
                       };
                        
        print2DArray(arr);
    }
}

Output:

We can also use the while loop to print the same 2D array but with a different set of counter variables. Let us have a look at the code for this method as well.

public class Java2Blog {
    
    static void print2DArray(int arr[][])
    {
    	int n = 0,k = 0;
    	System.out.println("The 2D Array using while loop : ");
    	System.out.println();
    	
        while (n != arr.length)
        {
            while (k != arr[n].length)
            {
                System.out.print(arr[n][k] + " ");
                k++;
            }
            k = 0;
            n++;
            System.out.println("");
        }
    }
 
    public static void main(String args[])
    {
        int arr[][] =  { { 1, 2, 3 },
                         { 4, 5, 6 }, // we declare a 2D array with 3 rows & 3 columns.
                         { 7, 8, 9 } 
                       };
                        
        print2DArray(arr);
    }
}

Output:

Using For-Each Loop to print 2D Array in Java

In Java, For- Each loop is another interesting technique to traverse arrays, introduced from Java 5. In this loop, instead of declaring a loop counter variable, we declare a reference variable of the same type as the array. It is also known as the Advanced For loop.

Important Points to note:

  • When traversing through a 2D array, we declare the reference variable of the type array. Example: int[] row, row is a reference to an int array, and refers to each row of the array.
  • For the next nested loop, we can simply go through each element of the reference array row and print the elements.

Let us look at the implementation in code.

public class Java2Blog {
    
    static void print2DArray(int arr[][])
    {
    	System.out.println("The 2D Array is : ");
    	System.out.println();
    	// for each loop
        for (int[] row : arr) // row refers to each row or array in 2D array arr
        {
            // Loop through all elements of the row
            for (int element : row) 
            {
              System.out.print(element + " ");
            }    
         System.out.println(); // Add a line break after printing each row
         
        }        
    }
 
    public static void main(String args[])
    {
        int arr[][] =  { { 1, 2, 3 },
                         { 4, 5, 6 }, // we declare a 2D array with 3 rows & 3 columns.
                         { 7, 8, 9 } 
                       };
                        
        print2DArray(arr);
    }
}

Output:

Arrays.toString() method to print 2D Array in Java

We can use the toString() method of the Object class to give the String representation of any object. Similarly, the Arrays of java.util package class in java has its own toString() method that represents the array as a String within square brackets. This is permissible as arrays are primarily objects in java, also we employ this method to mainly debug the code to get spontaneous values in the array.

We first loop through each row within the 2D array then we print each array using the Arrays.toString() method.

Let us look at the code.

import java.util.Arrays;

public class Java2Blog {
    
    static void print2DArray(int arr[][])
    {
    	System.out.println("The 2D Array using toString() is : ");
    	System.out.println();
    	// for each loop
        for (int[] row : arr) // row refers to each row or array in 2D array arr
        {
            
         // Print each row using toString
         System.out.print(Arrays.toString(row));    
         System.out.println();  // Add a line break after printing each row
         
        }        
    }
 
    public static void main(String args[])
    {
        int arr[][] =  { { 1, 2, 3 },
                         { 4, 5, 6 }, // we declare a 2D array with 3 rows & 3 columns.
                         { 7, 8, 9 } 
                       };
                        
        print2DArray(arr);
    }
}

Output:

Arrays.deepToString() method to print 2D Array in Java

In the Arrays class, the deepToString() method is an interesting implementation of toString() that returns a String representation of the deep contents of the specified array. It returns all the rows of the 2D array within square brackets.

The syntax of the method is :

public static String deepToString(Object[] a)

This method accepts only arrays as input parameters. Let us look at the code.

import java.util.Arrays;

public class Java2Blog {
    
    static void print2DArray(int arr[][])
    {
    	System.out.println("The 2D Array using deepToString() is : ");
    	System.out.println();
    	
    	 System.err.println(Arrays.deepToString(arr));
    }
 
    public static void main(String args[])
    {
        int arr[][] =  { { 1, 2, 3 },
                         { 4, 5, 6 }, // we declare a 2D array with 3 rows & 3 columns.
                         { 7, 8, 9 } 
                       };
                        
        print2DArray(arr);
    }
}

Output:

If we want to exclude the square brackets while printing the 2D array using deepToString() method we can also try replacing them with blank spaces to order and format the output.

Let us look at the example:

import java.util.Arrays;

public class Java2Blog {
    
    static void print2DArray(int arr[][])
    {
    	System.out.println("The 2D Array replacing the square brackets is : ");
    	System.out.println();
        // we replace ',' with blank space and add extra space while printing each row.    	                                                                       
    	System.err.println(Arrays.deepToString(arr).replace("],","\n").replace(","," ").replaceAll("[\\[\\]]", " ")); 
    }
 
    public static void main(String args[])
    {
        int arr[][] =  { { 1, 2, 3 },
                         { 4, 5, 6 }, // we declare a 2D array with 3 rows & 3 columns.
                         { 7, 8, 9 } 
                       };
                        
        print2DArray(arr);
    }
}

Output:

Using Stream API in Java 8 to print a 2D array

From the advent of Java 8, the introduction of the Stream API and Lambda expressions helped in minimizing the code and add more features of functional programming.

Hence, we can use the stream() method of the Arrays class and add for-each loop implementation with Lamda expressions to print a 2D array. We first take each row as a stream then convert each element in the row as a stream and print the elements in a 2D array.

Note: JDK 8.0 or higher must be installed in your machine to use this method.

Let us look at the code implementation.

import java.util.Arrays;

public class Java2Blog {
    
    static void print2DArray(int arr[][])
    {
    	System.out.println("The 2D Array using Streams : ");
    	System.out.println();
        // we use for each with stream to convert rows of array into a stream.  	                                                                       
    	Arrays.stream(arr).forEach((i) -> {
            Arrays.stream(i).forEach((j) -> System.out.print(j + " "));
            System.out.println();
        });
    }
 
    public static void main(String args[])
    {
        int arr[][] =  { { 1, 2, 3 },
                         { 4, 5, 6 }, // we declare a 2D array with 3 rows & 3 columns.
                         { 7, 8, 9 } 
                       };
                        
        print2DArray(arr);
    }
}

Output:

That’s all for the article, we looked at different methods to print a 2D array in java with working examples. You can try the code in your local compiler.

Feel free to reach out for any suggestions/doubts.

]]>
https://java2blog.com/print-2d-array-java/feed/ 0
Return Empty Array in Java https://java2blog.com/return-empty-array-java/?utm_source=rss&utm_medium=rss&utm_campaign=return-empty-array-java https://java2blog.com/return-empty-array-java/#respond Mon, 19 Sep 2022 07:33:19 +0000 https://java2blog.com/?p=19546

TL;DR
To return empty Array in Java, you can use curly braces.

public static String[] returnEmptyStringArray() {
        
        String[] emptyArray = {};
        return emptyArray;
    }

or

public static String[] returnEmptyStringArray() {
        return new String[]{};
    }

1. Introduction

In this article, we will take a look on to How to return Empty array in java. We will look at different ways to achieve this with demonstrated working examples in detail. At first, let us have a brief look into Arrays in java and what exactly is an Empty Array and how it is different from a null array.

An Array is a collection of homogenous or similar type of elements having contiguous memory allocation in a sequence. In Java, arrays are objects which are allocated memory dynamically. We can use arrays to store primitive data(int, float, double etc.) and object types as well.

2. What Is the Need to Return an Empty Array?

An Empty Array is an array with length 0 i.e. it has no elements. This indicates the array along with its reference exists in the memory but has no data within. We declare an empty array as:

int arr[] = new int[0];

There are certain cases where we need to return an empty array as specified below:

  • Suppose the array is coming from an API, and it returns null; in this case, we might want to return an array without any element, instead of null because it will be known what type of an array is actually returned as null doesn’t correspond to primitive type data.
  • Returning null instead of an actual array, collection or map forces the callers of the method to explicitly test for its nullity, making the method more complex and less readable.

Example:

public static Result[] getResults() {
  return null;                             // Noncompliant
}

Hence, if we return array like this, it will be mandatory to check for nullity in order to avoid NullPointerException in java and this is a recommended coding practice as well. So at the calling end we need to do check like this:

public static void main(String[] args) {
  Result[] results = getResults();
  if (results != null) {                   // Nullity test
    for (Result result: results) {
      /* your code */
    }
  }

3. How Do You Return Empty Array in Java?

There can be 4 methods mentioned in number point as below:

  1. Return using Curly Braces
  2. Return using Anonymous Array objects – new int[0] function 
  3. Return using Empty Array declaration
  4. Return using Apache Commons – org.apache.commons.lang3.ArrayUtils Package.

In Java, we instantiate an array using { } with the  values added manually or hardcoded, and the array size is the number of elements in the array. It is allowed in Java to return an array with empty curly braces; without any elements the array size will be zero.

We can create a method returnEmptyArray that returns a

3.1 Using Curly Braces

n array. We initialize an empty array using emptyArray = {} and then return emptyArray. Let us look at the example code.

package org.arpit.java2blog.generic;

public class ReturnEmptyArrayMain {
    public static void main(String args[]) {

        ReturnEmptyArrayMain ream=new ReturnEmptyArrayMain();
        int[] intEmptyArray = ream.returnEmptyIntegerArray();
        String[] stringEmptyArray = ream.returnEmptyStringArray();

        System.out.println("Integer Array length: "+intEmptyArray.length);
        System.out.println("String Array length: "+stringEmptyArray.length);
    }

    public static int[] returnEmptyIntegerArray() {

        return new int[] {};
    }

    public static String[] returnEmptyStringArray() {

        String[] emptyArray = {};
        return emptyArray;
    }
}

Output:

3.2 Using Anonymous Array Objects – New Int[0] 

In Java, an array has a fixed size that we can specify while creating the array. If the array has a length or size of zero, it indicates it has no values. Hence, we return empty arrays, creating them with a zero size or return an anonymous array without the name declaration. we use the new keyword here to create array and allocate memory to it.

Note: A null array is not an empty array.

We can create an array or just return this value : new int[0] that is an empty array of int . Let us take a look at the example code.

public class ReturnEmptyArrayMain {
    public static void main(String args[]) {
       
         ReturnEmptyArrayMain ream=new ReturnEmptyArrayMain();
        int[] intEmptyArray = ream.returnEmptyIntegerArray();
        String[] stringEmptyArray = ream.returnEmptyStringArray();
        
        System.out.println("Integer Array length: "+intEmptyArray.length);
        System.out.println("String Array length: "+stringEmptyArray.length);
    }

    public int[] returnEmptyIntegerArray() {
        
        // Declaring Array and allocating memory
        int[] emptyArray = new int[0];
        return emptyArray;
    }
    
    public String[] returnEmptyStringArray() {
        
        // Return Anonymous Array block
        return new String[0];
    }
}

Output:

3.3 Using Empty Array Declaration

This is another alternative way to declare an empty array with no dimensions i.e. size and then return it. We declare the array array using the conventional way of creating an array and instantiating with the new keyword but we do not input the size in the square brackets [] .

We can return the array like this: new int[]{} i.e. an integer array or declare first. This is a simpler method to follow the above approach. We will create an empty array of objects of class Employee and then return it.

Let us take a look at the example code.

class Employee
{
	int id;
	String name;
}

public class Java2Blog {
    public static void main(String args[]) {
       
    	Employee[] emptyArray1 = returnEmptyEmployeeArray();
        Employee[] emptyArray2 = returnAnonymousEmptyArray();
        
        System.out.println("First Array length: "+emptyArray1.length);
        System.out.println("Second Array length: "+emptyArray2.length);
    }

    public static Employee[] returnEmptyEmployeeArray() {
        
        // Declaring Array of type Employee and allocating memory
        Employee[] emptyArray = new Employee[]{};

        return emptyArray;
    }
    
    public static Employee[] returnAnonymousEmptyArray() {
        
        // Return Anonymous Array block
        return new Employee[]{};
    }
}

Output:

3.4 Using Apache Commons Library – Array Utils Package

The Apache Commons API provides powerful and reusable Java components and dependencies that we can embed into our applications and programs. Here, to return an empty array in we can use the inbuilt functionality of this package.

There are two ways we can return empty array using the Apache Commons lang3 package:

  • Return Using EMPTY_STRING_ARRAY  field of ArrayUtils Class.
  • Return Using toArray() method of ArrayUtils Class.

We can use the ArrayUtils class of the Apache Commons Library by importing with the following dependency. For ease we will use the JAR file component of Apache Commons Lang package. To setup the JAR file component for this package we follow these steps:

  1. Download the Apache Commons Lang JAR.
  2. Extract the ZIP file and keep the commons-lang3-3.12.0 JAR in separate folder.
  3. Go to your IDE (Eclipse/Intellij) then right click on package name go to -> Configure Build Path.
  4. Go to libraries -> Click on Classpath -> Add External JAR’s.
  5. Select the commons-lang3-3.12.0 JAR and click Apply and close.

The JAR will then be added to your Java Application after this we can just import the required classes from this package. Now, let us look into the steps.

3.4.1 Return Using EMPTY_STRING_ARRAY  field of ArrayUtils Class

The ArrayUtils class has a static field EMPTY_STRING_ARRAY which returns a empty String array. It has similar other static fields which return int, char, float etc. type of arrays.

3.4.2 Return Using toArray() method of ArrayUtils Class

The ArrayUtils class has a method toArray() which can return any type of array based on the the type it is referenced to it can be a object or a primitive type array. It automatically casts the return type based on the method definition.

Let us have a look at the example code to implement the two methods.

import org.apache.commons.lang3.ArrayUtils;     // importing Apache Commons lang3 package

class Employee
{
	int id;
	String name;
}

public class Java2Blog
{
	public static void main(String args[])
	{
		String[] stringArray = returnEmptyStringArray();
		int[] intArray = returnEmptyIntArray();
		Employee[] emptyArray = returnEmptyEmployeeArray();
                System.out.println("String Array length: "+stringArray.length);
                System.out.println("Integer Array length: "+intArray.length);
                System.out.println("Employee Array length "+emptyArray.length);
	}
	
	public static String[] returnEmptyStringArray() {
        // returns empty String array
        return ArrayUtils.EMPTY_STRING_ARRAY;
        }
	
	public static int[] returnEmptyIntArray() {
		// returns empty Int array
        return ArrayUtils.EMPTY_INT_ARRAY;
        }
	
        public static Employee[] returnEmptyEmployeeArray() {
    	// here we return Empty array of type Employee
        return ArrayUtils.toArray();
        }
}

Output:

That’s all about the articles we listed different methods to Return empty array in java with demonstrated examples. You can try them in your Local IDE for a clear understanding. Feel free to reach out to us for any queries/suggestions.

]]>
https://java2blog.com/return-empty-array-java/feed/ 0
How to Write Array to File in Java https://java2blog.com/write-array-to-file-java/?utm_source=rss&utm_medium=rss&utm_campaign=write-array-to-file-java https://java2blog.com/write-array-to-file-java/#respond Fri, 16 Sep 2022 11:03:48 +0000 https://java2blog.com/?p=20534 In this post, we will see how to write array to file in java.

Ways to Write Array to File in Java

There are different ways to write array to file in java. Let’s go through them.

Using BufferWriter

Here are steps to write array to file in java:

  • Create new FileWriter and wrap it inside BufferedWriter.
  • Iterate over the array and use write() method to write content of the array
  • Once done close and flush BufferedWriter obj.
package org.arpit.java2blog;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteArrayToFileMain {

    public static void main(String[] args) throws IOException {
        int[] intArr = {1,2,3,4,5};
        String fileName= "C:\\Users\\Arpit\\Desktop\\TxtFiles\\temp.txt";
        write(fileName,intArr);
    }
    public static void write (String filename, int[]arr) throws IOException {
        BufferedWriter ow = null;
        ow = new BufferedWriter(new FileWriter(filename));
        for (int i = 0; i < arr.length; i++) {

            ow.write(arr[i]+"");
            ow.newLine();
        }
        ow.flush();
        ow.close();
    }
}

Output:
Write array to file in java

Using ObjectOutputStream

You can use ObjectOutputStream to write object to underlying Stream. This is also know as Serialization in java.
Here are the steps:

  • Create new FileOutputStream and write it in ObjectOutputStream.
  • Use writeObject() method to write object to the file.
package org.arpit.java2blog;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class WriteArrayToFileObjectOutputStreamMain {

    public static void main(String[] args) throws IOException {

        int[] intArr = {1,2,3,4,5};
        String fileName= "C:\\Users\\Arpit\\Desktop\\TxtFiles\\tempObj.txt";
        ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
        outputStream.writeObject(intArr);
    }
}

Please note that content of the tempObj.txt file won’t be in readable format.

To read the array back, you need to use ObjectInputStream.

Here is an example to read file back into the array.

package org.arpit.java2blog;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Arrays;

public class ReadFileIntoArrayMain {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        String fileName= "C:\\Users\\Arpit\\Desktop\\TxtFiles\\tempObj.txt";
        ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(fileName));
        int[] intArr = (int[])inputStream.readObject();
        System.out.println("Array: "+Arrays.toString(intArr));
    }
}

Output

Array: [1, 2, 3, 4, 5]

That’s all about how to write array to File in Java.

]]>
https://java2blog.com/write-array-to-file-java/feed/ 0
How to Initialize an Array with 0 in Java https://java2blog.com/initialize-array-to-zero-java/?utm_source=rss&utm_medium=rss&utm_campaign=initialize-array-to-zero-java https://java2blog.com/initialize-array-to-zero-java/#respond Tue, 17 May 2022 16:10:46 +0000 https://java2blog.com/?p=19863 This article discusses the arrays and different ways to initialize an array with 0 in Java.

Arrays

The arrays are the fundamental data structures, they are sequences of elements stored in contiguous memory locations. The first step when using a data structure involves initializing the data structure which in our case is arrays. Array instantiation or initialization refers to the method of assigning values to array elements of a given data type and size.

We will discuss this in three parts.

  • The first part will deal with initializing a newly created array and how that can be initialized to zero.
  • The second part will be initializing an already existing array to zero.
  • And finally, we will discuss how to initialize user-defined arrays in Java.

Initializing Newly Created Array

When the use case involves an array to be newly created, we have the following methods for initialization at our disposal.

Using Default Initialization of Arrays in Java

Java Language has in-built functionalities to initialize anything which is not explicitly initialized by a programmer. The Java Specifications Document lists various default values for references (null), int, byte, short, long to 0, float to 0.0, etc.

The following code snippet illustrates how array values get initialized according to the data type specified while declaring the array in Java.

public class Sample {
    public static void main(String[] args)
    {
        int[] iarray=new int[5];
        float[] farray=new float[5];
        for(int i=0;i

Output:

0 0 0 0 0
0.0 0.0 0.0 0.0 0.0

When allocating memory to local variables the Java Virtual Machine or JVM is not required to zero out the underlying memory for them, and thus to avoid random values being allocated to them, the specification mandates initialization to specific values.

These operations help to execute efficient stack operations as and when needed.

Using Initialization After Declaration

You can also explicitly initialize an array to zero just after declaration. Declaration and initialization are two different things.
A declaration does not allocate memory. In order to allocate memory initialization is needed. In Java, you can achieve this separately as well as simultaneously.

The following code illustrates the explicit initialization of arrays with 0 after the declaration in Java

public class Sample {
    public static void main(String[] args)
    {
        int[] array;
        array= new int[]{0,0,0,0,0};
        for(int i=0;i

Output:

0 0 0 0 0

In the above example, code first declares the array variable and in the next line it separately and explicitly initialize the array to zero.

Using Simultaneous Initializing and Declaration of Array

As you have seen previously, instead of initialization after declaration, you can also initialize the arrays along with the declaration.
Although this simple change in line of code may look similar but underlying code is completely different for these two methods.

The following code illustrates simultaneous initialization and declaration of arrays in Java.

public class Sample {
    public static void main(String[] args)
    {
        int[] array={0,0,0,0,0};
        for(int i=0;i

Output:

0 0 0 0 0

In the above example, code performs simultaneous initialization and declaration of the array variable in a single line.

Notice that in this case there is no need to mention the size anywhere during the declaration and initialization.

Using Reflection in Java

Another workaround for the initialization can be by the use of the Array.newInstance() method in the reflection library of Java.
It creates a new instance of a specified type and dimension given as parameters to the function.

The definition of the function is given below.

public static Object newInstance(Class componentType,
                 int length)
                          throws NegativeArraySizeException

Note that you can not pass the negative size of the array, otherwise, the method throws an exception.

The following code will give you a fair idea of how to initialize the array to zero in Java.

import java.lang.reflect.Array;

public class Sample {
    public static void main(String[] args)
    {
        int[] array= (int[]) Array.newInstance(int.class, 5);
        for(int i=0;i

Output:

0 0 0 0 0

In the above example code, you can observe that the code calls the newInstance() member function with parameters defining the type and class which is to be returned.

It then assigns the result to the array variable, which by default gets initialized to zero, as you can see in the output.

Initializing Existing Array

In this part, we will learn how to initialize an array to zero if we already have an array declared and initialized with other values already given to us.

Using the Arrays.fill() Function of Java

The Util library of java provides the member function Arrays.fill(). This function can fill the array to any specified data type value either completely throughout the array or partially. It can also be used for multi-dimensional arrays.

The definition of the Arrays.fill() function is given below.

public static void fill(int[] a,
        int val)

There are multiple overloaded declarations of the method. You can visit here for more information.

In our example we will see the use of the Arrays.fill() function to initialize the array to zero, the following code illustrates this.

import java.util.Arrays;

public class Sample {
    public static void main(String[] args)
    {
        int[] array= {1,5,6,7,2};
        System.out.println("Array Initially:");
        for(int i=0;i

Output:

Array Initially:
1 5 6 7 2
Array After using fill():
0 0 0 0 0

Although internally the JVM also applies the for loop in the Arrays.fill() function it is much more efficient than a simple for loop, it does so by lower level implementation internally, making it run faster than a for loop.

Using the for Loop

You can explicitly also initialize the entire array or part of it by zero by using a simple for loop.
This method is often used by new users or learners and it is not as efficient but fairly simple and easy to understand for beginners.

The following code illustrates the usage of for loop for initialization of array to zero in Java.

public class Sample {
    public static void main(String[] args)
    {
        int[] array= {1,5,6,7,2};
        System.out.println("Array Initially:");
        for(int i=0;i

Output:

Array Initially:
1 5 6 7 2
Array After using for loop:
0 0 0 0 0

You can observe from this code that when the loop runs in each iteration the code assigns the value zero to each individual element sequentially.

Using Reassignment From Another Array

This method involves creating a new array and using it to re assign the originally given array.

This method uses the Java in-built functionality of default initialization and takes it a step further.

The following code illustrates how this reassignment can be performed which in process initializes the original array to zero in Java.

public class Sample {
    public static void main(String[] args)
    {
        int[] array= {1,5,6,7,2};
        System.out.println("Array Initially:");
        for(int i=0;i

Output:

Array Initially:
1 5 6 7 2
Array After performing reassignment:
0 0 0 0 0

In this example, temp array is created of the same data type and size.

This is a very important requirement for reassignment as only the same data type can be assigned to another variable and the same size is required for arrays.

Using Collections.nCopies() Function of Java

Groups of individual objects in Java are said to be collections in Java. The collection framework in Java has a variety of functions and wrapper classes that you can use for initialization as well.

Integer is a wrapper class whose array can be initialized as shown in the example.

The definition of the Collections.nCopies() method is given below.

public static  List nCopies(int n,
                  T o)

The following example illustrates nCopies() method of Collections to initialize Integer array using an existing array.

import java.util.Collections;

public class Sample {
    public static void main(String[] args)
    {
        int[] array= {1,5,6,2,8};

        System.out.println("Array Initially:");
        for(int i=0;i

Output:

Array Initially:
1 5 6 2 8
Array after using nCopies:
0 0 0 0 0

In this example, the code uses an already existing array from which another array of objects is created using the Collections.ncopies() method.

It copies the structure of arrays, but it is initialized to zero. Thus it creates a new Integer class array with the same size as that of the existing array but with initial values of zeroes.

Initializing User-Defined Object Array

In Java, Object arrays can also be user-defined. User defined arrays can also be initialized to zero.

User defined arrays are also declared in the same way as normal primitive data types.

The following example, illustrates how you can initialize the user defined arrays to zero in Java.

class num
{
    int value;
    num(int x)
    {
        value=x;
    }
};
public class Sample {

    public static void main(String[] args)
    {
        num[] arr=new num[5];
        arr[0]=new num(0);
        arr[1]=new num(0);
        arr[2]=new num(0);
        arr[3]=new num(0);
        arr[4]=new num(0);

        for(int i=0;i

Output:

0 0 0 0 0

This example creates a user defined class num with an integer data member value, with a constructor for initialization of each object.

An array of this class arr is then created with a size of five and then all of them are one by one initialized to zero.

Conclusion

These are different ways that can be used to initialize an array to zero in Java. In this article we discussed three different use cases where initialization of arrays can be needed.

In all these three methods we discussed different possible ways of initialization of an array with 0 in java.

That’s all about how to initialize an Array with 0 in Java.

Hope you have learned something new and enjoyed reading the article. Stay tuned for more such articles. Happy learning!

]]> https://java2blog.com/initialize-array-to-zero-java/feed/ 0 Set an Array Equal to Another Array in Java https://java2blog.com/set-array-equal-to-another-array-java/?utm_source=rss&utm_medium=rss&utm_campaign=set-array-equal-to-another-array-java https://java2blog.com/set-array-equal-to-another-array-java/#respond Fri, 22 Apr 2022 19:11:18 +0000 https://java2blog.com/?p=19798 This article discusses methods to set an array equal to another array in Java.

Arrays are the most basic data structures that store the data at contiguous memory locations. The operations on the array elements are performed using the indices.

Setting an Array Variable Equal to Another Array Variable

It might seem logical to set an array variable equal to another array variable to copy the elements of the array.

However, there is a catch. When you set an array variable equal to another array variable, both of the variables have the reference.

Therefore, instead of copying the array elements, reference is copied. In this case if you change array elements using one of the array variable, changes are reflected in both of the array variables.

Hence, you can not copy the array elements by simple assignment operator (=).

Set an Array Equal to Another Array in Java Using the clone() Method

The clone() method creates a copy of the object that calls it and returns the copied object reference.

Note that this method creates a deep copy. It means the separate memory is allocated to the new object.

This method is defined in the object class and returns an object of type Object. The definition of the clone() method is given below.

protected Object clone()
                throws CloneNotSupportedException

The method throws a CloneNotSupportedException in the case where the clone of the object could not be created.

The object of those classes that does not implement the Cloneable interface can not be cloned. In such cases the clone() method throws the exception. If you are overriding the clone() method your implementation should also throw the exception.

Let us say you have an object obj1 and you call clone() on it. You store the results in obj2. Then in that case, obj2 and obj1 contain different reference and hence are not equal.

Let us see an example code in Java that clones an array into another array using clone() method.

package java2blog;

public class ArrayExample 
{

    public static void main(String[] args)
    {
        int a [] = {1, 2, 3, 4, 5};
        int b [] = a.clone();

        System.out.print("a: ");

        for(int i=0;i

Output:

a: 1 2 3 4 5
b: 2 2 3 4 5

Set an Array Equal to Another Array in Java Using the arraycopy() Method

The arraycopy() method of the System class copies an array starting from a specific position to another array starting from a specific position.
Let us see the definition of the method.

public static void arraycopy(Object src,
             int srcPos,
             Object dest,
             int destPos,
             int length)

The method requires the following arguments,

  • src: The source array from which the elements are to be copied.
  • srcPos: The starting position in the src from where the elements are copied.
  • dest: The destination array to which the elements are to be copied.
  • destPos: The position in destination array where the elements are to be copied.
  • length: number of elements to be copied.

The method throws various exceptions as well. Let us see each one of them.

  • NullPointerException: If the src or dest are null, method throws this exception.

  • ArrayStoreException: The method throws this exception in various cases as given below.

    • If the src or dest is not an array.
    • If there is a type mismatch between the src and dest array. For example if one of the arrays is of type int and other is of type String, method throws this exception.
  • IndexOutOfBoundsException: This exception signifies that an array is being accessed beyond its assigned memory limit.

    So in case you provide negative srcPos and destPos or if length is more than number of elements, the method raises this exception.

Let us see the code to copy an array into another array using this method.

package java2blog;

public class ArrayExample 
{

    public static void main(String[] args)
    {
        int a [] = {1, 2, 3, 4, 5};
        int b [] = new int [a.length];

        System.arraycopy(a, 0, b, 0, a.length);

        System.out.print("a: ");

        for(int i=0;i

Note that the arraycopy() method is a static method of System class. So you can invoke it with class name only without creating the object.

Output:

a: 1 2 3 4 5
b: 2 2 3 4 5

Set an Array Equal to Another Array in Java Using the copyOf() Method

The copyOf() method copies the content of an array and returns a new array.
The method takes two arguments, the reference of original array and length denoting the number of elements to be copied starting from beginning.

Let us see the definition of the copyOf() method.

public static int[] copyOf(int[] original,
           int newLength)

Note that this method can truncate or pad the copied array with zeros. Padding will happen when the provided length is greater than the number of elements in the array.

This method throws two exceptions as given below.

  • NullPointerException: If the original array is null
  • NegativeArraySizeException: If the newLength argument is negative.

Let us see the code.

package java2blog;

import java.util.Arrays;

public class ArrayExample 
{

    public static void main(String[] args)
    {
        int a [] = {1, 2, 3, 4, 5};
        int b [] = Arrays.copyOf(a, a.length);

        System.out.print("a: ");

        for(int i=0;i

Output:

a: 1 2 3 4 5
b: 2 2 3 4 5

Set an Array Equal to Another Array in Java Using the copyOfRange() Method

If you need to copy the elements of an array within a particular range, then the copyOfRange() is a better option.

This method works similar to the copyOf() method except that it accepts three arguments specifying the range to be copied.

Let us see definition of the copyOfRange() method.

public static  T[] copyOfRange(T[] original,
                  int from,
                  int to)

The method definition specifies the generic template type so that it can be used with all of the data types.

The first argument original is the reference of the original array from where the elements are to be copied.

The second argument from specifies the starting point from where the elements will be copied.

The last argument to marks the end of the range. It means the elements from original array are copied till here to the new array.

This method throws the following exceptions.

  • NullPointerException: The method throws this exception if original is null.
  • IllegalArgumentException: The method throws this exception if from is greater than to.
  • ArrayIndexOutOfBoundsException: The method throws this argument if the from is negative or is greater than the length of the original array.

Let us see the code example.

package java2blog;

import java.util.Arrays;

public class ArrayExample 
{

    public static void main(String[] args)
    {
        int a [] = {1, 2, 3, 4, 5};
        int b [] = Arrays.copyOfRange(a, 1, a.length-2);

        System.out.print("a: ");

        for(int i=0;i

Note that the code copies only second and third elements of first array to the second array.

Output:

a: 1 2 3 4 5
b: 2

Copying Array Elements by Iterating the Array

One of the easiest method to copy the array elements is to iterate the first array using indices and assigning each element to corresponding index of second array.

You can iterate the array elements using any of the loops.

Let us see the code.

package java2blog;

public class ArrayExample 
{

    public static void main(String[] args)
    {
        int a [] = {1, 2, 3, 4, 5};
        int b [] = new int [a.length];

        for(int i=0;i

Note that the length variable in the array stores the number of elements in the array. The code copies the first array to the second array.

However the code also changes the first element of second array. You may notice that only element of second array is changed and first array remains same.

Output:

a: 1 2 3 4 5
b: 2 2 3 4 5

Conclusion

You have seen different methods of copying the array elements. While using the predefined methods, you can avoid iterations. Also, arraycopy() method is faster than clone() method.

Therefore, it is logical to select the method that suits best as per the needs. For example if you need to copy elements within a range the best suited method is copyOfRange() method.

This is all about how to set an array equal to another array in Java.
Hope you enjoyed reading the article. Stay tuned for more articles. Happy Learning!

]]> https://java2blog.com/set-array-equal-to-another-array-java/feed/ 0 Check if Array Is Empty in Java https://java2blog.com/check-if-array-is-empty-java/?utm_source=rss&utm_medium=rss&utm_campaign=check-if-array-is-empty-java https://java2blog.com/check-if-array-is-empty-java/#respond Fri, 04 Mar 2022 09:33:37 +0000 https://java2blog.com/?p=19577 In this post, we will see how to check if array is empty in Java.

The arrays are a data structure that facilitates storing multiple instances of data together in contiguous memory locations.

This article discusses different cases when an array is considered to be empty in Java. It also discusses methods to check, for different cases, if array is empty in Java.

Check if the Array Is Empty in Java

There are three different cases when Java considers an array to be empty. These are given as follows.

    • The array variable has the null reference.
    • The array does not contain any element.
    • The array has only null elements.

Let us understand each of these cases one by one.

The Array Variable Has the Null Reference

In this case, an array variable actually stores a null reference, therefore, storing virtually nothing. This case can arise from two different possibilities as given below.

  1. When the array is not instantiated, the array variable has a null reference making it an empty array. For example,
    int [] arr;
    > You should note that Java doesn’t allow you to use an uninitialized local variable. So this case does not apply to local variables. However, it is applicable if your array is globally declared.
  2. When you explicitly assign null to the array variable. For example,
    int [] arr = null;
    For this case when the array variable has a null reference, you can directly use the equality operator (==) to check if the array has the null reference.

Let us see the code to check this condition for Java arrays.

package java2blog;

public class NullArrayExample {
	
	int [] arr;
	int [] arr2 = null;
	public static void main(String [] args)
	{
		NullArrayExample obj = new NullArrayExample();
		if(obj.arr==null)
			System.out.println("arr is empty (null).");
		if(obj.arr2 == null)
			System.out.println("arr2 is empty (null).");
	}
}

Output:

arr is empty (null).
arr2 is empty (null).

The Array Does Not Contain Any Element

When you declare an array as well as instantiate it, the memory is assigned to it. The array variable stores reference to the assigned memory.

However, if you instantiate the array with the size of the array as zero, it will not store any elements, therefore, making it an empty array.

To check if the array is empty in this case,

  • Check the length of the array using the ‘length’ variable.
  • The Java array object has a variable named ‘length’ that stores the number of elements in the array.
  • If the length is zero, the array is empty.

Let us see an example that implements the steps given above.

package java2blog;

public class NullArrayExample {
	public static void main(String [] args)
	{		
		int [] emptyArr = new int[0];
		if(emptyArr.length == 0)
			System.out.println("The array is empty");
	}
}

Output:

The array is empty

The Array Has Only Null Elements

Java initializes all the arrays of non-primitive types with null values at the time of instantiating the array. Therefore, if you do not assign non-null elements to the array, it will continue to contain the null values for all elements.

Alternatively, you can manually assign the null values to all of the array elements. In both cases, Java considers the array to be empty.

To check if the array is empty in this case,

  • Initialize a boolean flag variable to true.
  • Loop through all elements of the array.
  • Check each element for a null value.
    • If the current element is not null, change the value of the flag variable to false and break from the loop.
    • Otherwise, move to the next element.
  • After the loop terminates, check the flag variable.
    • If the flag is true, the array is empty.
    • Otherwise, the array is not empty.

Let us see the implementation of these steps in code.

package java2blog;

public class NullArrayExample {
	
	public static void main(String [] args)
	{		
		String [] arr = new String[10];
		
		boolean allNull = true;
		
		for(int i=0;i<arr.length;i++)
		{
			if(arr[i] != null)
			{
				allNull=false;
				break;
			}
		}
		if(allNull)
			System.out.println("The array is empty!");
		else 
			System.out.println("The array is not empty!");
	}
}

Output:

The array is empty!

Note that the code declares a String array rather than an integer array as in previous cases. This is because the arrays with primitive data types are not initialized with null values by Java. For example, the integer array is initialized with zeros.

On the other hand, String is a class in Java, therefore, the String array is initialized with null values.

Using the Java Library to Check if the Array Is Empty in Java

Starting with the Java 8 version, Java provides library methods to perform a check on all array elements. Therefore, we can use these methods to check the condition of all null values in the array.

The java.util.Arrays class defines the stream() method that can be used to call the allMatch() method.

The stream() method returns a stream created using the array passed to it as a parameter. Let us see the definition of the stream() method.

public static  Stream stream(T[] array)

The allMatch() method accepts a predicate (a condition to be checked) and returns a boolean value. The allMatch() method returns a boolean true if the condition is met on all the array values. Otherwise, it returns a boolean false. Let us see the definition of the allMatch() method.

boolean allMatch(Predicate<? super T> predicate)

Note that using this method you can only check the condition of the empty array where all elements of the array are null. Let us see the example in code.

package java2blog;

import java.util.Arrays;
import java.util.Objects;

public class NullArrayJava 
{
	public static void main(String [] args)
	{
		String [] arr = new String [10];
		boolean isNull = Arrays.stream(arr).allMatch(Objects::isNull);
		if(isNull)
			System.out.println("The array is empty");
		else
			System.out.println("The array is not empty");
	}
}

The code passes the isNull predicate condition of the Objects class to the allMatch() method. It means that the allMatch() method returns true if all the elements of the array have null values.

Output:

The array is empty

Using Apache Commons Library to Check if the Array Is Empty in Java

The Apache commons library provides the isEmpty() method in the ArrayUtils class. This method can be used to check if the array is empty in Java.
You need to add below dependency to get Apache commons jar.

<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-lang3</artifactId>
		<version>3.9</version>
</dependency>

Let us see the definition of the isEmpty() method.

public static boolean isEmpty(Object[] array)

This method checks if the array passed to it as a parameter is empty or null. It returns a boolean true if an array is empty or null. Otherwise, it returns false.

Let us see the example demonstrating its use in the code.

package org.arpit.java2blog;

import org.apache.commons.lang3.*;

public class NullArrayJava 
{
	public static void main(String [] args)
	{
		String [] arr = new String[0];
		boolean isArrEmpty = ArrayUtils.isEmpty(arr);
		if(isArrEmpty)
			System.out.println("The array 1 is empty");
		else
			System.out.println("The array 1 is not empty");
		
		String [] arr2 = null;
		boolean isArrNull = ArrayUtils.isEmpty(arr2);
		if(isArrNull)
			System.out.println("The array 2 is Null");
		else
			System.out.println("The array 2 is not Null");
		
		String [] arr3 = new String[10];
		boolean isArrEmpty2 = ArrayUtils.isEmpty(arr3);
		if(isArrEmpty2)
			System.out.println("The array 3 is empty");
		else
			System.out.println("The array 3 is not empty");
	}
}

Output:

The array 1 is empty
The array 2 is Null
The array 3 is not empty

You should note that this method only checks the following conditions.

  • The array variable has a null reference.
  • The array is of zero length.

It can not check if the array has all null values.

Conclusion

While working with arrays, especially in the cases where arrays are passed as parameters to methods, you should perform the checks for an empty array. This helps in preventing the unexpected failures of the program.

Apart from the direct methods, you can use the libraries to check the cases of the empty array in Java. However, you should be careful while using library methods. This is because, as we have discussed, both of the library methods work only for a subset of cases of an empty array.

Hope you have enjoyed reading the article. Stay tuned for more such articles.

Happy Learning!

]]>
https://java2blog.com/check-if-array-is-empty-java/feed/ 0
Initialize Empty Array in Java https://java2blog.com/initialize-empty-array-java/?utm_source=rss&utm_medium=rss&utm_campaign=initialize-empty-array-java https://java2blog.com/initialize-empty-array-java/#respond Sat, 01 Jan 2022 13:33:03 +0000 https://java2blog.com/?p=18676

💡 Outline
You can use below code to initialize empty array in java.

// Initialize empty array
int arr[] = {};

Or

// Initialize empty array
int array[] = new int[0];

Or

// Initialize empty array
int arr[] = new int[] {};

1. Introduction

In this post, we take a look on How to Initialize empty array in Java. We will look at different ways to Initialize arrays in Java with dummy values or with prompted user inputs. Arrays in Java follow a different declaration paradigm than other programming languages like C, C++, Python, etc.

In Java, array is by default regarded as an object and they are allocated memory dynamically. Moreover, in java at the time of creation an array is initialized with a default value. For Example: If the array is of type int(integer) all the elements will have the default value 0.

Hence, we will outline different methods to initialize an empty array with examples, to make it easy for a beginner in Java to use appropriate example under apt cases.

2. Initialize an empty array in Java

Considering all cases a user must face, these are the different methods to initialize an array:

Let us look at these methods in detail.

2.1 Using Array Initializer

To declare empty array, we can use empty array initializer with {}. Java

int arr[] = {};

Here is sample program:

import java.util.Arrays;
 
public class EmptyArrayMain
{
    public static void main(String[] args) {
        int[] intArr= {};
        System.out.println(Arrays.toString(intArr));
    }
}

[]

Length of the array will be number of elements enclosed in {}. Since we have put nothing in {}, length of Array will be 0.

Please note that once you create empty array, you can’t change the length. In case, you need to change the size, you should use ArrayList instead.

You can also initialize empty array with Array creation expression as below:

import java.util.Arrays;
 
public class EmptyArrayMain
{
    public static void main(String[] args) {
        int[] intArr= new int[] {};
        System.out.println(Arrays.toString(intArr));
    }
}

[]

2.2 Using new keyword with 0 size

You can use new keyword with 0 size.

import java.util.Arrays;
 
public class EmptyArrayMain
{
    public static void main(String[] args) {
        int[] intArr= new int[0];
        System.out.println(Arrays.toString(intArr));
    }
}

[]

3. Initialize empty 2D Array in Java

You can initialize empty 2D array similar to empty Array.

import java.util.Arrays;
 
public class Empty2DArrayMain
{
    public static void main(String[] args) {
        int[][] intArr= new int[0][];
        System.out.println(Arrays.deepToString(intArr));
    }
}

[]

We can also create empty 2D array of non empty Arrays.

import java.util.Arrays;
 
public class Empty2DArrayMain
{
    public static void main(String[] args) {
        int[][] intArr= new int[0][1];
        System.out.println(Arrays.deepToString(intArr));
    }
}

[]

As Java allows to create empty array with size 0 for int and String.

int[] arr = new int[0];
String[] arr = new String[0];

Similarly it allows empty of int[1] here.

int[][] intArr= new int[0][1];

That’s all about how to initialize empty array in Java.

]]>
https://java2blog.com/initialize-empty-array-java/feed/ 0
Write a Program to Find the Maximum Difference between Two Adjacent Numbers in an Array of Positive Integers https://java2blog.com/program-find-maximum-difference-between-two-adjacent-numbers-array-of-positive-integers/?utm_source=rss&utm_medium=rss&utm_campaign=program-find-maximum-difference-between-two-adjacent-numbers-array-of-positive-integers https://java2blog.com/program-find-maximum-difference-between-two-adjacent-numbers-array-of-positive-integers/#respond Wed, 07 Apr 2021 12:49:07 +0000 https://java2blog.com/?p=13621 In this article, we look at a problem : Given an Array of Positive Integers, Find the [Maximum Difference](https://java2blog.com/maximum-difference-between-two-elements-in-array/ "Maximum Difference") between Two Adjacent Numbers.

For each pair of elements we need to compute their difference and find the Maximum value of all the differences in array.

Let us look at an example, Consider this array:

Sample Array with 10 Elements.

For the above shown array, we have to solve the given problem. Here are the steps which we will follow for the implementation:

  • Firstly, for each pair of elements, we have calculated their difference. We have calculated the Absolute Value of their difference because the array is not sorted and elements on either side can be greater or smaller.
  • In the figure above, we have shown the Diff. value for each such pair. We need to find the Maximum Value among these which for the above case is : 11 for the pair (1,12).
  • We are going to iterate through the array, Arr starting from index 1 and calculate the current difference for each pair as : Arr[i]>Arr[i] - Arr[i-1]code>. We have a max_diff variable which maintains the maximum of all the differences, on each iteration we update the max_diff with current difference.

Note: To calculate the Absolute Value we use Math.abs() in java. The approach is for only Positive Values in the array.

Now, let us have a quick look at the implementation:

import java.util.*;

public class Maximum_Adjacent_Difference
{
  public static void main(String args[])
  {
      // Initialize array with Positive Values.
      int arr[] = new int[]{5,0,10,2,3,6,8,1,12,7};
      // get the size of array.
      int n= arr.length;

      int result = maxDifference(arr,n);      
      System.out.println("The Maximum Difference between Two Adjacent Numbers in the Array is : "+ result);

  }

  public static int maxDifference(int arr[], int n)
  {
      int max_diff = Integer.MIN_VALUE;

      for(int i=1;i<n;i++)
      {
          // For each pair we calculate the Difference.
          int curr_diff = Math.abs(arr[i]-arr[i-1]);
          // Update max_diff if current pair value is the greatest till now.
          max_diff = Math.max(max_diff,curr_diff);
      }

      return max_diff;
  }

}

Output:

The Maximum Difference between Two Adjacent Numbers in the Array is : 11

We implement the same example discussed above in code. Let us analyze the complexity of the code.

Time Complexity: We do a simple single traversal of the array which takes linear time so the time complexitiy is O(n), for n elements in array.

That’s it for the article you can try out this code with different examples and let us know your suggestions or queries.

]]>
https://java2blog.com/program-find-maximum-difference-between-two-adjacent-numbers-array-of-positive-integers/feed/ 0