how-to-print-an-array-in-java?

“`html

When working with Java, we frequently need to showcase the components of an array for debugging or output reasons. By printing the components of an array, we can verify data, confirm the accuracy of calculations, and troubleshoot issues. Java offers various approaches to print an array.

In this post, we will explore how to print an array in Java utilizing different methods.

Table of Contents:

Techniques to Print an Array in Java

An array in Java is a data structure utilized to hold several values of the same data type under a single variable name. Let’s delve into all the various methods to print an array in Java:

Note: Although we have discussed several methods to print an array in Java, the easiest and most commonly used approach is the for loop.

Technique 1: Using for Loop to Print an Array in Java

To print an array in Java, we employ a for loop. This is the most straightforward method for displaying the elements of an array.

Example:

Java

Code Copied!

var isMobile = window.innerWidth “);

editor73356.setValue(decodedContent); // Set the default text editor73356.clearSelection();

editor73356.setOptions({ maxLines: Infinity });

function decodeHTML73356(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard73356() { const code = editor73356.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(“.maineditor73356 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor73356 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode73356() {

var code = editor73356.getSession().getValue();

jQuery(“#runBtn73356 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”, data: { language: “java”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output73356”).html(“

"+data+"

“); jQuery(“.maineditor73356 .code-editor-output”).show(); jQuery(“#runBtn73356 i.run-code”).hide(); } })

}

function closeoutput73356() { jQuery(“.maineditor73356 .code-editor-output”).hide(); }

// Attach event listeners to the buttons document.getElementById(“copyBtn73356”).addEventListener(“click”, copyCodeToClipboard73356); document.getElementById(“runBtn73356”).addEventListener(“click”, runCode73356); document.getElementById(“closeoutputBtn73356”).addEventListener(“click”, closeoutput73356);

Output:

Using for Loop to Print an Array in Java

Technique 2: Using while

“““html

Loop to Display an Array in Java

A while loop can also be utilized to display an array in Java. The while loop accepts a condition as its parameter and continues executing the block of code inside the loop as long as the condition remains true.

Illustration:

Java

Code Copied!

var isMobile = window.innerWidth “”);

editor25062.setValue(decodedContent); // Set the default text editor25062.clearSelection();

editor25062.setOptions({ maxLines: Infinity });

function decodeHTML25062(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard25062() { const code = editor25062.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(“.maineditor25062 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor25062 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode25062() { var code = editor25062.getSession().getValue();

jQuery(“#runBtn25062 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”, data: { language: “java”, code: code, cmd_line_args: “”, variablenames: “”, action: “compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output25062”).html(“

" + data + "

“); jQuery(“.maineditor25062 .code-editor-output”).show(); jQuery(“#runBtn25062 i.run-code”).hide(); } }); }

function closeoutput25062() { var code = editor25062.getSession().getValue(); jQuery(“.maineditor25062 .code-editor-output”).hide(); }

// Attach event listeners to the buttons document.getElementById(“copyBtn25062”).addEventListener(“click”, copyCodeToClipboard25062); document.getElementById(“runBtn25062”).addEventListener(“click”, runCode25062); document.getElementById(“closeoutputBtn25062”).addEventListener(“click”, closeoutput25062);

Result:

Using while Loop to Display an Array in Java

Method 3: Utilizing for-each Loop to Display an Array in Java

The for-each loop serves to traverse an array with a more straightforward syntax. The loop automatically cycles through all elements in the array, eliminating the need to manage the array index manually.

Illustration:

Java

Code Copied!

var isMobile = window.innerWidth “”);

editor55361.setValue(decodedContent); // Set the default text editor55361.clearSelection();

editor55361.setOptions({ maxLines: Infinity });

function decodeHTML55361(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Code execution function will be added here…
“““javascript
// Function to duplicate code to clipboard
function duplicateCodeToClipboard55361() {
const codeContent = editor55361.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(codeContent).then(() => {
// alert(“Code copied to clipboard!”);
jQuery(“.maineditor55361 .copymessage”).show();
setTimeout(function() {
jQuery(“.maineditor55361 .copymessage”).hide();
}, 2000);
}).catch(err => {
console.error(“Error duplicating code: “, err);
});
}

function executeCode55361() {
var codeContent = editor55361.getSession().getValue();

jQuery(“#runBtn55361 i.run-code”).show();
jQuery(“.output-tab”).click();

jQuery.ajax({
url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”,
type: “post”,
data: {
language: “java”,
code: codeContent,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var resultArray = response.split(“~”);
var outputData = resultArray[1];

jQuery(“.output55361”).html(“

"+outputData+"");
            jQuery(".maineditor55361 .code-editor-output").show();
            jQuery("#runBtn55361 i.run-code").hide();
        }
    });
}

function hideOutput55361() {    
    jQuery(".maineditor55361 .code-editor-output").hide();
}

// Assign event listeners to the buttons
document.getElementById("copyBtn55361").addEventListener("click", duplicateCodeToClipboard55361);
document.getElementById("runBtn55361").addEventListener("click", executeCode55361);
document.getElementById("closeoutputBtn55361").addEventListener("click", hideOutput55361);


Output:

Using for-each Loop to Print an Array in Java

Technique 4: Utilizing Arrays.toString() Method to Output an Array in Java

Arrays.toString() is a predefined method in the java.util.Arrays class that transforms an array into a comprehensible string. It formats the array automatically, delineating elements with commas and enclosing them in square brackets.

Sample:

Java
Code Duplicated!

Output:

Using Arrays.toString() Method to Print an Array in Java

Technique 5: Utilizing Arrays.deepToString() Method to Exhibit an Array in Java

Arrays.deepToString() is beneficial for outputting a multidimensional array. It functions akin to Arrays.toString(), but recursively transforms elements of nested arrays into a clear string.

Sample:

Java
Code Copied!

Code:

Using Arrays.deepToString() Method to Print an Array in Java

Method 6: Utilizing Arrays.asList() Method to Display an Array in Java

Arrays.asList() transforms an array into a fixed-size list. While it permits you to use List methods such as toString(), it does not facilitate resizing (e.g., adding or removing elements).

Example:

Java
Code Copied!

Output:

image 129

Technique 7: Utilizing Java Iterator Interface to Display an Array in Java

The Iterator interface in Java is a component of the Java Collections Framework that enables you to traverse through the items of a collection (for example, a List) one at a time.

Instance:

Java
Code Copied!

Output:

Utilizing Arrays.asList() Method to Display an Array in Java

Technique 8: Implementing Java Stream API to Show an Array in Java

The Java Stream API provides a contemporary approach to handle collections and arrays. By utilizing Streams with forEach(), you can effortlessly print the components of an array.

1. Java stream() Method

The stream() method belongs to the Java Stream API. It's utilized to transform a collection or array into a stream for processing data in a functional manner.

Syntax:

Arrays.stream(array)

2. Java forEach() Method

The forEach() method serves to iterate over items of a collection or a stream, allowing the printing of stream elements in each iteration.

Syntax:

collection.forEach(action);
stream.forEach(action);

 Where,

  • A collection is any List, Set, or another Collection.
  • A stream is a flow of data.
  • Action is a lambda expression or method reference dictating what to do with each item.

Instance:

Java

Code Successfully Copied!

var isMobile = window.innerWidth ");

editor84940.setValue(decodedContent); // Assign the default text editor84940.clearSelection();

editor84940.setOptions({ maxLines: Infinity });

function decodeHTML84940(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard84940() { const code = editor84940.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code copied to clipboard!");

jQuery(".maineditor84940 .copymessage").show(); setTimeout(function() { jQuery(".maineditor84940 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode84940() {

var code = editor84940.getSession().getValue();

jQuery("#runBtn84940 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "java", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output84940").html("

"+data+"");
									jQuery(".maineditor84940 .code-editor-output").show();
									jQuery("#runBtn84940 i.run-code").hide();

} })

}

function closeoutput84940() { var code = editor84940.getSession().getValue(); jQuery(".maineditor84940 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn84940").addEventListener("click", copyCodeToClipboard84940); document.getElementById("runBtn84940").addEventListener("click", runCode84940); document.getElementById("closeoutputBtn84940").addEventListener("click", closeoutput84940);

Outcome:

Utilizing Java Stream API to Display an Array in Java

Summary

In this piece, we have explored various techniques to output an array in Java. Among the different approaches, the most commonly employed technique is utilizing a for loop. You can adopt any of the aforementioned methods to display the array's elements. For those seeking to become proficient in Java, our Java Course may prove beneficial.

Frequently Asked Questions

Q1. Is it permissible to alter the elements of an array using a for-each loop?

No, altering elements of a primitive array (e.g., int[], boolean[], etc.) is not possible through a for-each loop as it operates on copies of each element (pass-by-value). Nevertheless, for an array of objects, you can modify their attributes since the references continue to point to the same objects in memory.

Q2. Is it feasible to print a multidimensional array using Arrays.toString()?

No, Arrays.toString() functions solely with one-dimensional arrays. We must use Arrays.deepToString() for multidimensional arrays.

Q3. Can I employ the Stream API with arrays of primitive types?

Yes, Arrays.stream() accommodates arrays of primitive types such as int[].

Q4. How to display an array in Java without using a loop?

You can display an array in Java without a loop by utilizing built-in methods from the Arrays class, specifically Arrays.toString().

Q5. How can I ascertain the length of an array?

You can determine the length of an array in Java via the array.length property.

The article How to Print an Array in Java? first appeared on Intellipaat Blog.

```


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This