Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

No increment at all??

 
sonir shah
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will happen when you attempt to compile and run the following code?
public class Inc{
public static void main(String argv[]){
Inc inc = new Inc();
int i =0;
inc.fermin(i);
i = i++;
System.out.println(i);
}
void fermin(int i){
i++;
}
}
1) Compile time error
2) Output of 2
3) Output of 1
4) Output of 0

Ans : 4)
why???
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sonir,
Before asking questions, you should use the search feature here at the ranch. This topic has been covered considerably and is old news. Here are for some links:
First Link
Second Link
Regards,
Manfred.
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Read the Campfire Story Pass by Value Please
 
Patrick Mugabe
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you say i=i++;
The i on the left hand side is assigned the value of i on the right hand side BEFORE the increment.
However when you say i=++i; then i on the left hand side is assigned the value of i on the Right hand side AFTER the increment.
Thus if you go to your code where it says:
i = i++;
System.out.println(i); and change it to:
i = ++i;
System.out.println(i); then your output will be one(1).
I hope this will help. For further information read on post increment and pre increment.(You will normally find this section under for loops)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic