Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Java and C# not have implicit conversions to boolean?

Since I started Java it's been very aggravating for me that it doesn't support implicit conversions from numeric types to booleans, so you can't do things like:

if (flags & 0x80) { ... } 

instead you have to go through this lunacy:

if ((flags & 0x80) != 0) { ... } 

It's the same with null and objects. Every other C-like language I know including JavaScript allows it, so I thought Java was just moronic, but I've just discovered that C# is the same (at least for numbers, don't know about null/objects): http://msdn.microsoft.com/en-us/library/c8f5xwh7(VS.71).aspx

Microsoft changed it on purpose from C++, so why? Clearly I'm missing something. Why change (what I thought was) the most natural thing in the world to make it longer to type? What on Earth is wrong with it?

like image 442
Shaun Avatar asked Jun 01 '10 17:06

Shaun


People also ask

Why do we use C in Java?

C is a procedural, low level, and compiled language. Java is an object-oriented, high level, and interpreted language. Java uses objects, while C uses functions. Java is easier to learn and use because it's high level, while C can do more and perform faster because it's closer to machine code.

Is Java or C more useful?

Java is more widely known and versatile, so it's also easier to find a Java developer than a “harder” language such as C++. Overall, C++ can be used for almost anything, but it's not always necessary to use it. Java is usually sufficient and can be much more effective for your project.

How is Java different from C?

Java is a high level language and is more data oriented also known globally as Object-Oriented language. On other hand C is a middle-level language and is more procedure-oriented also known globally as Procedural Programming Language.

Is there any relation between C and Java?

C is a middle-level language as it binds the bridges between machine-level and high-level languages. Java is a high-level language as the translation of Java code takes place into machine language, using a compiler or interpreter. C is only compiled and not interpreted. Java is both compiled and interpreted.


1 Answers

For clarity. It makes the following mistake simply illegal:

int x = ...;  if (x = 0)  // in C: assign 0 to x and always evaluate to false     ....     // never executed 

Note: most modern C / C++ compilers will give a Warning (but not an Error) on this straightforward pattern, but there are many variations possible. It can creep up on you.

like image 112
Henk Holterman Avatar answered Sep 21 '22 08:09

Henk Holterman