Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Marcus Green exam #3 question 54

 
Karlon Wu
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question 54)
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
The answer is 4, i.e., i=0. But I still cannot understand why
{int i=0; i=i++;} will be 0. Can somebody explain why? Thank you.
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karlon
Check out this thread for a good explaination http://www.javaranch.com/ubb/Forum24/HTML/009768.html

 
Karlon Wu
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Dave. I'll get the exam after 3 days. It really helps me.
 
easwaran ram
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

you should understand the difference between assignments and uninar incremental operator.
when you put
i=0;
i=i+10;
it assignes value to i a value 0+10=10
where as
i=i++
it assignes value
i=i and then increments,
ie i=0
when you pass as a parameter it passes only the copy of the value, hence the original value never changes. that is why you get 0 as output in this code.

Originally posted by Dave Vick:
Karlon
Check out this thread for a good explaination http://www.javaranch.com/ubb/Forum24/HTML/009768.html

 
easwaran ram
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
check this
public class Inc{
public static void main(String argv[]){
Inc inc = new Inc();
int i =0;
i=i+10;
i+=++i;
inc.fermin(i);
System.out.println(i);
i+=++i;
System.out.println(i);
}
void fermin(int i){
i+=100;
}
}
Originally posted by Dave Vick:
Karlon
Check out this thread for a good explaination http://www.javaranch.com/ubb/Forum24/HTML/009768.html

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic