Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How does java give a correct answer??

Status
Not open for further replies.

sreenath205

Programmer
Dec 9, 2003
17
IN
Hi all,



Code:
-------------------------------------------------------

class test
{
  public static void main(String args[])
    {
     int i,j;
     i=5;
     j=++i*++i;
     System.out.println(j);
    }

} 

------------------------------------------------------------
Out put :42
When the same code in c/c++ gives unpredictable answer ,how is java doing the magic




Thanks in advance
Sreenath m
 
how do you know what is the correct answer? Is stupid to talk about a correct answer in an incorrectly formed expression. Look at such expression:

j += j++ + ++j;
a very bad programming style, however for the compiller is ok.

Ion Filipski
1c.bmp
 
ANSI C always gives 49, Java 42.

None ANSI would give different values maybe.

The reason (I think) is this :

With C, the value of variables in muliplications are worked out the first - and then the * is done.

So the first ++i increments i from 5 to 6.
The second from 6 to 7.
But i in both cases here are now 7.
Then the multiplication is done which is 7*7 - ie 49.

But in java, it is not done like this, and the values basically equate to 6*7 - java works out that the first ++i is 6, and the second is 7 , hence 6*7=42.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top