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

whta this assignment is ?

 
Mahtab Alam
Ranch Hand
Posts: 391
1
Java MySQL Database PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

class A
{
public static void main(String args[])
{
int x=1;
x=x++; //even it is post increment but after this assignment x should have value 2
System.out.print(x); // prints 1
}
}
 
K. Tsang
Bartender
Posts: 3521
16
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to understand the concept of post-increment and pre-increment.

Post-increment is assign then increment
Pre-increment is increment then assign

So the following code

 
Mahtab Alam
Ranch Hand
Posts: 391
1
Java MySQL Database PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why then after assignment x=x++; x is incremented
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mahtab Alam wrote:Why then after assignment x=x++; x is incremented

That question has been asked and answered many times here on the ranch. SearchFirst or try the FAQs
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15485
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We have a frequently asked questions page about this subject: Post increment operator and assignment
 
James X Peterson
Whizlabs Java Support
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mahtab Alam,

lets say x=i++;

here first the value of i will be assigned to x and then i value is incremented.
if value of i =5 then after the above line x value will be 5 and i value will be 6.

Regards,
James.
 
Joe Allen
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
James,

int i=1;
int x;

x=i++;
System.out.println(x);//x = 1 here, which is clear

Hopefully I am not beating a dead horse here, but what is confusing here is

int x=1;

x=x++;//x on the left side is assigned 1, but x on the right hand side is supposed to be postincremented at the next System.out.println, right? But it looks like x=x++ and x=x are the same here.
System.out.println(x);//x=1
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic