The moose likes Beginning Java and the fly likes thie output is different in C and JAVA Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "thie output is different in C and JAVA" Watch "thie output is different in C and JAVA" New topic

thie output is different in C and JAVA

sharma sachin

Joined: Nov 13, 2009
Posts: 24

The output of the program is 1 but in C the output of the same program is 2
can any one explain why it is happening

and the other query is in java the size of int and float is 32 bits
then according to the size float value can assigned in to the int variable just like C language
but in case of JAVA it is achieve with the help of explicit-typecasting why it is so???
Greg Charles

Joined: Oct 01, 2001
Posts: 2968

For your first question, I think what happens is Java picks out the value of i before it's incremented (1), then increments it (making it 2) then assigns the picked out value back to i (making it 1 again). With C, edge cases like that can actually depend on which compiler you use. Ultimately though, the solution is the same in both C in Java: don't write code like that.

Java is stricter about casting than C is, and when you cast a float to int, for example, you are telling it to truncate off the fractional part. C is a lot more flexible. I'm a bit fuzzy on what would happen if you just assigned a float to an int variable, but when you access things through pointers, it would be possible to just interpret the bits in the float as an int, and the numerical values would only be vaguely related to each other.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46389
You only think it returns 2 in C. You need to try it on several different compilers, and see how many of them return 2.
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

This may help.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Anand Hariharan

Joined: Aug 22, 2006
Posts: 272

"Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away." -- Antoine de Saint-Exupery
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46389
Anand Hariharan wrote:
That link has it exactly right.
I agree. Here's the link:
subject: thie output is different in C and JAVA
It's not a secret anymore!