Wednesday, November 19, 2008

What is the Java equivalent of...?

If you're a C/C++ programmer who has more recently moved into Java, you may welcome a new section of the Javamex site loosely entitled What is the Java equivalent of...?

The section aims to examine Java equivalents of some of those awkward little features of C/C++ that people tend to miss or not know how to achieve when they migrate to Java. For example:

What is the Java equivalent of unsigned? In C/C++, you can tell the compiler to treat an integer variable as unsigned by adding the unsigned modifier to its declaration. In Java, integer primitives are generally unsigned. But as we see, bitwise operations generally only require the right shift operator to be modified (so that Java uses >>> where C/C++ uses >> to operate on unsigned values). And for arithmetic operations, judicious use of the AND operator can often get us round the problem.

What is the Java equivalent of const?
In C/C++, this operator tells the compiler not to allow the variable in question (or the value it points to) to be modified. We discuss the nearest Java equivalents, which actually depend on the circumstances.

The section on memory management in Java vs C/C++ looks at equivalents of operators such as new and malloc(), and their opposites. We see that in general, C/C++ puts more burden on the programmer to deal with memory management issues. Possible C/C++ bugs relating to memory management include allocating memory on the stack and then letting it "escape" the function; such bugs are not possible in Java. But there are issues that do crop up in Java that we sometimes need to be aware of, such as how garbage collection object finalization works, or how to deal with a "raw" block of memory (one typical use of malloc() in C/C++).

If you have a suggestion for a new topic in the Java equivalents section, please leave an appropriate comment on this blog. Corrections or suggestions for the existing articles are always welcome too!