• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

++ operator

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I have a doubbt in the following code

public class chaptwo
{
public static void main(String args[])
{
int i = 0, j = 1;
if ((i++ == 1) && (j++ == 2)) {
i = 42;
}
System.out.println("i = " + i + ", j = " + j);
}
}

The answer is i =1, j= 1

Why isn't i = 42 ?

I thought this is similar to the following code

public class chaptwo
{
public static void main(String args[])
{
int i =0;
i = i++;
System.out.println("i = " + i);
}
}

where i = 0

Please explain.

Thank you
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There are a few things going on:

First, the ++ is a post operation. It gets done after the evaluation of the expression for the if statement. This means that the expression evaluates to false, and i is not set to 42.

Second, the && will short circuit. Since the left side fails, there is no reason to evaluate the right side. Hence j will not get incremented.

Henry
 
gayatri ganesh
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank You Henry,

I forgot the If condition

Gayatri
reply
    Bookmark Topic Watch Topic
  • New Topic