Comparison of Java and C++ explained

Java and C++ are two prominent object-oriented programming languages. By many language popularity metrics, the two languages have dominated object-oriented and high-performance software development for much of the 21st century, and are often directly compared and contrasted. Java's syntax was based on C/C++.

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 (i.e., infrastructure 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 (Resource Acquisition Is Initialization (RAII)), generic programming, template metaprogramming, and the C++ Standard Library which includes generic containers and algorithms (the Standard Template Library or STL), 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 abstraction of the underlying platform. Java is a statically typed object-oriented language that uses a syntax similar to (but incompatible with) 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. However, native languages are not safe and applications using native methods are susceptible to memory corruption. If the code is not carefully written, native methods can lower the performance of the system because the garbage collector is incapable of monitoring or maintaining native memory usage, and there is a cost context-switching between native and non-native code.
Write once, compile anywhere (WOCA).Write once, run anywhere/everywhere (WORA/WORE).
Allows procedural programming, functional programming, object-oriented programming, generic programming, and template metaprogramming. Favors a mix of paradigms.Allows procedural programming, functional programming (since Java 8) and generic programming (since Java 5), 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(s).Runs on a virtual machine.
Provides object types and type names. Allows reflection via run-time type information (RTTI).Is reflective, allowing metaprogramming and dynamic code generation at runtime.
Has multiple binary compatibility standards (commonly Microsoft (for MSVC compiler) and Itanium/GNU (for almost all other compilers)).Has one binary compatibility standard, cross-platform for OS and compiler.
Optional automated bounds checking (e.g., the at method in vector and string containers).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.[1]
Standardized minimum limits for all numerical types, but the actual sizes are implementation-defined. Standardized types are available via the standard library <cstdint>.Standardized limits and sizes of all primitive types on all platforms.
Pointers, references, and pass-by-value are supported for all types (primitive or user-defined).All types (primitive types and reference types) are always passed by value.[2]
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.[3]
Resource management can be done manually or by automatic lifetime-based resource management (RAII).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 (version 7 onwards).

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 (passive data structure (PDS) types), 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 (for compatibility with C).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 (for static type introspection) 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 (ACE), Crypto++, various XMPP Instant Messaging (IM) libraries,[4] 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 (but not using the system GUI), 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 (e.g. LDAP), cryptography, security services (e.g. Kerberos), 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 (semantics) 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 (in C++11), and interfaces (using abstract classes).Functions references, function objects and lambdas were added in Java 8. Classes (and interfaces, which are classes) can be passed as references as well through SomeClass.class and someObject.getClass.
No standard inline documentation mechanism. Third-party software (e.g. Doxygen) 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 (see const-correctness).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 Java specification.
Source code can be written to be cross-platform (can be compiled for BSD, GNU/Linux, macOS, Solaris, Windows, etc., without modification) 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

See also: Java 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 asFoo a(args);// or (C++11):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 asFoo a = new Foo(args);

Foo b = a;// copies the contents of a to a new Foo object b;// alternative syntax is "Foo b(a)"// Foo b = a;// would declare b to be reference to the object pointed to by aFoo 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 aSystem.out.println(b.x);// outputs 0, because b points to// some object other than a
Foo *c;// declares c to be a pointer to a// Foo object (initially// undefined; could point anywhere)Foo c;// declares c to be a reference to a Foo// object (initially null if c is a class member;// it is necessary to initialize c before use// if it is a local variable)
c = new Foo;// c is set to the value of the address of the Foo object created by operator newc = new Foo;// binds c to reference a new Foo object
Foo &d = *c;// binds d to reference the same object to which c pointsFoo d = c;// binds d to reference the same object as c
c->x = 5;// modifies the object pointed to by cc.x = 5;// modifies the object referenced by c
d.bar(5); // invokes Foo::bar for ac->bar(5); // invokes Foo::bar for *cd.bar(5); // invokes Foo.bar for ac.bar(5); // invokes Foo.bar for c
std::cout << d.x << std::endl;// outputs 5, because d references the// same object to which c pointsSystem.out.println(d.x);// 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 afinal 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;// ILLEGALa.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// it is possible to modify the object,// but the pointer will constantly point// to the object assigned to it herefinal Foo b = new Foo;// a declaration of a "final" reference
b = new Foo;// ILLEGAL, it is not allowed to re-bind itb = new Foo;// ILLEGAL, it is not allowed to re-bind it
b->x = 5;// LEGAL, the object can still be modifiedb.x = 5;// LEGAL, the object can still be modified

Semantics

Resource management

The solution to this is to null out object references. A second common reason for memory leak is the use of cache that has become no longer relevant. The solution to memory leaks due to using old cache is to represent the cache using a WeakHashMap.

Libraries

Runtime

Templates vs. generics

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.

C++ TemplatesJava Generics
Classes, functions, aliases[17] and variables[18] can be templated.Classes and methods can be genericized.
Parameters can be variadic, of any type, integral value, character literal, or a class template.Parameters can be any reference type, including boxed primitive types (i.e. Integer, Boolean...).
Separate instantiations of the class or function will be generated for each parameter-set when compiled. For class templates, only the member functions that are used will be instantiated.One version of the class or function is compiled, works for all type parameters (via type-erasure).
Objects of a class template instantiated with different parameters will have different types at run time (i.e., distinct template instantiations are distinct classes).Type parameters are erased when compiled; objects of a class with different type parameters are the same type at run time. It causes a different constructor. Because of this type erasure, it is not possible to overload methods using different instantiations of the generic class.
Implementation of the class or function template must be visible within a translation unit in order to use it. This usually implies having the definitions in the header files or included in the header file. As of C++11, it is possible to use extern templates to separate compiling of some instantiations.Signature of the class or function from a compiled class file is sufficient to use it.
Templates can be specialized—a separate implementation could be provided for a particular template parameter.Generics cannot be specialized.
Template parameters can have default arguments. Pre-C++11, this was allowed only for template classes, not functions.Generic type parameters cannot have default arguments.
Wildcards unsupported. Instead, return types are often available as nested typedefs. (Also, C++11 added keyword auto, which acts as a wildcard for any type that can be determined at compile time.)Wildcards supported as type parameter.
Bounding of type parameters and enforcement of relationships between type parameters effectively possible through metaprogramming,[19] or since C++20, directly via std::derived_from and other conceptsSupports bounding of type parameters with "extends" and "super" for upper and lower bounds, respectively; allows enforcement of relationships between type parameters.
Allows instantiation of an object with the type of the parameter type.Precludes instantiation of an object with the type of the parameter type (except via reflection).
Type parameter of class template can be used for static methods and variables.Type parameter of generic class cannot be used for static methods and variables.
Static variables unshared between classes and functions of different type parameters.Static variables shared between instances of classes of different type parameters.
Class and function templates do not necessarily enforce type relations for type parameters in their declaration. Use of an incorrect type parameter results in compiling failure, often generating an error message within the template code rather than in the user's code that invokes it. Proper use of templated classes and functions is dependent on proper documentation. Metaprogramming provides these features at the cost of added effort. Since C++20, concepts can be used to provide these features.Generic classes and functions can enforce type relationships for type parameters in their declaration. Use of an incorrect type parameter results in a type error within the code that uses it. Operations on parametrized types in generic code are only allowed in ways that can be guaranteed to be safe by the declaration. This results in greater type safety at the cost of flexibility.
Templates are Turing-complete (see template metaprogramming).Generics are also Turing-complete[20]

Miscellaneous

An example comparing C++ and Java exists in Wikibooks.

Performance

In addition to running a compiled Java program, computers running Java applications generally must also run the Java virtual machine (JVM), 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:

Since performance optimization 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 (as in modern JVM implementations) 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++:

Official standard and reference of the language

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.[29]

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 (i.e., the stake-holders). 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 (1998, 2003, and 2011).

The Java language is defined by the Java Language Specification,[30] 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[31] —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.[32] "Java" is a trademark of Oracle Corporation.[33]

References

Sources

External links

Notes and References

  1. Web site: Unsigned Integer Arithmetic API now in JDK 8 . 17 March 2014 . 25 February 2017 . https://web.archive.org/web/20170225213350/https://blogs.oracle.com/darcy/entry/unsigned_api . dead .
  2. Web site: The Java Tutorials: Passing Information to a Method or a Constructor . Oracle . 17 February 2013.
  3. Web site: The Java Tutorials: Object as a Superclass . Oracle . 17 February 2013. .
  4. Web site: XMPP Software » Libraries. xmpp.org. 13 June 2013.
  5. Web site: Java vs. C++: A Critical Comparison. January 1997. Robert C. Martin. 15 December 2007. https://web.archive.org/web/20080511205821/http://www.objectmentor.com/resources/articles/javacpp.pdf. 11 May 2008. dead.
  6. Web site: Reference Types and Values. The Java Language Specification, Third Edition. 9 December 2010.
  7. Book: Core Java . I . Eighth . Horstmann . Cay . Cornell . Gary . Sun Microsystems . 2008 . 978-0-13-235476-9 . 140–141 . Some programmers (and unfortunately even some book authors) claim that the Java programming language uses call by reference for objects. However, that is false. Because this is such a common misunderstanding, it is worth examining a counterexample in some detail... This discussion demonstrates that the Java programming language does not use call by reference for objects. Instead object references are passed by value..
  8. Book: Java for Programmers . Deitel . Paul . Deitel . Harvey . Prentice Hall . 2009 . 978-0-13-700129-3 . 223 . Unlike some other languages, Java does not allow programmers to choose pass-by-value or pass-by-reference—all arguments are passed by value. A method call can pass two types of values to a method—copies of primitive values (e.g., values of type int and double) and copies of references to objects (including references to arrays). Objects themselves cannot be passed to methods..
  9. Web site: Semantics of Floating Point Math in GCC . GNU Foundation . 20 April 2013.
  10. Web site: Microsoft c++ compiler, /fp (Specify Floating-Point Behavior) . Microsoft Corporation . 19 March 2013.
  11. Web site: Java Language Specification 4.3.1: Objects . Sun Microsystems . 9 December 2010.
  12. Standard for Programming Language C++ '11, 5.3.2 Increment and decrement [expr.pre.incr].
  13. The Java™ Language Specification, Java SE 7 Edition, Chapters 15.14.2, 15.14.3, 15.15.1, 15.15.2, http://docs.oracle.com/javase/specs/
  14. Web site: Java memory leaks – Catch me if you can . Satish Chandra Gupta . Rajeev Palanki . IBM DeveloperWorks . 16 August 2005 . 2015-04-02. https://web.archive.org/web/20120722095536/http://www.ibm.com/developerworks/rational/library/05/0816_GuptaPalanki/ . 2012-07-22.
  15. https://web.archive.org/web/20140205030750/http://www.openlogic.com/wazi/bid/188158 How to Fix Memory Leaks in Java
  16. https://stackoverflow.com/questions/6470651/creating-a-memory-leak-with-java Creating a memory leak with Java
  17. Web site: cppreference.com. Type alias, alias template. 4 October 2022.
  18. Web site: Variable template . cppreference.com . 4 October 2022.
  19. http://www.boost.org/libs/type_traits/doc/html/boost_typetraits/reference.html Boost type traits library
  20. https://arxiv.org/abs/1605.05274 Java Generics Are Turing Complete
  21. Nathan . Clark . Amir Hormati . Sami Yehia . Scott Mahlke . Liquid SIMD: Abstracting SIMD hardware using lightweight dynamic mapping . Hpca'07 . 216–227 . 2007.
  22. Web site: Hundt . Robert . Loop Recognition in C++/Java/Go/Scala . Scala Days 2011 . 2011-04-27. Stanford, California . 2012-11-17 . https://ghostarchive.org/archive/20221009/https://days2011.scala-lang.org/sites/days2011/files/ws3-1-Hundt.pdf . 2022-10-09 . live . Java shows a large GC component, but a good code performance. [...] We find that in regards to performance, C++ wins out by a large margin. [...] The Java version was probably the simplest to implement, but the hardest to analyze for performance. Specifically the effects around garbage collection were complicated and very hard to tune; 318 kB.
  23. Web site: Quantifying the Performance of Garbage Collection vs. Explicit Memory Management . Matthew Hertz, Emery D. Berger . OOPSLA 2005 . 2005 . 2015-03-15 . In particular, when garbage collection has five times as much memory as required, its runtime performance matches or slightly exceeds that of explicit memory management. However, garbage collection's performance degrades substantially when it must use smaller heaps. With three times as much memory, it runs 17% slower on average, and with twice as much memory, it runs 70% slower. . https://web.archive.org/web/20170706100244/https://people.cs.umass.edu/~emery/pubs/gcvsmalloc.pdf . 6 July 2017 . dead .
  24. Book: Alexandrescu, Andrei . Modern C++ Design: Generic Programming and Design Patterns Applied. Chapter 4 . Addison-Wesley . 77–96 . 2001 . 978-0-201-70431-0.
  25. Web site: Boost Pool library . Boost . 19 April 2013.
  26. https://web.archive.org/web/20200929080449/https://www.slac.stanford.edu/comp/unix/.../icc/.../optaps_dsp_qax.htm Targeting IA-32 Architecture Processors for Run-time Performance Checking
  27. Web site: Fixing The Inlining "Problem" by Dr. Cliff Click Azul Systems: Blogs . 23 September 2011 . 7 September 2011 . https://web.archive.org/web/20110907092432/http://www.azulsystems.com/blog/cliff/2011-04-04-fixing-the-inlining-problem . dead .
  28. http://java.sun.com/performance/reference/whitepapers/6_performance.html#2.1.2 Oracle Technology Network for Java Developers
  29. Web site: Working Draft, Standard for Programming Language C++ . https://ghostarchive.org/archive/20221009/http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf . 2022-10-09 . live.
  30. http://java.sun.com/docs/books/jls/ The Java Language Specification
  31. http://www.jcp.org/en/participation/members The Java Community Process(SM) Program - Participation - JCP Members
  32. http://www.stroustrup.com/bs_faq.html#revenues Bjarne Stroustrup's FAQ: Do you own C++?
  33. http://blogs.zdnet.com/BTL/?p=16598 ZDNet: Oracle buys Sun; Now owns Java