GO-V.ORG
As seen in

Comparison of Java and C++

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++. Source: e01 Encyclopedia. Licence: CC BY-SA 4.0.

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++. A result of this is that although loop conditions ( if , while and the exit condition in for ) in Java and C++ both expect a Boolean expression, code such as if (a = 5) will cause a compile error in Java because there is no implicit narrowing conversion from int to Boolean, but will compile in C++. This is handy if the code was a typo and if (a == 5) was intended. However, current C++ compilers will usually generate a warning when such an assignment is performed within a conditional expression. Similarly, standalone comparison statements, e.g. a == 5; , without a side effect usually lead to a warning. For passing parameters to functions, C++ supports both pass-by-reference and pass-by-value. In Java, primitive parameters are always passed by value. Class types, interface types, and array types are collectively called reference types in Java and are also always passed by value. Java built-in types are of a specified size and range defined by the language specification. In C++, a minimal range of values is defined for built-in types, but the exact representation (number of bits) can be mapped to whatever native types are preferred on a given platform. For instance, Java characters are 16-bit Unicode characters, and strings are composed of a sequence of such characters. C++ offers both narrow and wide characters, but the actual size of each is platform dependent, as is the character set used. Strings can be formed from either type. This also implies that C++ compilers can automatically select the most efficient representation for the target platform (i.e., 64-bit integers for a 64-bit platform), while the representation is fixed in Java, meaning the values can either be stored in the less-efficient size, or must pad the remaining bits and add code to emulate the reduced-width behavior. The rounding and precision of floating point values and operations in C++ is implementation-defined (although only very exotic or old platforms depart from the IEEE 754 standard). Java provides an optional strict floating-point model ( strictfp ) that guarantees more consistent results across platforms, though at the cost of possibly slower run-time performance. However, Java does not comply strictly with the IEEE 754 standard. Most C++ compilers will, by default, comply partly with IEEE 754 (usually excluding strict rounding rules and raise exceptions on NaN results), but provide compliance options of varied strictness, to allow for some optimizing. If we label those options from least compliant to most compliant as fast, consistent (Java's strictfp), near-IEEE, and strict-IEEE, we can say that most C++ implementations default to near-IEEE, with options to switch to fast or strict-IEEE, while Java defaults to fast with an option to switch to consistent. In C++, pointers can be manipulated directly as memory address values. Java references are pointers to objects. Java references do not allow direct access to memory addresses or allow memory addresses to be manipulated with pointer arithmetic. In C++ one can construct pointers to pointers, pointers to ints and doubles, and pointers to arbitrary memory locations. Java references only access objects, never primitives, other references, or arbitrary memory locations. In Java, memory can be read and written by arbitrary values using the sun.misc.Unsafe API, however it is deprecated and not recommended. In C++, pointers can point to functions or member functions (function pointers). The equivalent mechanism in Java uses object or interface references. Via stack-allocated objects, C++ supports scoped resource management, a technique used to automatically manage memory and other system resources that supports deterministic object destruction. While scoped resource management in C++ cannot be guaranteed (even objects with proper destructors can be allocated using new and left undeleted) it provides an effective means of resource management. Shared resources can be managed using std::shared_ptr , along with std::weak_ptr to break cyclic references. Java supports automatic memory management using garbage collection which can free unreachable objects even in the presence of cyclic references, but other system resources (files, streams, windows, communication ports, threads, etc.) must be explicitly released because garbage collection is not guaranteed to occur immediately after the last object reference is abandoned. Java allows scope resource management through try -with-resources blocks for types that implement java.lang.AutoCloseable , but unlike C++, the object is not disposed from memory, but only owned resources are disposed by the close() method. C++ features user-defined operator overloading. Operator overloading allows for user-defined types to support operators (arithmetic, comparisons, etc.) like primitive types via user-defined implementations for these operators. It is generally recommended to preserve the semantics of the operators. Java supports no form of operator overloading (although its library uses the addition operator for string concatenation). Java features standard application programming interface (API) support for reflective programming (reflection) and dynamic loading of arbitrary new code. C++ supports static and dynamic linking of binaries. Both Java and C++ (since C++26) offer reflection, allowing for a degree of code introspection. Reflection in Java acts primarily at runtime and is primarily behavioral, while reflection in C++ acts at compile-time and produces meta-objects, and is primarily generative. Java has generics, which main purpose is to provide type-safe containers. However, Java generics are not reified (act only at compile-time), and are type-erased at runtime. C++ has compile-time templates, which provide more extensive support for generic programming and metaprogramming. C++ templates instantiate a specialization for each type used with them. Both Java and C++ offer annotations. Java annotations allow adding arbitrary custom metadata to classes and metaprogramming via an annotation processing tool. C++ offers attributes to indicate compiler-defined metadata, as well as annotations (since C++26) which can user-defined and read at compile time, but not at runtime like in Java. Both Java and C++ distinguish between native types (also termed fundamental or built-in types) and user-defined types (also termed compound types). In Java, native types have value semantics only, and compound types have reference semantics only. In C++ all types have value semantics, but a reference can be created to any type, which will allow the object to be manipulated via reference semantics. C++ supports multiple inheritance of arbitrary classes. In Java a class can derive from only one class, but a class can implement multiple interfaces (in other words, it supports multiple inheritance of types, but only single inheritance of implementation). Java explicitly distinguishes between interfaces and classes. In C++, multiple inheritance and pure virtual functions make it possible to define classes that function almost like Java interfaces do, with a few small differences. Java has both language and standard library support for multi-threading. The synchronized keyword in Java provides mutex locks to support multi-threaded applications. 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. C++ member functions can be declared as virtual functions, 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 final keyword (i.e., opt-out virtual). C++ features a language-level override keyword to indicate overriding a virtual method. Java does not, but features a @Override annotation to indicate overriding, which issues a compiler error if no existing method is being overriden. C and C++ enumerations are primitive types. C enumerations ( enum ) implicitly convert to integer types (but not from integer types), while C++ enumerations ( enum class ) are strongly typed and do not implicitly convert. Java enumerations behave like classes and may define constructors and methods. Unary operators and : in C++ "The operand shall be a modifiable lvalue. [skipped] The result is the updated operand; it is an lvalue...", 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.", i.e. in Java, after the initialization changes the reference by assigning new object, while in C++ the object is still the same. In Java, lambdas are "poly expressions", whose types dependent on context , while in C++, lambdas have a real runtime class which can be accessed with decltype and are part of the language model. Java lambdas depend on the functional interface which they are assigned to. === Asynchronous/concurrent programming=== Java lacks an asynchronous runtime entirely. Java traditionally relies on thread pools managed by a java.util.concurrent.ExecutorService , which runs on an operating system multi-threading. For non-blocking I/O, Java offers java.nio . Java 21 with Project Panama introduces virtual threads (similar to Go's "goroutines" which are analogous to green threads), allowing writing traditional blocking code inside a virtual thread with automatic unmounting and remounting. C++20 introduces true coroutines, C++23 introduces generators in the standard library, and C++26 introduces an asynchronous task type in the standard library. C++20 introduces three new keywords (but no async keyword): co_await : suspends execution until resumed, analogous to await in other languages co_yield : suspends execution, returning a value, analogous to yield in other languages' generators co_return : completes execution, returning a value C++26 introduces the std::execution library, which is a lazy, composable, zero-overhead framework, while Java's java.util.concurrent.ExecutorService is an eager runtime. Java yields the execution control to the internal task queue, while C++ only starts execution when a receiver connects to a sender and calls start() . C++'s std::execution::scheduler is an execution engine, analogous to Java's java.util.concurrent.ExecutorService . C++'s std::execution::sender is an async pipeline, analogous to Java's java.util.concurrent.CompletableFuture . C++'s std::execution::receiver is a callback/sink, analogous to Java's internal completion handlers/lambdas. Java lacks a true equivalent to C++'s std::execution::task , which represents a unit of asynchronous work, and is a sender that is often used as a coroutine's return type to be co_await ed. Older C++ used std::async() (introduced in C++11), which receives a unit of work (a lambda) and returns a std::future as a receipt, similar to Java's ExecutorService.submit() which returned a java.util.concurrent.Future . Java's division and modulus operators are well defined to truncate to zero. Prior to C++11, C++ did not specify whether or not these operators truncate to zero or "truncate to negative infinity". -3/2 will always be -1 in Java and C++11, but a C++03 compiler may return either -1 or -2 , depending on the platform. C99 defines division in the same fashion as Java and C++11. Both languages guarantee (where a and b are integer types) that (a / b) * b + (a % b) == a for all a and b ( b non-zero). The C++03 version will sometimes be faster, as it is allowed to pick whichever truncation mode is native to the processor. The sizes of integer types are fixed in Java (for example int is 32-bit, long is 64-bit), while in C++ the size of integers and pointers is compiler and application binary interface (ABI) dependent within given constraints. Thus a Java program will have consistent behavior across platforms, whereas a C++ program may require adapting for some platforms, but may run faster with more natural integer sizes for the local platform. However, C/C++ also have fixed width sizes (such as int32_t for signed 32-bit integers, uint64_t for unsigned 64-bit integers, etc.) An example comparing C++ and Java exists in Wikibooks. Hyperpoly - Java and C++ Comparison

source: e01 Encyclopedia · licence: CC BY-SA 4.0 · page · source revision

Cite this

"Comparison of Java and C++". 1791229243. e01 Encyclopedia. CC BY-SA 4.0. https://en.wikipedia.org/w/index.php?oldid=1378721567

JSON record · API collection · BibTeX · RIS · CSL-JSON · citation policy

Save to pass ·