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.
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 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:
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();
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:
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();
"+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:
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:
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:
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:
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:
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.
A collection isany 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!");
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:
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.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.