aspose file tools*
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


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "whta this assignment is ?" Watch "whta this assignment is ?" New topic
Author

whta this assignment is ?

Mahtab Alam
Ranch Hand

Joined: Mar 28, 2012
Posts: 319


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
}
}


http://www.mahtabalam.net , Oracle Java Programmer , Oracle SQL Expert , Oracle Java Web Component Developer
K. Tsang
Bartender

Joined: Sep 13, 2007
Posts: 2615
    
    9

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/OCM-JD OCPJP7 OCPWCD5 OCPBCD5
Mahtab Alam
Ranch Hand

Joined: Mar 28, 2012
Posts: 319

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

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


Joanne
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14423
    
  23

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.

Regards,
James.
Joe Allen
Ranch Hand

Joined: Nov 14, 2012
Posts: 93
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


"There are no dumb questions" quoted from HFSJ. "To err is human; to forgive is divine"
OCPJP 6, OCEJWCD 6
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: whta this assignment is ?