This code produce output 1 2, when i use J++ and produce 1 when i use ++J
Please help me to understand, im new to java. Still trying to understand how loops work.
int j = 0;
while (j++ < 2)
System.out.print(j);
Printable View
This code produce output 1 2, when i use J++ and produce 1 when i use ++J
Please help me to understand, im new to java. Still trying to understand how loops work.
int j = 0;
while (j++ < 2)
System.out.print(j);
j++ returns the value of j then increments j.
++j increments the value of j then returns the value of j.
Can you work out why you're getting the different results now?
Hi helloworld922
Thank you for your quick response. Yes i managed to understand.
int j = 0;
while (j++ < 2) // j = 0 / j = 1/ j = 2 and condition false.
System.out.print(j); // prints incremented value. so J is 1/ J is 2,
int j = 0;
while (++j < 2) // j = 1/ j = 2 and condition false
System.out.print(j); // prints incremented value. so J is 1.
If you want to study more about these, google for Post Fix and Pre Fix Increment. You will get the clear understanding about these.
j++ return the value of j after that it will make increment
while ++j return from incremented value