File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes whta this assignment is ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "whta this assignment is ?" Watch "whta this assignment is ?" New topic

whta this assignment is ?

Mahtab Alam
Ranch Hand

Joined: Mar 28, 2012
Posts: 388

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

Oracle Java Programmer , Oracle SQL Expert , Oracle Java Web Component Developer, Oracle Web Service Developer
K. Tsang

Joined: Sep 13, 2007
Posts: 3130

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

K. Tsang JavaRanch SCJP5 SCJD OCPJP7 OCPWCD5 OCPBCD5 OCPWSD5 OCMJEA5 part 1 part 2/3
Mahtab Alam
Ranch Hand

Joined: Mar 28, 2012
Posts: 388

Why then after assignment x=x++; x is incremented
Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
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

Joined: Aug 16, 2005
Posts: 15081

We have a frequently asked questions page about this subject: Post increment operator and assignment

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
James X Peterson
Whizlabs Java Support
Ranch Hand

Joined: Feb 26, 2013
Posts: 158
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.

Joe Allen
Ranch Hand

Joined: Nov 14, 2012
Posts: 93

int i=1;
int x;

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.

"There are no dumb questions" quoted from HFSJ. "To err is human; to forgive is divine"
I agree. Here's the link:
subject: whta this assignment is ?
It's not a secret anymore!