Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Comparison of Java and C++
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Semantics === * C++ allows default values for arguments of a function/method. Java does not. However, [[method overloading]] can be used to obtain similar results in Java but generate redundant stub code. * The minimum of code needed to compile for C++ is a function, for Java is a class. However, since Java 21 with the introduction of the unnamed class, it is possible to write a Java program consisting only of a main function. * C++ allows a range of implicit conversions between native types (including some narrowing conversions), and also allows defining implicit conversions involving user-defined types. In Java, only widening conversions between native types are implicit; other conversions require explicit cast syntax. ** A result of this is that although loop conditions (<code>if</code>, <code>while</code> and the exit condition in <code>for</code>) in Java and C++ both expect a boolean expression, code such as <code>if(a = 5)</code> 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 <code>if(a == 5)</code> 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. <code>a==5;</code>, 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.<ref>{{cite web|title=Reference Types and Values|url=http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.3|work=The Java Language Specification, Third Edition|access-date=9 December 2010}}</ref><ref>{{cite book |title= Core Java |volume= I |edition= Eighth |last1= Horstmann |first1= Cay |last2= Cornell |first2= Gary |publisher= Sun Microsystems |date= 2008 |isbn= 978-0-13-235476-9 |pages= 140–141 |quote=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''.}}</ref><ref>{{cite book |title= Java for Programmers |last1= Deitel |first1= Paul |last2= Deitel |first2= Harvey |publisher= Prentice Hall |date= 2009 |isbn= 978-0-13-700129-3 |page= 223 |quote= 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.}}</ref> * 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.<ref>{{cite web |url= https://gcc.gnu.org/wiki/FloatingPointMath |title= Semantics of Floating Point Math in GCC |publisher= GNU Foundation |access-date= 20 April 2013}}</ref><ref>{{cite web |url= http://msdn.microsoft.com/en-us/library/e7s85ffb.aspx |title= Microsoft c++ compiler, /fp (Specify Floating-Point Behavior) |publisher= Microsoft Corporation |access-date=19 March 2013}}</ref> 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++, [[pointer (computer programming)|pointers]] can be manipulated directly as memory address values. Java references are pointers to objects.<ref>{{cite web |url= http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.3.1 |title= Java Language Specification 4.3.1: Objects |publisher= Sun Microsystems |access-date=9 December 2010}}</ref> 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 <code>sun.misc.Unsafe</code> API, however it is deprecated and not recommended. * In C++, pointers can point to functions or member functions ([[function pointer]]s). The equivalent mechanism in Java uses object or interface references. * Via stack-allocated objects, C++ supports [[Resource Acquisition Is Initialization|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 <code>new</code> and left undeleted) it provides an effective means of resource management. Shared resources can be managed using <code>shared_ptr</code>, along with <code>weak_ptr</code> to break cyclic references. Java supports automatic memory management using [[Garbage collection (computer science)|garbage collection]]{{sfn|Bloch|2018|loc=Chapter §2 Item 8: Avoid finalizers and cleaners|pp=29-33}} which can free unreachable objects even in the presence of cyclic references, but other system resources (files,{{sfn|Bloch|2018|loc=Chapter §2 Item 7: Eliminate obsolete references|pp=123-125}} 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. * 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. * Java has [[Generic programming#Generics in Java|generics]], which main purpose is to provide type-safe containers. C++ has compile-time [[Generic programming#Templates in C++|templates]], which provide more extensive support for generic programming and metaprogramming. Java has [[Java annotation|annotations]], which allow adding arbitrary custom metadata to classes and metaprogramming via an [[Annotation processing tool#Java|annotation processing tool]]. * 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,{{sfn|Bloch|2018|loc=Foreword|pp=xi-xii}} but a class can implement multiple [[Interface (Java)|interfaces]]{{sfn|Bloch|2018|loc=Chapter §8 Item 8: Favor composition over inheritance|pp=87-92}} (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 [[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++ enumerations are primitive types and support implicit conversion to integer types (but not from integer types). 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.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)