*
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 Murach's Java Servlets and JSP this week in the Servlets 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: 222


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
K. Tsang
Bartender

Joined: Sep 13, 2007
Posts: 2231
    
    7

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
Mahtab Alam
Ranch Hand

Joined: Mar 28, 2012
Posts: 222

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

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

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 7 API documentation
Scala Notes - My blog about Scala
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 ?
 
Similar Threads
Difference between additive & assignment operator
Initialization question
infinite for loop
Anonymous Inner class
Increment Operator and Assignment Operator