dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

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


Differences Between C++ and Java

Question:
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?

Answer:
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.

 

 

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