Results 1 to 3 of 3
  1. #1
    makeawish is offline Member
    Join Date
    Oct 2010
    Posts
    4
    Rep Power
    0

    Default Question about ++x and x++

    In Java, do these two operators mean the same thing?

    x++ and ++x

    So if x = 6

    x++ = 7
    ++x = 7

    And the code below would print 14.

    Java Code:
    System.out.println(x++ + ++x);
    The problem is...

    when x = 6 and

    Java Code:
    	System.out.println(x++ + ++x);
    		System.out.println(x++);
    		System.out.println(++x);
    I get results: 14, 8, 10

    Please can someone explain why? Thank you.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,679
    Blog Entries
    7
    Rep Power
    21

    Default

    Straight from the Java Language Definition:

    Quote Originally Posted by JLS
    15.14.2 Postfix Increment Operator ++

    [ ... ] The value of the postfix increment expression is the value of the variable before the new value is stored.

    15.15.1 Prefix Increment Operator ++

    [ ... ] the value 1 is added to the value of the variable and the sum is stored back into the variable.
    kind regards,

    Jos
    Last edited by JosAH; 10-17-2010 at 06:37 PM.

  3. #3
    suresh.sa is offline Member
    Join Date
    Oct 2010
    Posts
    14
    Rep Power
    0

    Default

    Code:
    System.out.println(x++ + ++x);
    System.out.println(x++);
    System.out.println(++x);

    In this code first line makes x++ -> 7 again ++x -> 8
    so, now the value of x when coming to second line is 8, so it prints the X value as 8,then
    in second line one more increment,so x= 9 now, in third line pre-increment(++x) so it prints x value as 10 for the third SOP statement.


    Regards,
    Suresh. S.A.

Similar Threads

  1. Question mark colon operator question
    By orchid in forum Advanced Java
    Replies: 9
    Last Post: 12-19-2010, 09:49 AM
  2. question
    By berkeley in forum New To Java
    Replies: 5
    Last Post: 06-03-2010, 09:56 PM
  3. help question
    By 99w210 in forum NetBeans
    Replies: 0
    Last Post: 03-08-2010, 06:23 AM
  4. help me in dis question
    By krishan in forum New To Java
    Replies: 10
    Last Post: 02-16-2009, 08:04 PM
  5. question
    By zizou147 in forum New To Java
    Replies: 13
    Last Post: 07-04-2008, 08:05 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •