×

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a result, we may use an array to hold a fixed set of elements. In Java, we cannot print array elements directly; instead, we must utilise Arrays. deepToString() or function toString() { [native code] }() to print array elements. If we wish to print a one-dimensional array, use the function toString() { [native code] }() function; if we need to print a two-dimensional or three-dimensional array, use the deepToString() method. Java arrays enable programmers to store data of a same type. This homogeneous data structure contains information in a single memory region. Printing the array elements reveals the values contained within the Java array.

However, with Java, we cannot directly print array elements. Java has several methods for printing a two-dimensional array, such as nested for-loops, for-each loops, arrays.deepToString() function, and so on. Each method follows a different strategy, but they all achieve the same goal: printing a 2D array. We define a function called Print array(), which takes as input the array to be printed as well as its size. As mentioned in previous sections, the method internally employs a for loop to output an array. f the passed-in object is null, the function returns null; otherwise, it calls obj.toString(). To print the output, System.out.println() eventually calls function toString().

If the class of that object does not override the implementation of Object.toString(), the function will be called getClass is returned by Object.toString() ().getName()+‘@’+Integer.hashCode() = toHexString() It just returns "class name @ object's hash code."The [says that this is an array, and I stands for int in our previous output [I@74a14482 ]. (the type of the array). The array's hash code is represented in unsigned hexadecimal as 74a14482.It is recommended practise to override the Object.toString() method whenever we create our own custom classes.

Arrays cannot be printed in Java using a simple System.function out.println(). We'll be using the function toString() method of the Arrays class in Java's util package. This technique assists us in obtaining the array's String representation. This string can be simply printed using the print() or println() methods. They were provided as convenience ways to eliminate the requirement for you to design a manual for loop.In the case of ArrayLists created with primitive data types, the println command can be used directly. String, integer, float, long, double, and boolean are examples of primitive data types in Java. This method cannot be used to print a list that contains data that does not match these types.

In Java, you may print an array in the following ways:

  • for loop in Java
  • For-each loop in Java
  • Arrays.toString() function in Java
  • deepToString() function in Java
  • Arrays.asList() function in Java
  • Java Iterator API Java Stream API

For loop in Java:

A for loop in Java is used to run a series of instructions repeatedly until a specific condition is met.

In the following example, we've built a four-element array and initialised it. We used a for loop to retrieve the data from the array. It is the most commonly used method for printing arrays in Java.

PrintArrExample.java

public class PrintArrExample
{    
public static void main(String args[])  
{    
//declaring and instantiating of array  
int a[]=new int[3];     
//initializing elements   
a[0]=10;  
a[1]=20;    
a[2]=50;    
// using for loop transverse
for(int i=0;i<a.len;i++)    
System.out.println(a[i]);    
}  
}    

Output:

10
20
50

Using Java For-each loop:

The for-each loop in Java is also used to explore an array or collection. It operates on an elemental level. It returns elements in the defined variable one by one.

In the following example, we built a String array of length four and initialised it with elements. To explore the array, we utilised a for-each loop.

PrintArrExample.java

public class PrintArrExample 
{  
public static void main(String args[])   
{  
// declaring and instantiating of array   
Str[] city = new Str[3];  
//elements initialization   
c[0] = "Hyderabad";  
c[1] = "Goa";  
c[2] = "Mumbai";  
// array using for-each loop transversing 
for (String str : c)   
{  
System.out.println(str);  
}  
}  
}  

Output:

Hyderabad
Goa
Mumbai

Arrays.toString() function in Java:

Arrays.toString() is a static method of the Arrays class, which is part of the java.util package. It includes several techniques for manipulating arrays.

Syntax:

public static String toStr(int[] b) 

As an argument, it takes an array of any primitive type. It produces a datatype of an array with a list of the array's elements. String.valueOf(int) is used to convert array elements to String.

Using Java toString() method:

PrintArrExample.java

import java.util.Arrays;  
public class PrintArrExample 
{  
public static void main(String[] args)  
{  
//declaration and initialization of an array  
int arr[] = {4,-1, 5, -19, 3};  
//representating the array and returning the value  
System.out.println(Arrays.toStr(arr));  
}  
}  

Output:

[4, -1, 5, -19, 3]

Using Arrays deepToString() function:

The deepToString() function of the Java Arrays class converts multidimensional arrays to strings.

Syntax:

public static String deepToStr(Obj[] b) 

As an argument, it accepts an array. It returns the array's String representation.

Using deepToString() method:

In the following example, we generated a two-dimensional float array.

import java.util.Arrays;  
public class PrintArrExample
{  
public static void main(String[] args)   
{  
//declaring and initializating of 2-D array of data type called float   
float[][] arr= {{11.2f, 2.6f}, {4.9f, 4.2f}, {5.0f, 2.2f}};  
System.out.println(Arrays.deepToStr(arr));  
}  
}   

Output:

[[11.2, 2.6], [4.9, 4.2], [5.0, 2.2]]

Arrays.asList() function in Java:

Java Arrays.asList() is a static method of the java.util package's Java Arrays class. It serves as a link between array-based and collection-based APIs.

Syntax:

public static <L> List<L>asList(L...b) 

The method also makes it simple to generate a fixed-size list with a large number of elements.

obj=Arrays.toStr(arr[] b) ListL>

As an argument, it takes an array. It returns the array's list view.

Using asList() method:

PrintArrExample.java

import java.util.Arrays;  
public class PrintArrExample  
{  
public static void main(String [] args)  
{  
String[] stringArray={"Hi","Sahi"};  
System.out.println(Arrays.asList(stringArr));  
}  

Output:

[Hi, Sahi]

Iterator interface in Java:

The Java Iterator interface is part of the java.util package. Iterator objects are generated by invoking the iterator() function. It is available in the Collection interface. It gives back an iterator.

Iterator interface illustration:

In the following example, we declare an array and populate it with elements. We first transform the supplied array to a list using the Arrays.asList() function since iterator allows us to traverse the collection and then use the collection class's iterator() method.

PrintArrExample.java

import java.util.Arrays;  
import java.util.Iterator;  
public class PrintArrExample  
{  
public static void main(String[] args)   
{  
Double[] arr = { 2.5, 4.6, 3.2, 4.1, 2.9};  
Iterator<Double> it = Arrays.asList(arr).itr();  
while(itr.hasN()){  
System.out.println(itr.n());  
}  
}  
}  

Output:

2.5
4.6
3.2
4.1
2.9

The Java Stream API

A Java Stream is a data structure that can be computed on the fly. It does not keep any data. It works with the source data structure, such as a collection or an array. Internal iteration is implemented using the Java stream API. It has various characteristics, including sequential and parallel execution.

Java stream() function:

Java stream() is a static function of the java.util package's Java Arrays class. It is used to obtain an array's sequential stream.

Syntax:

public static <t>Stream stream(t[] arr)

Where t is the array type. The method takes an array of elements to convert into a sequential stream. It returns a sequential IntStream whose source is the supplied array.

Java forEach() function:

It's a final operation. It does not ensure that the encounter sequence of the stream will be respected.

Syntax:

void forEach(Consumer<? super t> action)

As an argument, the method accepts an action. Each element is subjected to non-interfering action. It produces no results.To print an array from a stream, we can use one of two terminal procedures.

stream.forEach() function example:

We used a different method to print an array in the following example. The forEach() method is used to loop through all of the stream's elements. The Iterable and Stream interfaces define it.

We utilised System.out, which is a reference to an object, within the forEach() method. It is a standard output stream. It includes a method named println (). It is an overloaded method that can accept any parameter. When we place the println() method behind the member access operator (::), it transforms into an expression.

PrintArrExample.java

import java.util.Arrays;  
public class PrintArrExample 
{  
public static void main(String[] args)   
{  
String[] array= {"C", "C++", "Python"};  
Arrays.str(array).forEach(System.out::println);  
}  
}  

Output:

C
C++
Python

Related Topics

Example of Static import in Java

Static keyword Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is...

3 minutes read.

Deadlock in Java

Deadlock is when two or more processes wait for the state to do their tasks, but none of them can do so. It is a very common problem that one...

6 minutes read.

Static class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM is mostly...

7 minutes read.

Java Math max() Method

The max() method of Math class returns the greater of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double max(double a, double b)public...

2 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Java String hashCode() method

Java String hashCode() method returns hash code for current String. hash code for string object is computed as s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1] Using int...

2 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.

Java Abstraction

Java Abstraction Abstraction is an advanced feature of Java to make it transparent. The main motive behind the abstraction is to deal with ideas, not with events. Abstraction is a process...

4 minutes read.