Comparison of Java and C++


This is a comparison of Java and C++, two prominent object-oriented programming languages.

Design aims

The differences between the programming languages C++ and Java can be traced to their heritage, as they have different design goals.
C++ was designed for systems and applications programming, extending the procedural programming language C, which was designed for efficient execution. To C, C++ added support for object-oriented programming, exception handling, lifetime-based resource management, generic programming, template metaprogramming, and the C++ Standard Library which includes generic containers and algorithms, and many other general purpose facilities.
Java is a general-purpose, concurrent, class-based, object-oriented programming language that is designed to minimize implementation dependencies. It relies on a Java virtual machine to be secure and highly portable. It is bundled with an extensive library designed to provide a full abstraction of the underlying platform. Java is a statically typed object-oriented language that uses a syntax similar to C++. It includes a documentation system called Javadoc.
The different goals in the development of C++ and Java resulted in different principles and design trade-offs between the languages. The differences are as follows:
C++Java
Extends C with object-oriented programming and generic programming. C code can most properly be used.Strongly influenced by C++/C syntax.
Compatible with C source code, except for a few corner cases.Provides the Java Native Interface and recently Java Native Access as a way to directly call C/C++ code.
Write once, compile anywhere.Write once, run anywhere/everywhere.
Allows procedural programming, functional programming, object-oriented programming, generic programming, and template metaprogramming. Favors a mix of paradigms.Allows procedural programming, functional programming and generic programming, but strongly encourages the object-oriented programming paradigm. Includes support for creating scripting languages.
Runs as native executable machine code for the target instruction set.Runs on a virtual machine.
Provides object types and type names. Allows reflection via run-time type information.Is reflective, allowing metaprogramming and dynamic code generation at runtime.
Has multiple binary compatibility standards and Itanium/GNU ).Has one binary compatibility standard, cross-platform for OS and compiler.
Optional automated bounds checking.All operations are required to be bound-checked by all compliant distributions of Java. HotSpot can remove bounds checking.
Native unsigned arithmetic support.Native unsigned arithmetic unsupported. Java 8 changes some of this, but aspects are unclear.
Standardized minimum limits for all numerical types, but the actual sizes are implementation-defined. Standardized types are available via the standard library .Standardized limits and sizes of all primitive types on all platforms.
Pointers, references, and pass-by-value are supported for all types.All types are always passed by value.
Memory management can be done manually via new / delete, automatically by scope, or by smart pointers. Supports deterministic destruction of objects. Garbage collection ABI standardized in C++11, though compilers are not required to implement garbage collection.Automatic garbage collection. Supports a non-deterministic finalize method use of which is not recommended.
Resource management can be done manually or by automatic lifetime-based resource management.Resource management must generally be done manually, or automatically via finalizers, though this is generally discouraged. Has try-with-resources for automatic scope-based resource management.
It can also be done using the internal API sun.misc.Unsafe but that usage is highly discouraged and will be replaced by a public API in an upcoming Java version.
Supports classes, structs, and unions, and can allocate them on the heap or the stack.Classes are allocated on the heap. Java SE 6 optimizes with escape analysis to allocate some objects on the stack.
Allows explicitly overriding types, and some implicit narrowing conversions.Rigid type safety except for widening conversions.
The C++ Standard Library was designed to have a limited scope and functions, but includes language support, diagnostics, general utilities, strings, locales, containers, algorithms, iterators, numerics, input/output, random number generators, regular expression parsing, threading facilities, type traits and Standard C Library. The Boost library offers more functions including network I/O.
A rich amount of third-party libraries exist for GUI and other functions like: Adaptive Communication Environment, Crypto++, various XMPP Instant Messaging libraries, OpenLDAP, Qt, gtkmm.
The standard library has grown with each release. By version 1.6, the library included support for locales, logging, containers and iterators, algorithms, GUI programming, graphics, multi-threading, networking, platform security, introspection, dynamic class loading, blocking and non-blocking I/O. It provided interfaces or support classes for XML, XSLT, MIDI, database connectivity, naming services, cryptography, security services, print services, and web services. SWT offered an abstraction for platform-specific GUIs, but was superseded by JavaFX in the latest releases ; allowing for graphics acceleration and CSS-themable UIs. Although it doesn't support any kind of "native platform look" support.
Operator overloading for most operators. Preserving meaning is highly recommended.Operators are not overridable. The language overrides + and += for the String class.
Single and multiple inheritance of classes, including virtual inheritance.Only supports single inheritance of classes.
Compile-time templates. Allows for Turing complete meta-programming.Generics are used to achieve basic type-parametrization, but they do not translate from source code to byte code due to the use of type erasure by the compiler.
Function pointers, function objects, lambdas, and interfaces.Functions references, function objects and lambdas were added in Java 8. Classes can be passed as references as well through SomeClass.class
No standard inline documentation mechanism. Third-party software exists.Extensive Javadoc documentation standard on all system classes and methods.
const keyword for defining immutable variables and member functions that do not change the object. Const-ness is propagated as a means to enforce, at compile-time, correctness of the code with respect to mutability of objects.final provides a version of const, equivalent to type* const pointers for objects and const for primitive types. Immutability of object members achieved via read-only interfaces and object encapsulation.
Supports the goto statement.Supports labels with loops and statement blocks. goto is a reserved keyword but is marked as "unused" in the
Source code can be written to be cross-platform and written to use platform-specific features. Typically compiled into native machine code, must be recompiled for each target platform.Compiled into Java bytecode for the JVM. Byte code is dependent on the Java platform, but is typically independent of operating system specific features.

Language features

Syntax

C++Java

class Foo ;

class Foo

Foo a;
// declares a to be a Foo object value,
// initialized using the default constructor.
// Another constructor can be used as
Foo a;
// or :
Foo a;

Foo a = new Foo;
// declares a to be a reference to a new Foo object
// initialized using the default constructor
// Another constructor can be used as
Foo a = new Foo;

Foo b = a;
// copies the contents of a to a new Foo object b;
// alternative syntax is "Foo b"

// Foo b = a;
// would declare b to be reference to the object pointed to by a
Foo b = a.clone;
// copies the contents of the object pointed to by a
// to a new Foo object;
// sets the reference b to point to this new object;
// the Foo class must implement the Cloneable interface
// for this code to compile
a.x = 5; // modifies the object aa.x = 5; // modifies the object referenced by a

std::cout << b.x << std::endl;
// outputs 0, because b is
// some object other than a

System.out.println;
// outputs 0, because b points to
// some object other than a

Foo *c;
// declares c to be a pointer to a
// Foo object

Foo c;
// declares c to be a reference to a Foo
// object

c = new Foo;
// c is set to the value of the address of the Foo object created by operator new

c = new Foo;
// binds c to reference a new Foo object

Foo &d = *c;
// binds d to reference the same object to which c points

Foo d = c;
// binds d to reference the same object as c

c->x = 5;
// modifies the object pointed to by c

c.x = 5;
// modifies the object referenced by c

d.bar; // invokes Foo::bar for a
c->bar; // invokes Foo::bar for *c

d.bar; // invokes Foo.bar for a
c.bar; // invokes Foo.bar for c

std::cout << d.x << std::endl;
// outputs 5, because d references the
// same object to which c points

System.out.println;
// outputs 5, because d references the
// same object as c

C++Java

const Foo *a; // it is not possible to modify the object
// pointed to by a through a
Foo * const a = new Foo;
// A declaration of a const pointer:
// it is possible to modify the object,
// but the pointer will constantly point
// to the object assigned to it here

final Foo a; // a declaration of a "final" reference:
// it is possible to modify the object,
// but the reference will constantly point
// to the first object assigned to it
a = new Foo;a = new Foo; // Only in constructor
a->x = 5;
// ILLEGAL
a.x = 5;
// LEGAL, the object's members can still be modified
// unless explicitly declared final in the declaring class
Foo *const b = new Foo;
// a declaration of a "const" pointer
final Foo b = new Foo;
// a declaration of a "final" reference
b = new Foo;
// ILLEGAL, it is not allowed to re-bind it
b = new Foo;
// ILLEGAL, it is not allowed to re-bind it
b->x = 5;
// LEGAL, the object can still be modified
b.x = 5;
// LEGAL, the object can still be modified

Both C++ and Java provide facilities for generic programming, templates and generics, respectively. Although they were created to solve similar kinds of problems, and have similar syntax, they are quite different.

Miscellaneous

An example comparing and exists in Wikibooks.

Performance

In addition to running a compiled Java program, computers running Java applications generally must also run the Java virtual machine, while compiled C++ programs can be run without external applications. Early versions of Java were significantly outperformed by statically compiled languages such as C++. This is because the program statements of these two closely related languages may compile to a few machine instructions with C++, while compiling into several byte codes involving several machine instructions each when interpreted by a JVM. For example:
Java/C++ statementC++ generated code Java generated byte code

Since performance optimizing is a very complex issue, it is very difficult to quantify the performance difference between C++ and Java in general terms, and most benchmarks are unreliable and biased. Given the very different natures of the languages, definitive qualitative differences are also difficult to draw. In a nutshell, there are inherent inefficiencies and hard limits on optimizing in Java, given that it heavily relies on flexible high-level abstractions, however, the use of a powerful JIT compiler can mitigate some issues. In any case, if the inefficiencies of Java are too great, compiled C or C++ code can be called from Java via the JNI.
Some inefficiencies that are inherent to the Java language include, mainly:
However, there are a number of benefits to Java's design, some realized, some only theorized:
Also, some performance problems occur in C++:

Language specification

The C++ language is defined by ISO/IEC 14882, an ISO standard, which is published by the ISO/IEC JTC1/SC22/WG21 committee. The latest, post-standardization draft of C++17 is available as well.
The C++ language evolves via an open steering committee called the C++ Standards Committee. The committee is composed of the creator of C++ Bjarne Stroustrup, the convener Herb Sutter, and other prominent figures, including many representatives of industries and user-groups. Being an open committee, anyone is free to join, participate, and contribute proposals for upcoming releases of the standard and technical specifications. The committee now aims to release a new standard every few years, although in the past strict review processes and discussions have meant longer delays between publication of new standards.
The Java language is defined by the Java Language Specification, a book which is published by Oracle.
The Java language continuously evolves via a process called the Java Community Process, and the world's programming community is represented by a group of people and organizations - the Java Community members—which is actively engaged into the enhancement of the language, by sending public requests - the Java Specification Requests - which must pass formal and public reviews before they get integrated into the language.
The lack of a firm standard for Java and the somewhat more volatile nature of its specifications have been a constant source of criticism by stake-holders wanting more stability and conservatism in the addition of new language and library features. In contrast, the C++ committee also receives constant criticism, for the opposite reason, i.e., being too strict and conservative, and taking too long to release new versions.

Trademarks

"C++" is not a trademark of any company or organization and is not owned by any individual.
"Java" is a trademark of Oracle Corporation.