×

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

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue....

3 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

Java Math acos() Method

The acos() method of Math class computes the trigonometric Arc Cosine (inverse of cosine ) of an angle. The value returned is between 0.0 to pi. Syntax: public static double acos(double a) Parameters: The...

1 minute read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java...

4 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Calculator Program in Java

Calculator Program in Java A calculator performs the basic mathematical operations such as addition, subtraction, multiplication, etc. In this section, we will create a calculator program in Java using switch case...

5 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

Java Rename File

Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible. A file can be renamed using Java's renameTo()...

3 minutes read.

Java Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must...

2 minutes read.

This Operator Using in Java

this keyword in Java has a wide range of applications. this reference variable in Programming language refers to the object of interest. This keyword is used in Java. this keyword is...

5 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.