I recently started learning java and I am kinda stumped by this---
the below program determines the speed of the for loop--
public class ForLoopExample {
public static void main(String[] args) {
long startTime = System.nanoTime();
for(int a = 0; a < 10; a++) {
System.out.println(a);
}
long endTime = System.nanoTime();
System.out.println("for loop timing = " + (endTime - startTime) + " ns");
System.out.println("loop completed");
}
}
and the output timing is:
for loop timing = 853716 ns
The program determining the speed of the while loop:
public class WhileLoopExample {
public static void main(String[] args) {
int a=0;
long startTime = System.nanoTime();
while(a < 10) {
System.out.println(a);
a++;
}
long endTime = System.nanoTime();
System.out.println("while loop timing = " + (endTime - startTime) + " ns");
}
}
while loop timing=928358 ns
Why does this happen a detailed explanation would be appreciated.