Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java Language
Expertise: Beginner
Dec 8, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Differences Between C++ and Java

In C++, when a programmer intends to write:
   if (value == 1) {
But, they often make the following mistake:
   if (value = 1) {......
Why doesn't this problem exist in Java?

In C and C++ a non-zero value evaluates to a true boolean expression and a zero value equates to false. Even though C++ has introduced the bool type, this behavior is still supported. Therefore, if you accidentally write the expression value = 1, it evaluates to the integer value of 1, which represents a true boolean value.

You cannot do this in Java because all boolean expressions must evaluate to a value of type boolean, either true or false. It is not possible to coerce integer types to boolean types. Therefore, if you really do mean if(value = 1) in C/C++, you would have to write if((value = 1) == 1) in Java. This makes you more likely to write what you mean.

But the awkward transliteration of the C idiom actually makes it preferable in Java to just assign the value first, and then perform a test, such as:

value = foo;
if(value == bar) {

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date