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!
=== Syntax === {{see also|Java syntax|C++ syntax}} * [[Java syntax]] has a [[context-free grammar]] that can be parsed by a simple [[LALR parser]]. Parsing C++ is more complicated. For example, {{nowrap|<code>Foo<1>(3);</code>}} is a sequence of comparisons if Foo is a variable, but creates an object if Foo is the name of a class template. * C++ allows namespace-level constants, variables, and functions. In Java, such entities must belong to some given type, and therefore must be defined inside a type definition, either a class or an [[interface (Java)|interface]]. * In C++, objects are values, while in Java they are not. C++ uses ''value semantics'' by default, while Java always uses ''reference semantics''. To opt for reference semantics in C++, either a pointer or a reference can be used. {| class="wikitable" ! style="width:600px;"| C++ ! style="width:600px;"| Java |- | <syntaxhighlight lang="cpp"> class Foo { // Declares class Foo int x = 0; // Private Member variable. It will // be initialized to 0, if the // constructor would not set it. // (from C++11) public: Foo(): x{0} // Constructor for Foo; initializes {} // x to 0. If the initializer were // omitted, the variable would // be initialized to the value that // has been given at declaration of x. int bar(int i) { // Member function bar() return 3 * i + x; } };</syntaxhighlight> | <syntaxhighlight lang="java"> class Foo { // Defines class Foo private int x; // Member variable, normally declared // as private to enforce encapsulation // initialized to 0 by default public Foo() { // Constructor for Foo } // no-arg constructor supplied by default public int bar(int i) { // Member method bar() return 3 * i + x; } }</syntaxhighlight> |- | <syntaxhighlight lang="cpp"> Foo a; // declares a to be a Foo object value, // initialized using the default constructor. // Another constructor can be used as Foo a(args); // or (C++11): Foo a{args}; </syntaxhighlight> | <syntaxhighlight lang="java"> 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(args); </syntaxhighlight> |- | <syntaxhighlight lang="cpp"> Foo b = a; // copies the contents of a to a new Foo object b; // alternative syntax is "Foo b(a)"</syntaxhighlight> | <syntaxhighlight lang="java"> // 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 </syntaxhighlight> |- | <syntaxhighlight lang="cpp">a.x = 5; // modifies the object a</syntaxhighlight> | <syntaxhighlight lang="java">a.x = 5; // modifies the object referenced by a</syntaxhighlight> |- | <syntaxhighlight lang="cpp"> std::println("{}", b.x); // outputs 0, because b is // some object other than a </syntaxhighlight> | <syntaxhighlight lang="java"> System.out.println(b.x); // outputs 0, because b points to // some object other than a</syntaxhighlight> |- | <syntaxhighlight lang="cpp"> Foo* c; // declares c to be a pointer to a // Foo object (initially // undefined; could point anywhere)</syntaxhighlight> | <syntaxhighlight lang="java"> 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)</syntaxhighlight> |- | <syntaxhighlight lang="cpp"> c = new Foo; // c is set to the value of the address of the Foo object created by operator new</syntaxhighlight> | <syntaxhighlight lang="java"> c = new Foo(); // binds c to reference a new Foo object</syntaxhighlight> |- | <syntaxhighlight lang="cpp"> Foo& d = *c; // binds d to reference the same object to which c points</syntaxhighlight> | <syntaxhighlight lang="java"> Foo d = c; // binds d to reference the same object as c</syntaxhighlight> |- | <syntaxhighlight lang="cpp"> c->x = 5; // modifies the object pointed to by c</syntaxhighlight> | <syntaxhighlight lang="java"> c.x = 5; // modifies the object referenced by c</syntaxhighlight> |- | <syntaxhighlight lang="cpp"> d.bar(5); // invokes Foo::bar() for a c->bar(5); // invokes Foo::bar() for *c </syntaxhighlight> | <syntaxhighlight lang="java"> d.bar(5); // invokes Foo.bar() for a c.bar(5); // invokes Foo.bar() for c </syntaxhighlight> |- | <syntaxhighlight lang="cpp"> std::println("{}", d.x); // outputs 5, because d references the // same object to which c points </syntaxhighlight> | <syntaxhighlight lang="java"> System.out.println(d.x); // outputs 5, because d references the // same object as c</syntaxhighlight> |- | It is possible to declare a pointer or reference to a [[const]] object in order to prevent client code from modifying it. Functions and methods can also guarantee that they will not modify the object pointed to by a pointer by using the "const" keyword. This enforces [[const-correctness]]. <syntaxhighlight lang="cpp"> const Foo* a; // it is not possible to modify the object // pointed to by a through a </syntaxhighlight> | The <code>final</code> keyword is similar to the <code>const</code> keyword in C++, but its usage is more limited.{{sfn|Goetz|Peierls|Bloch|Bowbeer|2006|loc=Β§3.4.1 Final fields|p=48}} For the most part, const-correctness must rely on the semantics of the class' interface, i.e., it is not strongly enforced, except for public data members that are labeled <code>final</code>. <syntaxhighlight lang="java"> 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</syntaxhighlight> |- | <syntaxhighlight lang="cpp">a = new Foo();</syntaxhighlight> | <syntaxhighlight lang="java">a = new Foo(); // Only in constructor</syntaxhighlight> |- | <syntaxhighlight lang="cpp">a->x = 5; // ILLEGAL</syntaxhighlight> | <syntaxhighlight lang="java">a.x = 5; // LEGAL, the object's members can still be modified // unless explicitly declared final in the declaring class</syntaxhighlight> |- | <syntaxhighlight lang="cpp">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 here</syntaxhighlight> | <syntaxhighlight lang="java">final Foo b = new Foo(); // a declaration of a "final" reference</syntaxhighlight> |- | <syntaxhighlight lang="cpp">b = new Foo(); // ILLEGAL, it is not allowed to re-bind it</syntaxhighlight> | <syntaxhighlight lang="java">b = new Foo(); // ILLEGAL, it is not allowed to re-bind it</syntaxhighlight> |- | <syntaxhighlight lang="cpp">b->x = 5; // LEGAL, the object can still be modified</syntaxhighlight> | <syntaxhighlight lang="java">b.x = 5; // LEGAL, the object can still be modified</syntaxhighlight> |} * C++ supports <code>[[goto]]</code> statements, which may lead to [[spaghetti code]] programming. With the exception of the goto statement (which is very rarely seen in real code and highly discouraged), both Java and C++ have basically the same [[control flow]] structures, designed to enforce structured control flow, and relies on [[Control flow#Early exit from loops|break and continue]] statements to provide some <code>goto</code>-like functions. Some commenters point out that these labelled flow control statements break the single point-of-exit property of structured programming.<ref name="Martin">{{cite web|url=http://www.objectmentor.com/resources/articles/javacpp.pdf|title=Java vs. C++: A Critical Comparison|date=January 1997|author=Robert C. Martin|access-date=15 December 2007|archive-url=https://web.archive.org/web/20080511205821/http://www.objectmentor.com/resources/articles/javacpp.pdf|archive-date=11 May 2008|url-status=dead}}</ref> * C++ provides low-level features which Java mostly lacks (one notable exception being the <code>sun.misc.Unsafe</code> API for direct memory access and manipulation). In C++, pointers can be used to manipulate specific memory locations, a task necessary for writing low-level [[operating system]] components. Similarly, many C++ compilers support an [[inline assembler]]. Assembly language code can be imported to a C/C++ program and vice versa. This makes C/C++ language even faster. In Java, such code must reside in external libraries, and can only be accessed via the [[Java Native Interface]], with a significant overhead for each call.
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)