• Post Reply Bookmark Topic Watch Topic
  • New Topic

Help Me to Understand the code  RSS feed

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Help me to understand this code....
class Try
{
public static void main(String[] args)
{
int i = 10;
while (i++ <= 10) {
i++;
}
System.out.print(i);
}
}

Result is 13

I can't Understand why it is 13..
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The key is in understanding what the expression i++ does and returns.

It increments i and then returns the old value of i.

With this in mind, can you see what happens?
 
Abhishek Boppudi
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can you please explain when the loop is breaking
 
Greenhorn
Posts: 8
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At the end of the first iteration it is 12. then the while loop checks for the condition again and i++ gives 13 and come out of the loop.


on the first iteration.
i is 10 and incremented by 1 in the while condition.
condition passes and again i is incremented by 1, now it is 12.
then while checks for the condition again and this time it gets incremented by 1.

so it is 13.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
while (i++ <= 10)

The loop continues as long as the result of the expression i++ is less than or equal to 10. So, it stops iterating as soon as the result of the expression is > 10.

Try imagining in your head, line by line, what happens.

First, i is equal to 10. Then we get to the while line. Remember what I wrote in my first reply about what i++ does. What happens to the variable i? What is the result of the expression i++? What is the result of i++ <= 10 (is it true or false)? What happens next? Etc.
 
Abhishek Boppudi
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<p>Got it Thank you Ramesh and Jasper </p>
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!