• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Operator assignment freaks me out?

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What will the following class print ?
class InitTest
{
public static void main(String[] args)
{
int a = 1;
int b = 1;
a = a++;
b = b++ + b;
System.out.println(a+ " "+b);
}
}


How come the answer is 1,3 for the above code? I am not able to get my head around this stuff...please somebody explain. I thought it 2,3.
 
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Karthik,
To compute a, the compiler first sees what a is (1), then does the post-increment (now a = 1), then finally set a to what it saw the first time (which was 1). So, a will be 1 once the "=" is done.
To compute b, you must remember that operands are computed left to right. So, the first operand will be 1, then b is incremented so be = 2. Then the second operand is retrieve (which is b, now 2). Then the "+" is done, using 2 and 1. So, be = 3.
Does that make sense?
 
Ranch Hand
Posts: 384
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hey Karthik,
this is a great thread to read on the post increment operator.
post increment operator
but in quick terms.
int a = 1;
int b = 1;
a = a++; //a=a; then add 1 to a, so a=1; the last post increment did happen but did not get assigned to anything
b = b++ + b; //b=b++ + b; b=1 + 2 b=3 same here because it increments after it has done the last thing.
System.out.println(a+ " "+b);
Davy
[ April 19, 2004: Message edited by: Davy Kelly ]
 
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just remember x++ adds one to x but it actually returns x. ++x adds one to x and returns x + 1.
 
author
Posts: 9050
21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Three guesses what my comment is?
 
reply
    Bookmark Topic Watch Topic
  • New Topic