[Java] How to print even elements from an array?
I want to print only elements which are in even indexes, how to do that in Java?
1 Answer
4 years ago by Eleven
We can loop through the array using for loop and check if the index is even of now and print the element. Following code shows how to do that
public class JavaArrays {
public static void main(String[] args) {
String[] colors = { "blue", "red", "green", "yellow" };
for (int i = 0; i < colors.length; i++) {
if (i % 2 == 0) {
System.out.println(colors[i]);
}
}
}
}
Output
blue
green
Try this online: https://onecompiler.com/java/3xmtcbsgr
4 years ago by Karthik Divi