[Java] How to print an array with indexes?
I want to print all elements with their indexes on to console, how can I do that in Java?
1 Answer
4 years ago by Eleven
There is no inbuit util method to do this, we can do ourself by iterating over the array. Following code shows how to do this
public class JavaArrays {
public static void main(String[] args) {
String[] colors = { "blue", "red", "green", "yellow" };
for (int i = 0; i < colors.length; i++) {
System.out.printf("index: %d, element: %s \n", i, colors[i]);
}
}
}
Output:
index: 0, element: blue
index: 1, element: red
index: 2, element: green
index: 3, element: yellow
Try this code online here: https://onecompiler.com/java/3xmtbfggy
4 years ago by Karthik Divi