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);
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
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?
rayan2004 (November 30th, 2012)
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.
Anyone who stops learning is old, whether at twenty or eighty. Anyone who keeps learning stays young. The greatest thing in life is to keep your mind young.
- Henry Ford
rayan2004 (November 30th, 2012)
j++ return the value of j after that it will make increment
while ++j return from incremented value