Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

incremetor

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here are two programs using the incrementor x++ or x-- in a different way:
Program1:
class incDec
{
public static void main(String args[]) {
int x;
int y;
x = 1;
y = x++;
System.out.print(y + "\n");
x = 1;
y = ++x;
System.out.print(y + "\n");
x = 1;
y = x--;
System.out.print(y + "\n");
x = 1;
y = --x;
System.out.print(y + "\n");
}
}
Program 2:
class incdem
{
public static void main(String args[]) {
int x;
int y;
x = 1;
x = x++;
System.out.print(x + "\n");
x = 1;
x = ++x;
System.out.print(x + "\n");
x = 1;
x = x--;
System.out.print(x + "\n");
x = 1;
x = --x;
System.out.print(x + "\n");
}
}
=> Both programms use the incrementor in the way: x = x ++
y = x ++
Result of both programms: 1 - 2 - 1 -
---------
program 3:
class incDe
{
public static void main(String args[]) {
int x;
int y;
x = 1;
x++;
System.out.print(x + "\n");
x = 1;
++x;
System.out.print(x + "\n");
x = 1;
x--;
System.out.print(x + "\n");
x = 1;
--x;
System.out.print(x + "\n");
}
}
Uses incrementor in the way: x++, x++ (instead of y = x++)
Result: 2 - 2 - 0 - 0
*************************************************
Why the different results between
x++
System.out.println(x)
and
y = x++
System.out.println(x)
???
******************************************+

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the result of program 1+2 is
1-2-1-0
 
Greg Harris
Ranch Hand
Posts: 1012
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the increment is performed before the value is assigned if it is like this:
x = ++x;
otherwise, it performed after the value is assigned. so, when it says:
x = 1;
x = ++x;
x will be equal to 2 when it is printed. but, when it is like:
x = 1;
x = x++;
x is still equal to 1 because the increment was performed after the value was assigned.
same thing with y... and same thing with --.
 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Thomas Markl:
the result of program 1+2 is
1-2-1-0

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic