Comparison of Java and C++: Difference between revisions

Content deleted Content added
 
(3 intermediate revisions by the same user not shown)
Line 27:
|-
| Compatible with [[C (programming language)|C]] source code, except for a few [[corner case]]s.
| Provides the [[Java Native Interface]] as well as [[Java Native Access]] and more recently [[Java Native AccessInterface#Foreign Function and Memory API|Foreign Function and Memory API]] 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.{{sfn|Bloch|2018|loc=Chapter §11 Item 66: Use native methods judiciously|p=285}} 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.{{sfn|Bloch|2018|loc=Chapter §11 Item 66: Use native methods judiciously|p=285}}
|-
| [[Write once, compile anywhere]] (WOCA).
Line 60:
|-
| [[Resource management (computing)|Resource management]] can be done manually or by automatic lifetime-based resource management ([[Resource Acquisition Is Initialization|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). Resources, such as memory, can be managed using [[Java Native Interface]] or the Java Foreign Function and Memory API (since Java 22), but requires calling external C/C++ code.
 
It can also be done using the internal API <code>sun.misc.Unsafe</code> 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 [[Dynamic memory allocation|heap]] or the [[Stack-based memory allocation|stack]].
| Classes are allocated on the [[Dynamic memory allocation|heap]]. [[Java version history#Java SE 6|Java SE 6]] optimizes with [[escape analysis]] to allocate some objects on the [[Stack-based memory allocation|stack]].
|-
| Allows explicitly overriding types, and some implicit narrowing conversions (for compatibility with C).
Line 75:
|-
| [[Operator overloading]] for most operators. Preserving meaning (semantics) is highly recommended.
| Operators are not overridable. The language overrides + and += for the <code>String</code> class.
|-
| Single and [[multiple inheritance]] of classes, including virtual inheritance.
Line 81:
|-
| Compile-time templates. Allows for [[Turing complete]] meta-programming.
| [[Generics in Java|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. Java type-casts all generics to their lowest bound (<code>Object</code> if no such bound exists, otherwise <code>? extends T</code> is casted to <code>T</code>).
|-
| 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 <code>SomeClass.class</code> and <code>someObject.getClass()</code>.
|-
| No standard inline documentation mechanism. Third-party software (e.g. [[Doxygen]]) exists. Standard library vendors may provide documentation comments, though it is not guaranteed.
| Extensive [[Javadoc]] documentation standard on all system classes and methods.
|-
Line 113:
| <syntaxhighlight lang="cpp">
class Foo { // Declares class Foo
private:
int x = 0; // Private Member variable. It will
// be initialized to 0, if the
Line 305 ⟶ 306:
* Java has both language and standard library support for [[Thread (computer science)|multi-threading]]. The <code>synchronized</code> [[Java keywords|keyword in Java]] provides [[mutual exclusion|mutex locks]] to support multi-threaded applications.{{sfn|Goetz|Peierls|Bloch|Bowbeer|2006|loc=§2.3.1 Intrinsic locks|pp=25-26}}{{sfn|Bloch|2018|loc=Chapter §11 Item 78: Synchronize access to shared mutable data|pp=126-129}} Java also provides libraries for more advanced multi-threading synchronizing. [[C++11]] has a defined memory model for multi-threading in C++, and library support for creating threads and for many synchronizing primitives. There are also many third-party libraries for this.
* C++ member functions can be declared as [[virtual function]]s, which means the method to be called is determined by the run-time type of the object (a.k.a. dynamic dispatching). By default, methods in C++ are not virtual (i.e., ''opt-in virtual''). In Java, methods are virtual by default, but can be made non-virtual by using the <code>[[final (Java)|final]]</code> keyword (i.e., ''opt-out virtual'').
* C and C++ enumerations are primitive types. andC enumerations (<code>enum</code>) support implicit conversion to integer types (but not from integer types), while C++ enumerations (<code>enum class</code>) do not. Java enumerations can be {{code|public static enum { enumName1, enumName2 }|java}} and are used like classes. Another way is to make another class that extends <code>java.lang.Enum<E></code>) and may therefore define constructors, fields, and methods as any other class. As of [[C++11]], C++ supports [[C++11#Strongly typed enumerations|strongly-typed enumerations]] which provide more type-safety and explicit specification of the storage type.
* Unary operators {{code|++}} and {{code|--}}: in C++ "The operand shall be a modifiable [[Value (computer science)|lvalue]]. [skipped] The result is the updated operand; it is an lvalue...",<ref>Standard for Programming Language C++ '11, 5.3.2 Increment and decrement [expr.pre.incr].</ref> but in Java "the binary numeric promotion mentioned above may include unboxing conversion and value set conversion. If necessary, value set conversion {and/or [...] boxing conversion} is applied to the sum prior to its being stored in the variable.",<ref>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/</ref> i.e. in Java, after the initialization {{code|1=Integer i=2; ++i;|2=java}} changes the reference {{code|i}} by assigning new object, while in C++ the object is still the same.