!= operator in Java for loop

  • A+
Category:Languages

How come the below code prints "The value of J is: 1000". I would've thought that the "j != 1000" would evaluate to false in all instances (Because 1000 mod 19 is not 0), hence making it an infinite loop?

public static void loop2() {     int j = 0;      for(int i=0;j != 1000;i++) {         j = j+19;     }     System.out.println("The value of J is: " + j); } 

 


you defined your j as int. Integers have a defined range. The Max-Value of the signed Integer is 2,147,483,647. As soon as you go over that value you have a bit-overflow which causes the whole thing to start at the min value. In case of Integers thats -2,147,483,648. At some point in the loop you get to a negativ starting value of the loop which leads your loop to land at 981+19 = 1000 >>> loop is exited, cause J equals your exit-condition of your for-loop.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: