Features of C++ versus Java
- Java, like C++, has primitive types for efficient access. In Java, these are boolean, char, byte , short, int, long, float, and double. All the primitive types have specified sizes that are machine-independent for portability (this must have some impact on performance, varying with the machine). Type-checking and type requirements are much tighter in Java.
- All objects of non-primitive types can be created only via new. There’s no equivalent to creating non-primitive objects “on the stack” as in C++. All primitive types can be created only on the stack, without new. There are wrapper classes for all primitive classes so equivalent heap-based objects can be created with new. (Arrays of primitives are a special case: they can be allocated via aggregate initialization as in C++, or by using new).
- Java has method overloading that works virtually identically to C++ function overloading.
- Java does not support default arguments.
- There’s no goto in Java. The one unconditional jump mechanism is the break label or continue label, which is used to jump out of the middle of multiply-nested loops.
- There is method overloading, but no operator overloading in Java. The String class does use the + and += operators to concatenate strings and String expressions use automatic type conversion, but that’s a special built-in case.
- If the access to a Java handle fails, an exception is thrown. This test doesn’t have to occur right before the use of a handle; the Java specification just says that the exception must somehow be thrown. Many C++ runtime systems can also throw exceptions for bad pointers.
- Exception specifications in Java are vastly superior to those in C++. Instead of the C++ approach of calling a function at run-time when the wrong exception is thrown, Java exception specifications are checked and enforced at compile-time. In addition, overridden methods must conform to the exception specification of the base-class version of that method: they can throw the specified exceptions, or exceptions derived from those. This provides much more robust exception-handling code.
|