[Java] how to print odd elements from an array?
I want to print only elements which are in odd indexes, how to do that in Java?
1 Answer
3 years ago by Eleven
We can loop through the array using for loop and check if the index is odd or not 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 == 1) {
System.out.println(colors[i]);
}
}
}
}
Output
red
yellow
Try this online: https://onecompiler.com/java/3xmtchr84
3 years ago by Karthik Divi