50
Comparison of Java and C++ From Wikipedia, the free encyclopedia Jump to: navigation , search Some of this article's listed sources may not be reliable . (September 2010) This article may be unbalanced towards certain viewpoints. (May 2016)This article may contain improper references to selfpublished sources . (September 2010) This article possibly contains original research . (August 2012) This article may require cleanup to meet Wikipedia's quality standards . (February 2011) Design aims[edit ] 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 (a.k.a., infrastructure programming), extending the procedural programming language C , which was designed for efficient execution. To C, C++ added support for static typing , objectoriented programming , exception handling , lifetimebased resource management (RAII ), generic programming , template metaprogramming , and the C++ Standard Library which includes generic containers and algorithms (STL), and many other general purpose facilities. Java Is a generalpurpose, concurrent, classbased, objectoriented 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 a full abstraction of the underlying platform. Java is a statically typed objectoriented language that uses a syntax similar to C++, but incompatible. It includes a documentation system called Javadoc . The different goals in the development of C++ and Java resulted in different principles and design tradeoffs between the languages. The differences are as follows: C++ Java Extends C with objectoriented 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. Write once, compile anywhere (WOCA). Write once, run anywhere /everywhere (WORA/WORE). Allows procedural programming , functional Allows procedural programming , functional programming

Comparison of Java and C++ - Ashish Prajapati · PDF fileComparison of Java and C++ From Wikipedia, the free encyclopedia Jump to: navigation, search Some of this article's listed

Embed Size (px)

Citation preview

Comparison of Java and C++

From Wikipedia, the free encyclopediaJump to: navigation, search

Some of this article's listed sources may not be reliable. (September 2010) This article may be unbalancedtowards certain viewpoints. (May 2016)This article may contain improper references to self­publishedsources. (September 2010) This article possibly contains original research. (August 2012) This article mayrequire cleanup to meet Wikipedia's quality standards. (February 2011)

Design aims[edit]

The differences between the programming languages C++ and Java can be traced to their heritage, as theyhave different design goals.

C++Was designed for systems and applications programming (a.k.a., infrastructure programming), extendingthe procedural programming language C, which was designed for efficient execution. To C, C++ addedsupport for static typing, object­oriented programming, exception handling, lifetime­based resourcemanagement (RAII), generic programming, template metaprogramming, and the C++ Standard Librarywhich includes generic containers and algorithms (STL), and many other general purpose facilities.

JavaIs a general­purpose, concurrent, class­based, object­oriented programming language that is designed tominimize 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 a full abstraction of the underlying platform. Javais a statically typed object­oriented language that uses a syntax similar to C++, but incompatible. It includesa documentation system called Javadoc.

The different goals in the development of C++ and Java resulted in different principles and design tradeoffsbetween the languages. The differences are as follows:

C++ Java

Extends C with object­orientedprogramming and generic programming. Ccode can most properly be used.

Strongly influenced by C++/C syntax.

Compatible with C source code, except fora few corner cases.

Provides the Java Native Interface and recently Java NativeAccess as a way to directly call C/C++ code.

Write once, compile anywhere (WOCA). Write once, run anywhere/everywhere (WORA/WORE).

Allows procedural programming, functionalAllows procedural programming, functional programming

programming, object­orientedprogramming, generic programming, andtemplate metaprogramming. Favors a mixof paradigms.

(since Java 8) and generic programming (since Java 5), butstrongly encourages the object­oriented programmingparadigm. Includes support for creating scripting languages.

Runs as native executable machine codefor the target instruction set(s).

Runs on a virtual machine.

Provides object types and type names.Allows reflection via run­time typeinformation (RTTI).

Is reflective, allowing metaprogramming and dynamic codegeneration at runtime.

Has multiple binary compatibility standards(commonly Microsoft (for MSVC compiler)and Itanium/GNU (for almost all othercompilers)).

Has one binary compatibility standard, cross­platform for OSand compiler.

Optional automated bounds checking (e.g.,the at() method in vector and stringcontainers).

All operations are required to be bound­checked by allcompliant distributions of Java. HotSpot can remove boundschecking.

Native unsigned arithmetic support.Native unsigned arithmetic unsupported. Java 8 changessome of this, but aspects are unclear.

Standardized minimum limits for allnumerical types, but the actual sizes areimplementation­defined. Standardizedtypes are available via the standard library<cstdint>.

Standardized limits and sizes of all primitive types on allplatforms.

Pointers, references, and pass­by­valueare supported for all types (primitive oruser­defined).

All types (primitive types and reference types) are alwayspassed by value.

Memory management can be donemanually via new / delete, automaticallyby scope, or by smart pointers. Supportsdeterministic destruction of objects.Garbage collection ABI standardized inC++11, though compilers are not requiredto implement garbage collection.

Automatic garbage collection. Supports a non­deterministicfinalize() method which use is not recommended.

Resource management can be donemanually or by automatic lifetime­basedresource management (RAII).

Resource management must be done manually, orautomatically via finalizers, though this is generallydiscouraged. Has try­with­resources for automatic scope­based resource management (version 7 onwards).

Supports classes, structs (passive datastructure (PDS) types), and unions, and Classes are allocated on the heap. Java SE 6 optimizes with

[1]

[2]

[3]

can allocate them on the heap or thestack.

escape analysis to allocate some objects on the stack.

Allows explicitly overriding types, and someimplicit narrowing conversions (forcompatibility with C).

Rigid type safety except for widening conversions.

The C++ Standard Library was designed tohave a limited scope and functions, butincludes language support, diagnostics,general utilities, strings, locales,containers, algorithms, iterators, numerics,input/output, random number generators,regular expression parsing, threadingfacilities, type traits (for static typeintrospection) and Standard C Library. TheBoost library offers more functionsincluding network I/O.A rich amount of third­party libraries existfor GUI and other functions like: AdaptiveCommunication Environment (ACE),Crypto++, various XMPP InstantMessaging (IM) libraries, OpenLDAP, Qt,gtkmm.

The standard library has grown with each release. Byversion 1.6, the library included support for locales, logging,containers and iterators, algorithms, GUI programming (butnot using the system GUI), graphics, multi­threading,networking, platform security, introspection, dynamic classloading, blocking and non­blocking I/O. It provided interfacesor support classes for XML, XSLT, MIDI, databaseconnectivity, naming services (e.g. LDAP), cryptography,security services (e.g. Kerberos), print services, and webservices. SWT offers an abstraction for platform­specificGUIs.

Operator overloading for most operators.Preserving meaning (semantics) is highlyrecommended.

Operators are not overridable. The language overrides +and += for the String class.

Single and Multiple inheritance of classes,including virtual inheritance.

Single inheritance of classes. Supports multiple inheritancevia the Interfaces construct, which is equivalent to a C++class composed of abstract methods.

Compile­time templates. Allows for Turingcomplete meta­programming.

Generics are used to achieve basic type­parametrization,but they do not translate from source code to byte code dueto the use of type erasure by the compiler.

Function pointers, function objects,lambdas (in C++11), and interfaces.

References to functions achieved via the reflection API. OOPidioms using Interfaces, such as Adapter, Observer, andListener are generally preferred over direct references tomethods.

No standard inline documentationmechanism. Third­party software (e.g.Doxygen) exists.

Extensive Javadoc documentation standard on all systemclasses and methods.

const keyword for defining immutable

[4]

variables and member functions that donot change the object. Const­ness ispropagated as a means to enforce, atcompile­time, correctness of the code withrespect 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­onlyinterfaces and object encapsulation.

Supports the goto statement. Supports labels with loops and statement blocks.

Source code can be written to be cross­platform (can be compiled for Windows,BSD, Linux, OS X, Solaris, etc., withoutmodification) and written to use platform­specific features. Typically compiled intonative machine code, must be recompiledfor each target platform.

Compiled into byte code for the JVM. Byte code isdependent on the Java platform, but is typically independentof operating system specific features.

Java syntax has a context­free grammar that can be parsed by a simple LALR parser. Parsing C++ ismore complicated. For example, Foo<1>(3); is a sequence of comparisons if Foo is a variable, butcreates 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 tosome given type, and therefore must be defined inside a type definition, either a class or an interface.In C++, objects are values, while in Java they are not. C++ uses value semantics by default, while Javaalways uses reference semantics. To opt for reference semantics in C++, either a pointer or a referencecan be used.

C++ Java

class Foo // Declares class Foo int x; // Private Member variable public: Foo() : x(0) // Constructor for Foo; initializes // x to 0. If the initializer were // omitted, the variable would not // be initialized to a specific // value.

int bar(int i) // Member function bar() return 3*i + x;

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;

;

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 aargs;

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);

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 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

a.x = 5; // modifies the object a a.x = 5; // modifies the object referenced by a

std::cout << b.x << std::endl; // outputs 0, because b is // some object other than a

System.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; // binds c to reference a new Foo object

c = new Foo(); // binds c to reference a new Foo object

Foo &d = c; // binds d to reference the same object as c

Foo d = c; // binds d to reference the same object as c

c‐>x = 5; // modifies the object referenced by c

c.x = 5; // modifies the object referenced by c

a.bar(5); // invokes Foo::bar() for a c‐>bar(5); // invokes Foo::bar() for *c

a.bar(5); // invokes Foo.bar() for a c.bar(5); // invokes Foo.bar() for c

std::cout << d‐>x << std::endl; // outputs 5, because d references the // same object as c

System.out.println(d.x); // outputs 5, because d references the // same object as c

In C++, it is possible to declare a pointer or reference to a const object in order to prevent client codefrom modifying it. Functions and methods can also guarantee that they will not modify the object pointedto by a pointer by using the "const" keyword. This enforces const­correctness.In Java, for the most part, const­correctness must rely on the semantics of the class' interface, i.e., it isn'tstrongly enforced, except for public data members that are labeled final.

C++ Java

const Foo *a; // it is not possible to modify the object // pointed to by a through a

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

a = new Foo(); a = new Foo(); // Only in constructor

a‐>x = 5; // ILLEGAL

a.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

final Foo b = new Foo(); // a declaration of a "final" reference

b = new Foo(); //ILLEGAL, it is not allowed to re‐bind it

b = new Foo(); // ILLEGAL, it is not allowed to re‐bind it

b‐>x = 5; // LEGAL, the object can still be modified

b.x = 5; // LEGAL, the object can still be modified

C++ supports goto statements, which may lead to spaghetti code programming. With the exception ofthe 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 onbreak and continue statements to provide some goto­like functions. Some commenters point out thatthese labelled flow control statements break the single point­of­exit property of structured programming.

C++ provides low­level features which Java lacks. In C++, pointers can be used to manipulate specificmemory locations, a task necessary for writing low­level operating system components. Similarly, manyC++ compilers support an inline assembler. In Java, such code must reside in external libraries, and canonly be accessed via the Java Native Interface, with a significant overhead for each call.

Semantics[edit]

C++ allows default values for arguments of a function/method. Java does not. However, methodoverloading 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.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 wideningconversions between native types are implicit; other conversions require explicit cast syntax.

A result of this is that although loop conditions (if, while and the exit condition in for) in Java andC++ both expect a boolean expression, code such as if(a = 5) will cause a compile error in Javabecause there is no implicit narrowing conversion from int to boolean. This is handy if the code was atypo for if(a == 5). Yet current C++ compilers usually generate a warning when such an assignment

[5]

is performed within a conditional expression. Similarly, standalone comparison statements, e.g. a==5;,without a side effect generate 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 arecollectively 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++, aminimal range of values is defined for built­in types, but the exact representation (number of bits) can bemapped 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 sequenceof such characters. C++ offers both narrow and wide characters, but the actual size of each is platformdependent, 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 thetarget 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 andadd 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 optionalstrict floating­point model (strictfp) that guarantees more consistent results across platforms, though atthe cost of possibly slower run­time performance. However, Java does not comply strictly with the IEEE754 standard. Most C++ compilers will, by default, comply partly with IEEE 754 (usually excluding strictrounding 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 defaultto near­IEEE, with options to switch to fast or strict­IEEE, while Java defaults to fast with an option toswitch to consistent.In C++, pointers can be manipulated directly as memory address values. Java references are pointers toobjects. Java references do not allow direct access to memory addresses or allow memory addressesto be manipulated with pointer arithmetic. In C++ one can construct pointers to pointers, pointers to intsand doubles, and pointers to arbitrary memory locations. Java references only access objects, neverprimitives, other references, or arbitrary memory locations.In C++, pointers can point to functions or member functions (function pointers). The equivalentmechanism in Java uses object or interface references.Via stack­allocated objects, C++ supports scoped resource management, a technique used toautomatically manage memory and other system resources that supports deterministic object destruction.While scoped resource management in C++ cannot be guaranteed (even objects with proper destructorscan be allocated using new and left undeleted) it provides an effective means of resource management.Shared resources can be managed using shared_ptr, along with weak_ptr to break cyclic references.Java supports automatic memory management using garbage collection which can free unreachableobjects 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 notguaranteed to occur immediately after the last object reference is abandoned.C++ features user­defined operator overloading. Operator overloading allows for user­defined types tosupport operators (arithmetic, comparisons, etc.) like primitive types via user­defined implementations forthese operators. It is generally recommended to preserve the semantics of the operators. Java supports

[6][7][8]

[9][10]

[11]

no form of operator overloading (although its library uses the addition operator for string concatenation).Java features standard application programming interface (API) support for reflection and dynamicloading of arbitrary new code.C++ supports static and dynamic linking of binaries.Java has generics, which main purpose is to provide type­safe containers. C++ has compile­timetemplates, which provide more extensive support for generic programming and metaprogramming. Javahas annotations, which allow adding arbitrary custom metadata to classes and metaprogramming via anannotation processing tool.Both Java and C++ distinguish between native types (also termed fundamental or built­in types) anduser­defined types (also termed compound types). In Java, native types have value semantics only, andcompound types have reference semantics only. In C++ all types have value semantics, but a referencecan 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, buta class can implement multiple interfaces (in other words, it supports multiple inheritance of types, butonly single inheritance of implementation).Java explicitly distinguishes between interfaces and classes. In C++, multiple inheritance and pure virtualfunctions make it possible to define classes that function almost like Java interfaces do, with a few smalldifferences.Java has both language and standard library support for multi­threading. The synchronized keyword inJava provides simple and secure mutex locks to support multi­threaded applications. Java also providesrobust and complex libraries for more advanced multi­threading synchronizing. Only as of C++11 is therea defined memory model for multi­threading in C++, and library support for creating threads and for manysynchronizing primitives. There are also many third­party libraries for this.C++ member functions can be declared as virtual functions, which means the method to be called isdetermined 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 byusing the final keyword (i.e., opt­out virtual).C++ enumerations are primitive types and support implicit conversion to integer types (but not frominteger types). Java enumerations can be public static enumenumName1,enumName2 and are usedlike classes. Another way is to make another class that extends java.lang.Enum<E>) and may thereforedefine constructors, fields, and methods as any other class. As of C++11, C++ also supports strongly­typed enumerations which provide more type­safety and explicit specification of the storage type.Unary operators '++' and '­­': in C++ "The operand shall be a modifiable lvalue. [skipped] The result is theupdated operand; it is an lvalue...", but in Java "the binary numeric promotion mentioned above mayinclude 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 theinitialization "Integer i=2;", "++i;" changes the reference i by assigning new object, while in C++ the objectis still the same.

Resource management[edit]

Java offers automatic garbage collection, which may be bypassed in specific circumstances via the Realtime Java specification. Memory management in C++ is usually done via constructors, destructors, andsmart pointers. The C++ standard permits garbage collection, but does not require it. Garbage collectionis rarely used in practice.C++ can allocate arbitrary blocks of memory. Java only allocates memory via object instantiation. Arbitrary

[12]

[13]

memory blocks may be allocated in Java as an array of bytes.Java and C++ use different idioms for resource management. Java relies mainly on garbage collection,which can reclaim memory, while C++ relies mainly on the Resource Acquisition Is Initialization (RAII)idiom. This is reflected in several differences between the two languages:

In C++ it is common to allocate objects of compound types as local stack­bound variables which aredestroyed when they go out of scope. In Java compound types are always allocated on the heap andcollected by the garbage collector (except in virtual machines that use escape analysis to convert heapallocations to stack allocations).C++ has destructors, while Java has finalizers. Both are invoked before an object's deallocation, butthey differ significantly. A C++ object's destructor must be invoked implicitly (in the case of stack­boundvariables) or explicitly to deallocate an object. The destructor executes synchronously just before thepoint in a program at which an object is deallocated. Synchronous, coordinated uninitializing anddeallocating in C++ thus satisfy the RAII idiom. In Java, object deallocation is implicitly handled by thegarbage collector. A Java object's finalizer is invoked asynchronously some time after it has beenaccessed for the last time and before it is deallocated. Very few objects need finalizers. A finalizer isneeded by only objects that must guarantee some cleanup of the object state before deallocating,typically releasing resources external to the JVM.With RAII in C++, one type of resource is typically wrapped inside a small class that allocates theresource upon construction and releases the resource upon destruction, and provide access to theresource in between those points. Any class that contain only such RAII objects do not need to definea destructor since the destructors of the RAII objects are called automatically as an object of this classis destroyed. In Java, safe synchronous deallocation of resources can be performed deterministicallyusing the try/catch/finally construct.In C++, it is possible to have a dangling pointer, a stale reference to an object that has already beendeallocated. Attempting to use a dangling pointer typically results in program failure. In Java, thegarbage collector will not destroy a referenced object.In C++, it is possible to have uninitialized primitive objects. Java enforces default initialization.In C++, it is possible to have an allocated object to which there is no valid reference. Such anunreachable object cannot be destroyed (deallocated), and results in a memory leak. In contrast, inJava an object will not be deallocated by the garbage collector until it becomes unreachable (by theuser program). (Weak references are supported, which work with the Java garbage collector to allowfor different strengths of reachability.) Garbage collection in Java prevents many memory leaks, butleaks are still possible under some circumstances.

Libraries[edit]

C++ provides cross­platform access to many features typically available in platform­specific libraries.Direct access from Java to native operating system and hardware functions requires the use of the JavaNative Interface.

Runtime[edit]

C++ Java

C++ is compiled directly tomachine code which is then

Java is compiled to byte­code which the Java virtual machine (JVM) theninterprets at runtime. Actual Java implementations do just­in­time

[14][15][16]

executed directly by thecentral processing unit.

compilation to native machine code. Alternatively, the GNU Compiler forJava can compile directly to machine code.

Due to its unconstrained expressiveness, low level C++ language features (e.g. unchecked array access,raw pointers, type punning) cannot be reliably checked at compile­time or without overhead at run­time.Related programming errors can lead to low­level buffer overflows and segmentation faults. TheStandard Template Library provides higher­level RAII abstractions (like vector, list and map) to help avoidsuch errors. In Java, low level errors either cannot occur or are detected by the Java virtual machine(JVM) and reported to the application in the form of an exception.The Java language requires specific behavior in the case of an out­of­bounds array access, whichgenerally requires bounds checking of array accesses. This eliminates a possible source of instability butusually at the cost of slowing execution. In some cases, especially since Java 7, compiler analysis canprove a bounds check unneeded and eliminate it. C++ has no required behavior for out­of­bounds accessof native arrays, thus requiring no bounds checking for native arrays. C++ standard library collections likestd::vector, however, offer optional bounds checking. In summary, Java arrays are "usually safe; slightlyconstrained; often have overhead" while C++ native arrays "have optional overhead; are slightlyunconstrained; are possibly unsafe."

Templates vs. generics[edit]

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 quitedifferent.

C++ Templates Java Generics

Classes, functions, aliases and variables can betemplated.

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 begenerated for each parameter­set when compiled. For classtemplates, only the member functions that are used will beinstantiated.

One version of the class or function iscompiled, works for all type parameters(via type­erasure).

Objects of a class template instantiated with differentparameters will have different types at run time (i.e., distincttemplate instantiations are distinct classes).

Type parameters are erased whencompiled; objects of a class with differenttype parameters are the same type at runtime. It causes a different constructor.Because of this type erasure, it is notpossible to overload methods usingdifferent instantiations of the genericclass.

[17] [18]

Implementation of the class or function template must bevisible within a translation unit in order to use it. This usuallyimplies having the definitions in the header files or included inthe header file. As of C++11, it is possible to use externtemplates to separate compiling of some instantiations.

Signature of the class or function from acompiled class file is sufficient to use it.

Templates can be specialized—a separate implementationcould 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, notfunctions.

Generic type parameters cannot havedefault arguments.

Wildcards unsupported. Instead, return types are oftenavailable as nested typedefs. (Also, C++11 added keywordauto, which acts as a wildcard for any type that can bedetermined at compile time.)

Wildcards supported as type parameter.

No direct support for bounding of type parameters, butmetaprogramming provides this

Supports bounding of type parameterswith "extends" and "super" for upper andlower bounds, respectively; allowsenforcement of relationships betweentype parameters.

Allows instantiation of an object with the type of theparameter type.

Precludes instantiation of an object withthe type of the parameter type (except viareflection).

Type parameter of class template can be used for staticmethods and variables.

Type parameter of generic class cannotbe used for static methods and variables.

Static variables unshared between classes and functions ofdifferent type parameters.

Static variables shared between instancesof classes of different type parameters.

Class and function templates do not enforce type relations fortype parameters in their declaration. Use of an incorrect typeparameter results in compiling failure, often generating anerror message within the template code rather than in theuser's code that invokes it. Proper use of templated classesand functions is dependent on proper documentation.Metaprogramming provides these features at the cost addedeffort. There was a proposition to solve this problem inC++11, so­called Concepts, it is planned for the nextstandard.

Generic classes and functions canenforce type relationships for typeparameters in their declaration. Use of anincorrect type parameter results in a typeerror within the code that uses it.Operations on parametrized types ingeneric code are only allowed in ways thatcan be guaranteed to be safe by thedeclaration. This results in greater typesafety at the cost of flexibility.

Templates are Turing­complete (see templatemetaprogramming).

Generics are probably not Turing­complete.

[19]

Miscellaneous[edit]

Java and C++ use different means to divide code into multiple source files. Java uses a package systemthat dictates the file name and path for all program definitions. Its compiler imports the executable classfiles. C++ uses a header file source code inclusion system to share declarations between source files.Compiled Java code files are generally smaller than code files in C++ as Java bytecode is usually morecompact than native machine code and Java programs are never statically linked.C++ compiling features an added textual preprocessing phase, while Java does not. Thus some usersadd a preprocessing phase to their build process for better support of conditional compiling.Java's division and modulus operators are well defined to truncate to zero. C++ (pre­C++11) does notspecify whether or not these operators truncate to zero or "truncate to ­infinity". ­3/2 will always be ­1 inJava and C++11, but a C++03 compiler may return either ­1 or ­2, depending on the platform. C99defines division in the same fashion as Java and C++11. Both languages guarantee (where a and b areinteger types) that (a/b)*b + (a%b) == a for all a and b (b != 0). The C++03 version will sometimes befaster, as it is allowed to pick whichever truncation mode is native to the processor.The sizes of integer types are defined in Java (int is 32­bit, long is 64­bit), while in C++ the size ofintegers and pointers is compiler and application binary interface (ABI) dependent within givenconstraints. 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 forthe local platform.

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

In addition to running a compiled Java program, computers running Java applications generally must alsorun 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 isbecause the program statements of these two closely related languages may compile to a few machineinstructions with C++, while compiling into several byte codes involving several machine instructions eachwhen interpreted by a JVM. For example:

Java/C++ statement C++ generated code (x86) Java generated byte code

vector[i]++;

mov edx,[ebp+4h] mov eax,[ebp+1Ch] inc dword ptr [edx+eax*4]

aload_1 iload_2 dup2 iaload iconst_1 iadd iastore

Since performance optimizing is a very complex issue, it is very difficult to quantify the performancedifference between C++ and Java in general terms, and most benchmarks are unreliable and biased. Giventhe very different natures of the languages, definitive qualitative differences are also difficult to draw. In anutshell, there are inherent inefficiencies and hard limits on optimizing in Java, given that it heavily relies onflexible 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, compiledC or C++ code can be called from Java via the JNI.

Some inefficiencies that are inherent to the Java language include, mainly:

All objects are allocated on the heap. For functions using small objects, this can result in performancedegradation and heap fragmentation, while stack allocation, in contrast, costs essentially zero. However,modern JIT compilers mitigate this problem to some extent with escape analysis or escape detection toallocate objects on the stack, since Oracle JDK 6.Methods are virtual by default (although they can be made final), usually leading to an abuse of virtualmethods, adding a level of indirection to every call. This also slightly increases memory use by addingone pointer per object to a virtual table. It also induces a start­up performance penalty, since a JITcompiler must perform added optimizing passes to devirtualize small functions.A lot of run­time casting required even using standard containers induces a performance penalty.However, most of these casts are statically eliminated by the JIT compiler.Safety guarantees come at a run­time cost. For example, the compiler is required to put appropriaterange checks in the code. Guarding each array access with a range check is not efficient, so most JITcompilers will try to eliminate them statically or by moving them out of inner loops (although most nativecompilers for C++ will do the same when range­checks are optionally used).Lack of access to low­level details prevents the developer from improving the program where thecompiler is unable to do so.The mandatory use of reference­semantics for all user­defined types in Java can introduce largeamounts of superfluous memory indirections (or jumps) (unless elided by the JIT compiler) which canlead to frequent cache misses (a.k.a. cache thrashing). Furthermore, cache­optimization, usually viacache­aware or cache­oblivious data structures and algorithms, can often lead to orders of magnitudeimprovements in performance as well as avoiding time­complexity degeneracy that is characteristic ofmany cache­pessimizing algorithms, and is therefore one of the most important forms of optimization;reference­semantics, as mandated in Java, makes such optimizations impossible to realize in practice (byneither the programmer nor the JIT compiler).Garbage collection, as this form of automatic memory management introduces memory overhead.

However, there are a number of benefits to Java's design, some realized, some only theorized:

Java garbage collection may have better cache coherence than the usual use of malloc/new for memoryallocation. Nevertheless, arguments exist that both allocators equally fragment the heap andneither exhibits better cache locality. However, in C++, allocation of single objects on the heap is rare, andlarge quantities of single objects are usually allocated in blocks via an STL container and/or with a smallobject allocator.Run­time compiling can potentially use information about the platform on which the code is beingexecuted to improve code more effectively. However, most state­of­the­art native (C, C++, etc.) compilersgenerate multiple code paths to employ the full computational abilities of the given system. Also, theinverse argument can be made that native compilers can better exploit architecture­specific optimizingand instruction sets than multi­platform JVM distributions.Run­time compiling allows for more aggressive virtual function inlining than is possible for a staticcompiler, because the JIT compiler has more information about all possible targets of virtual calls, even ifthey are in different dynamically loaded modules. Currently available JVM implementations have no

[20]

[21] [22]

[weasel words]

[23][24]

[25]

problem in inlining most of the monomorphic, mostly monomorphic and dimorphic calls, and research isin progress to inline also megamorphic calls, thanks to the recent invoke dynamic enhancements addedin Java 7. Inlining can allow for further optimisations like loop vectorisation or loop unrolling, resultingin a huge overall performance increase.In Java, thread synchronizing is built into the language, so the JIT compiler can potentially, via escapeanalysis, elide locks, significantly improve the performance of naive multi­threaded code. This methodwas introduced in Sun JDK 6 update 10 and is named biased locking.

Also, some performance problems occur in C++:

Allowing pointers to point to any address can make optimizing difficult due to possible interferencebetween pointers that alias each other. However, the introduction of strict­aliasing rules largely solves thisproblem.Since the code generated from various instantiations of the same class template in C++ is not shared (aswith type­erased generics in Java), excessive use of templates may lead to significant increase of theexecutable code size (code bloat). However, because function templates are aggressively inlined, theycan sometimes reduce code size, but more importantly allow for more aggressive static analysis andcode optimizing by the compiler, more often making them more efficient than non­templated code. Incontrast, Java generics are necessarily less efficient than non­genericized code.Because dynamic linking is performed after code generating and optimizing in C++, function callsspanning different dynamic modules cannot be inlined.Because thread support is generally provided by libraries in C++, C++ compilers cannot perform thread­related optimizations. However, since multi­threading memory models were introduced in C++11, moderncompilers have the needed language features to implement such optimizations. Furthermore, manyoptimizing compilers, such as the Intel compiler, provide several language extensions and advancedthreading facilities for professional multi­threading development.

Language specification[edit]

The C++ language is defined by ISO/IEC 14882, an ISO standard, which is published by the ISO/IECJTC1/SC22/WG21 committee. The latest, post­standardization draft of C++11 is available as well.

The C++ language evolves via an open steering committee called the C++ Standards Committee. Thecommittee is composed of the creator of C++ Bjarne Stroustrup, the convener Herb Sutter, and otherprominent 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 releasesof the standard and technical specifications. The committee now aims to release a new standard every fewyears, although in the past strict review processes and discussions have meant longer delays betweenpublication of new standards (1998, 2003, and 2011).

The Java language is defined by the Java Language Specification, a book which is published by Oracle.

The Java language continuously evolves via a process called the Java Community Process, and the world'sprogramming community is represented by a group of people and organizations ­ the Java Communitymembers —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 intothe language.

[26]

[27]

[28]

[29]

[30]

[31]

[32]

The lack of a firm standard for Java and the somewhat more volatile nature of its specifications have been aconstant source of criticism by stake­holders wanting more stability and conservatism in the addition of newlanguage and library features. In contrast, the C++ committee also receives constant criticism, for theopposite reason, i.e., being too strict and conservative, and taking too long to release new versions.

Trademarks[edit]

"C++" is not a trademark of any company or organization and is not owned by any individual. "Java" is atrademark of Oracle Corporation.

From Wikipedia, the free encyclopediaJump to: navigation, search

This article is within the scope of WikiProject Computing, a collaborative effort to improve the coverage ofcomputers, computing, and information technology on Wikipedia. If you would like to participate, please visitthe project page, where you can join the discussion and see a list of open tasks. This article is within thescope of WikiProject Java, a collaborative effort to improve the coverage of Java on Wikipedia. If you wouldlike to participate, please visit the project page, where you can join the discussion and see a list of opentasks.(Rated Low­importance)

This article is within the scope of WikiProject C/C++, a collaborative effort to improve the coverage of C/C++on Wikipedia. If you would like to participate, please visit the project page, where you can join the discussionand see a list of open tasks. ??? This article has not yet received a rating on the quality scale.­­­

Untitled[edit]

I'm a C fan and I also like some features introduced by C++. I never wrote a Java program before. Iprogrammed in C but used both C and C++ compilers, sometimes adding to the code features likereferences. However, my impression is: this article puts Java in an unfavorable light compared to C++, whichmight be viewed as subjective. Also, I have a personal impression. Everyone is able to produce someworking program in Java (simply because of the library offered methods), while to write high qualitysoftware, both high level programming in C/C++, algorithm and data structure knowledge is needed. I haveno idea how the JVM is implemented, however, I bet it began with a C/C++ compilation. And the only nicefeature Java has is some metaprogramming (I prefer Lisp much more for this purpose and it also can beembaded with C/C++). Also C/C++ stands for decades (and probably will continue to stand), however, mypersonal impression is that Java is fading away and PHP takes it's place (my job is as a PHP programmerand I hate it, however, like before with Java, today everyone can code some program in PHP, so findingenough great C/C++ programmers is hard and only the top companies can afford it (I live in a low economycountry)).

­­­ —Preceding unsigned comment added by 79.113.42.109 (talk) 19:43, 1 April 2011 (UTC) This article

[33]

[34]

does not compare Java and C++ programming languages.

­­­ —Preceding unsigned comment added by 190.175.146.75 (talk) 11:32, 6 October 2010 (UTC) Thisarticle does not compare Java as programming language against C++. It compares Java + Java ByteCode +JVM against C++ + Native Assembler. Which is very stupid, since you can mix these anyway you want. Forexample you can run on other JVM's. You can compile Java code into native assembler code or C++ codeinto Java ByteCode. What's the point of this article? It's just wrong. If something, it should compare thelanguages. And for example for performance comparision, they both must be compiled into the same to becomparable.

Anonymous User: I think the person who wrote it doesn't like java, by listing all the ways java is worse thenc++, and not the other way around. Also, he put extra code, such as .clone() that is not needed. —Preceding unsigned comment added by 74.95.9.18 (talk) 01:14, 19 August 2012 (UTC)

­­­ —Preceding unsigned comment added by 83.254.91.82 (talk) 20:06, 1 May 2009 (UTC)

There is no universal clone() method in Java. Although Object has a clone() method, it is protected and willthrow an exception if a subclass that tries to call it does not implement the Cloneable interface. I'm going tonote this in the code samples table.

—Preceding unsigned comment added by 68.35.12.123 (talk) 07:30, 25 May 2008 (UTC)

There are some on­line articles comparing Java with C++. Some of them emphasize C++'s advantages,while others highlight Java's. Who's that guy who write "Thinking in Java"? He had a pretty comprehensiveone, although it's dated now. User:Ed Poor

–––– This is my first time editing Wiki, so please correct me if I am not doing this correctly. Just trying tohelp :P.

After looking at source 5, I completely disagreed on the validity of the findings of I/O operations. A differenceof 5 ms is not an acceptable difference, since the bottleneck is the HDD and not the language. If the HDD isordered to write 8 MBs, then it will write it when it can and that depends on a large amount of factors.

Furthermore, figure 6 shows completely the opposite of what the statement (Java outperforms C++ inoperations such as memory allocation and file I/O) is saying. Just to test this memory allocation I quicklywrote a program to flip ~16000x16000 matrix: all ints. This matrix should theoretically take 1024 MBs. Afterconfiguring the Java to eat up 1400 MBs of RAM it agreed to do it....somewhat. For compiling (WinXP) I ranDev­CPP4.9.9.2 with GCC 3.4.2 for mingw. For Java I used 3.2.2 Eclipse with Java 1.6.0. The matrix wasread from a file and only then the program started counting.

C++ ate up 1.02 gigs and after 20 trials it printed out 1.8x seconds for each. Java's time were much lessconsistent. It ate up 1.01 gigs, but running times were much different. They ranged from 2.2 seconds to 2.9seconds.

I believe that the article there is dated and invalid. 24.12.159.57 02:59, 23 May 2007(UTC)ShadowPhoenix24.12.159.57 02:59, 23 May 2007 (UTC)

The memory locality and allocation performance claims about Java being more efficient than C++ apear asnonsense to me, considering that when using C and C++ we have full control over these aspects. We're free

to implement or use whatever efficient memory allocation system required. This is definitely not the casewith Java. My guess is that those claims are only valid for casual C++ users than actual low­level coders whohave an understanding of optimization issues. We can roll­out custom allocators, as well as define datastructures and their relations recisely. As for the platform­independence aspects, C and C++ are actuallymore portable (Java only being available on specific architectures and platforms), yet I agree somearchitecture­specific performance tweaking can be necessary for optimal performance. The part aboutarchitecture­dependent floating point issues appears valid for C++. 66.11.179.30 23:30, 17 June 2007 (UTC)

–––––––­­­­­­­­­­

Maintaining a NPOV[edit]

A comparison of Java to C++ should list differences. Calling those differences "advantages" or"disadvantages" of one language or the other is in most cases controversial and shows bias. Additionally, it'soften impossible to argue in favor or against a specific language feature without considering the broaderperspective and intent of the languages.

In the interest of maintaining a NPOV, I have reworded and moved all items from the"advantages"/"disadvantages" lists to the "differences" list. In addition, I've added a paragraph that describesthe cause of many differences: differing design aims.

I urge future editors to not show bias.

­­ Eelis 01:53, 2005 May 23 (UTC)

Someone deleted information about 64­bit numbers (from IP 213.94.248.38 on July 8), claiming it to beinaccurate. I have restored this information, and added a link to the 64­bit page to allow editors to vouche itsauthenticity, along with clearer wording. CmdrRickHunter 06:06, 2 August 2006 (UTC)

A previous edit indicated that there was dispute over whether or not C++ is better for "DSP or arithmaticheavy" operations.

I would like to add text clarifying it, but I do not feel that I have fully researched the topic. Here are my points:

For sequential arithmatic, Java and C++ are on the same level. However, Java cannot support vectorprocessing because its very processor dependant. C++ allows one to craft code designed for specificprocessors, opening up the use of SSE or AltiVec.A search for Java DSP or Java vector arithmatic yields no hits for while doing similar searches for C++yield libraries designed for native interfacing with the vector processors.

Based on this, I feel the statment should be added back into the article, with clarification. However, since Iam new to wikipedia, I'd at least like to see if anyone has feedback on the idea.CmdrRickHunter 21:32, 30June 2006 (UTC)

I think Java's lack of operator overloading is a serious disadvantage with DSP processing (or any kind ofscientific computing), especially if you want to use complex numbers. It may not effect performance much,but operator overloading can make complex arithmetic MUCH easer to read in a programming language.Despite that, I've used Java for some simple scientific computing applications because I'm most familiar with

it, and it's left me motivated to write a Java preprocesser specifically for complex numbers :/

I'm going to remove the comment that this article should be merged because I don't agree with the reasons,and the fact that editing has remained active for over 5 months and about 40 edits leads me to believe thereare plenty of others to support my position. If this should be merged, I think there are enough people whohave worked on this article that there should be some discussion here first. I don't want to see anoverzealous and possibly inexperienced editor coming along, see the merge task as a community decisionwaiting to be implemented, and do the merge without discussion. CyborgTosser (Only half the battle) 20:22,25 Feb 2005 (UTC)

For reference, here is the original merge request as posted by Netoholic:

This article or section should be merged with the Java programming language & the C++ programminglanguage.CyborgTosser (Only half the battle) 20:27, 25 Feb 2005 (UTC)

My main point is that there are infinite combinations of comparison articles possible (just the top 10languages alone would lead to 45 such articles). A much better approach would be to put the "Advantages"and "Disavantage" sections within each language article itself. That way, you can reduce the redundancywhere a language has dis/advantages over multiple other ones. ­­ Netoholic @ 22:12, 2005 Feb 25 (UTC)

There are many possible combinations for articles, but probably only about a dozen that would makeinteresting articles. In particular, when one language is strongly influenced by another (this article) or if thelanguages represent a split in design philosophy within a given paradigm (such as OCaml vs. Lisp), there isa possibility for an interesting article. An advantages/disadvantages section in each article would be a goodidea, but as long as the number of comparison articles we have doesn't grow without bounds, I don't thinkthere will be a lot of redundancy. Look, for example, at this article and the comparison of Java to C#. Whatgives Java an advantage/disadvantage compared to C++ is not the same as compared to C#. But I will takea "wait and see" attitude on this. If I am wrong and there is a ton of redundancy as more of these articlespop up, then I'm in support of consolidation. CyborgTosser (Only half the battle) 23:28, 25 Feb 2005 (UTC)

resource[edit]

This article equates resource with memory, but a resource might also be a lock that is acquired and lots ofother things too.­­MarSch 15:05, 27 October 2005 (UTC)

contributions by 68.68.100.185[edit]

The biggest consequence of this is that you can't have const parameter types in Java. ­ this is at leastincredibly misleading if not incorrect. to properly explain this would require more space than this articleshould dedicate to the subject. someone interested in knowing more should research it further.

Destructors are essentially what enable the RAII idiom, as deallocation is done in the destructor. This meansthat the RAII idiom is impossible to implement properly in Java... ­ besides being poorly written/explained, ithink this is too much depth for the article, but i think drawing a little more distinction between destructorsand finalizers is appropriate.

i've updated accordingly. critique, rebut, modify at will ;) ­­pfunk42 14:54, 26 December 2005 (UTC)

Edits by 84.61.26.158 on January 10, 2006[edit]

There is a pro­C++ (or perhaps anti­Java) POV in many of these contributions. I've lightly editted some ofthem to attempt NPOV. I admit to having my own bias, which I am trying not to include in the article. Thereare some specific points I'll address here for discussion before making additional changes to the article.Additions from 84.61.26.158 in the excepts from the article below are shown in bold italics.

C++ features callbacks, which must be simulated in Java using trampolines.

I have a couple issues with this. First, callbacks are not a feature of C++, but rather a use of functionpointers (or functors). So a callback is not a feature of C++ (although function pointer is a feature that can becompared). Second, the mechanism in Java is to use an object for a callback, or more pointedly, to definethe callback method using an interface and pass an object that implements the interface in place of the C++function pointer. This mechanism does not match the definition of a trampoline. ­­ Doug Bell 23:12, 10January 2006 (UTC)

Removing it, but a good statement regarding function pointers should be put in. ­­pfunk42 19:10, 11 January2006 (UTC)

C++ supports goto statements; Java does not, but its labelled breaks provide some goto­likefunctionality. In fact, Java enforces structured control flow, with the goal of code being easier tounderstand. That can make code distintly less readable.

I corrected the spelling, but left the statement. My problem with this is that while there can be a case madefor limited circumstances where a goto can make code more readable (and most of these cases areobviated by the use of exceptions to handle errors and exception execution paths), there are many morecases where the use of goto makes code less readable. That makes this statement an unbalanced POV. ­­Doug Bell 23:12, 10 January 2006 (UTC)

That can make code distinctly less readable. I have no idea what "that" is supposed to refer to, so thisstatement is gone. I see no POV problem with the way it was because with the goal of leaves the reader todraw his/her own conclusion as to whether enforcing structured control flow makes code easier tounderstand. ­­pfunk42 19:10, 11 January 2006 (UTC)

The encoding of string and character literals in C++ is as the programmer sees fit.

This used to say "platform dependant". I wasn't aware that it was a feature of C++ to allow the programmerto determine how the compiler encodes string and character literals. Perhaps this is a feature of somespecific C++ compiler? ­­ Doug Bell 23:12, 10 January 2006 (UTC)

I'm reverting it. 84.61.26.158 is wrong. ­­pfunk42 19:10, 11 January 2006 (UTC)

In Java, all code is implicitly multithreaded, though most programmers are unaware of that fact.Deadlocks can thus easily happen.

I have a few issues with this statement.

Deadlocks do not easily happen in Java because of the inherent multi­threaded nature of Java programs.This is because unless a Java program is operating in a multi­threaded context, such as an Applet orapplications with a GUI, all of the main application code and objects run in, and are accessed from, asingle thread. There is no opportunity for contention or deadlock.

Both C++ and Java programs that run in a multi­threaded context can suffer from problems inherent inmulti­threaded programs (deadlocks and race conditions). This includes any applications that support callbacks or events, to name a couple. This means that the issue of deadlock is not a Java phenomenon, butrather a multi­threaded programming phenomenon relavent to both Java and C++.

The statement that most programmers are unaware of when they are programming in a multi­threadedcontext is unsubstantiated speculation.

I'm assuming that the underlying issue here is the Java synchronized mechanism, but that's not readilyapparent from the statement. Deadlock could also occur in a multi­threaded C++ program that used mutexlocks to guard against contention, except that in the case of the C++ program, the release of the mutex lockis not enforced by the programming language. So it can be argued that deadlock is more likely in the multi­threaded C++ program than in the comparable Java program. ­­ Doug Bell 23:12, 10 January 2006 (UTC)

I'm removing it. If you don't declare multiple threads in your code, deadlock is impossible. Wait, the Swingthread pops up implicitly, but that doesn't fall under "happening easily in all code". ­­pfunk42 19:10, 11January 2006 (UTC)

which might never happen. Guaranteed execution of finalizers before exit can be requested throughthe API. ==> removing qualifier. ­­pfunk42 19:10, 11 January 2006 (UTC)

Actually, System.runFinalizersOnExit has been deprecated for some time. So the statement whichmight never happen is correct. There is no way to force finalization to occur. Even callingSystem.runFinalization will not guarantee execution of the finalizers. I readded the statement andexpanded the comparison of destructors and finalizers.­­ Doug Bell talk/contrib 21:13, 11 January 2006(UTC)

In C++ we have the programming model of multiprocessing. We can create multiple multiple processes andcommunicate using shared memory calls. This model you can find in Apache Unix versions. If the applicationruns for more than a minute, multiprogramming model can be considered. The locking and unclokingproblem will not be present at all. Data sharing between processes is less(low coupling when designed). It isnearly impossible in JAVA to implement this model in an efficient way. Another advantage is variousplatforms impose a limit on stack size when functions are called in multithreaded applications. This limitationis not applicable to this model. This is C++ way of designing and programming. :­) Jayaram Ganapathy

references for the design goals of C++ (and Java)[edit]

The article contains this table:

The different goals in the development of C++ and Java resulted in different principles and designtradeoffs between the languages.

C++ Java

execution efficiency developer productivity

trusts the programmer protects the programmer

arbitrary memory access possible memory access only through objects

concise expression explicit operation

can arbitrarily override types type safety

procedural and object­oriented object­oriented

redefine operators meaning of operators immutable

feature rich easy to use

which implies that for example execution efficiency and developer productivity are opposites. It is myunderstanding that C++ aims for both of these (and supports developer productivity with genericprogramming, unlike Java), while this table seems to say that using java allows for greater developerproductivity. All other entries also suffer from POV or are simply false. I'd like some references for this table,for example from The Design and Evolution of C++. The fact Java doesn't support operator­overloading ortemplates, doesn't make it easier to use. What it does mean is that C++ has a far more powerful way ofexpressing, resulting in generic algorithms. Java doesn't protect the programmer, it forces the programmernot to do certain things. C++ protects the programmer, by providing type safety, but also providing casts. Ithink there is a lot of pro­Java POV in this article. Even the title (Comparison of Java to C++) is POV. MarSch13:21, 5 March 2006 (UTC)

if your commentary isn't a totally biased Java flame, i don't know what is. POV! POV! POV!!! (i can say ittoo). . . . more seriously, i think you're taking the table to mean a lot more than intended. the tableoutlines rough design goals. it's not meant to be conclusionary about the efficacy or merits of those goals,or how elegantly the languages fulfill those goals. . . . but also, some of what you say is just wrong. :) ­­pfunk42 14:58, 5 March 2006 (UTC)

While, as pfunk42 points out, there are many points where MarSch is just wrong, I think s/he makes acouple good points. First, a better name for the article would be Comparison of Java and C++. Second,there should be references for the languages respective design goals. However, these points arecompletely wrong:

OK, I renamed the page as above. – Doug Bell 05:00, 6 March 2006 (UTC)

implies that for example execution efficiency and developer productivity are oppositesNothing of the sort is implied. What is stated is that each language had principles that establishedpriorities that guided the design of the language.supports developer productivity with generic programming, unlike JavaUh, right there in the article it talks about comparing generics and templates and even references asibling article Comparison of generics and templates that compares the two features in depth.All other entries also suffer from POV or are simply false.

talk•contrib

This statement clearly suffers from both POV and simply being false.The fact Java doesn't support operator­overloading or templates, doesn't make it easier to use. A point that can be argued to death without ever reaching a decisive conclusion because "easier" issubjective and not uniquely quantifiable...however, the points in the table are, as pfunk42 points out,discussing goals, not outcome.

The rest of the points raised by MarSch are POV. This article has been edited by both Java, C++, and Java+ C++ users and while it can be better, it is not a one­sided myopic view of the subject as MarSch seems tosuggest. – Doug Bell 18:23, 5 March 2006 (UTC)

This section has been modified since the discussion above, but this seems to be the appropriate place todiscuss its current status. Recently, I corrected a sentence in another section that said, incorrectly, that inJava function parameters were call­by­reference if the parameters were objects. This, of course, is false: inJava all function parameters are passed by value. Now, in this section, it says that Java has "referencesemantics for user­defined objects", while C++ has "value­based semantics and explicit pointers". Thequestion I have is whether this is simply the same misunderstanding of Java's parameter passing that Icorrected before? The explicit calling out of "user­defined objects" suggests that it is, since in Java there isno difference between user­defined objects and built­in objects, so there definitely is somemisunderstanding somewhere. On the other hand, is this some subtle semantic point? (After all, in Javathere are reference types. But then, in C++ there are reference parameters as well, and so what does"value­based semantics" mean?) I'm inclined to just cut this line in the table, on the grounds that even ifwhatever it was meant to say is correct, it certainly doesn't convey said meaning currently. Any objections orclarifications? SlitherM 03:58, 22 March 2007 (UTC)

See also, later on, "In Java, parameters are passed using pass­by­reference for non­final objects and pass­by­value for final objects and primitives.". Again, AIUI, what is actually happening is that an object referenceis being passed­by­value. 80.168.196.219 20:24, 27 April 2007 (UTC)

The last bit about "pass­by­reference for non­final objects" was made after I wrote the above question, andis, of course, completely wrong. I've fixed it once more. As for the original question about the line in thetable, since nobody seems to know what that line is supposed to mean, other than confusion aboutparameter passing, I replaced the line with a statement about parameter passing. SlitherM 14:44, 30 April2007 (UTC)

Cleanup tags[edit]

I've added three cleanup tags to this article.

Tone: This article consists mainly of bulleted lists of features, rather than a more encyclopedic discussionof fundamental issues.Not verified: The article does not cite sources sufficiently, especially in the "Design aims" section; it makesa number of unverified (and implementation­dependent) claims about speed and size, as well as a fewabout ease of programming and/or maintenance.Importance: What information does this article provide that is not already covered by Java programminglanguage and C++?

—donhalcon 05:47, 6 March 2006 (UTC)

talk•contrib

Syntax power![edit]

"C++ has more powerful syntax than Java", says the article. Right. Powerful. Precisely what, may I ask, does"powerful" mean in the context of syntax?

The whole thing seems to be like that. This article doesn't need cleanup, it needs deleting completely andrewriting from scratch, preferably by someone who doesn't prefer either language and is therefore capableof viewing them objectively. — Haeleth Talk 23:15, 16 May 2006 (UTC)

"power" in the sense of doing more with less. ­­pfunk42 16:56, 3 June 2006 (UTC)

in which case, "expressive" or "compact" are more specific adjectives that might be worth consideringinstead. JulesH 10:43, 17 July 2006 (UTC)

From my experiance, "power," is the adjective most comonly used to describe a syntax which allows for agreat deal of versitility with a minimal number of keystrokes. This matches C++ very well. And "powerful" isaccurate in annother way ­ C++ can do more than Java, because Java has chosen to sacrifice power forsafety. Just as C++ offers you more power to do what you want, it also offers you more power to hangyourself with a sphagetii goto mess with a dangling pointer while your boss gives you questioning looksduring the demonstration.CmdrRickHunter 06:10, 2 August 2006 (UTC)

I perfectly agree with CmdrRickHunter. JAVA is a language for easy development which prevents adeveloper from comitting mistakes and saves him. Its language syntax is for defending for which it pays inthe performance and flexibility. JAVA is not a language developed to show power. Its for fast and error freedevelopmet with lessor effort. I would appretiate members to discuss their thoughts and learnings and wecan go ahead rather than just making statements like just rework the entire page. Comparing with otherlanguages like LISP is a wonderful idea but the members who know LISP shpuld take initiative for that.

You comments are indicative of one who is not thoroughly familiar with the Java language. Java is not C++,which I believe is the intended point of this article. It is by no means slower, less powerful, or necessarilyeasier to develop than C++. This article reeks of NPOV. I don't think it has to be completely rewritten, but itneeds a rethink in the approach. HotBBQ 17:01, 17 April 2007 (UTC) Dear friend you cannot blindly say "it isby o means slower, less powerful etc.." We are here to discuss. If you have a point why it cannot be slowerthen put it down here. Convince the world. Any given day if you write a program in JAVA 99% of time a C++equivalent will run better. 1 % they will be equal when the bench mark code is based on primitive data types.But if the bench mark is written using powerfull C++language features, the euivalent porting in JAVA in astraight forward way may not be possible at all because JAVA compromises the language power for easyprogramming. In this case the code written in JAVA may become twice big as C++ and performance evenworse. I develop in both the languages. Jayaram Ganapathy

Java­centric[edit]

A partisan article like the one comparing Java and C++ has no place in Wikipedia. Its Java drum­beating isembarrassing to anyone who has dealt seriously with the range of computer languages. This piece is error­ridden and should be rewritten from the ground up.

A more general issue is, what is the point of an encylopaedia article that takes two particulars from a larger

set and compares them? That is ­­ C++ and Java are just two of several commonly used object­ (andfunction­) oriented languages. Where are the others? Python, LISP, Delphi, Smalltalk... these are languagesthat have significant industrial usage around the world. They all have thousands of advocates who canintelligently defend their particular advantages. (For example, space and atomic energy enterprises morecommonly use LISP dialects than C++ or Java for their generalized applications.)

I believe that an article comparing all the major object­ and function­oriented languages would be useful inthis encyclopaedia. It would be difficult to write in a fair manner, but could be quite useful ­­ even influential ­­if it were done well. —Preceding unsigned comment added by Kentfx (talk • contribs)

Some inaccuracies[edit]

Some things I believe are inaccurate, but which I'm not updating because I don't have sources for most ofthis.

Still it's possible to have memory leaks in java, via cross­referencing, on most JVM implementations. Twounused object (not referenced anymore by the main application) could reference themselves so they are stillmarked as used and not garbage­collected.

As I understand it, most if not all Java implementations use mark and sweep garbage collection or somesimilar method to collect cyclical references. Certainly all the ones I've worked on do not suffer this problem.It is possible to have memory leaks, but only by making objects that will never be used again theoreticallyreachable if you followed the right chain of references.

In Java, assembly code can only be accessed as libraries, through the Java Native Interface. However,there is significant overhead for each call.

This depends on the implementation of Java you are using. There is nothing in the Java Language or VirtualMachine specifications that requires the use of JNI for any native code calls. See, e.g., gcj's "CNI"implementation, which allows a native method to be implemented in C++ and directly linked to the class thatuses it[1]. In this case, the overhead is significantly lower, and is in many cases as efficient as a C++ methodcall.

The same objection also applies to the statement "Direct access from Java to native operating system andhardware functions requires the use of the Java Native Interface."

Both Java and C++ distinguish between native types (these are also known as "fundamental" or "built­in"types) and user­defined types (these are also known as "compound" types). However, in C++ this distinctionis far less extensive.

This sentence is meaningless. It should be expanded with specific examples of why the distinction is lessextensive in C++ (e.g. ability to construct a reference to fundamental types in C++ but not in Java).

Due to the lack of constraints in the use of some C++ language features (e.g. unchecked array access, rawpointers), programming errors can lead to low­level buffer overflows, page faults, and segmentation faults.

Java can cause page faults too, you know. Changing "page faults and segmentation faults" to "memoryaccess violations" might make sense.

In C++, if you have an array, or a pointer to an array, or a reference to an array, you can determine thearray's size using the "sizeof" operator; however, if you only have a pointer to the first element of an array,its size cannot be determined.

I think this might better be phrased as "In C++ the size of an array may only be determined (using the"sizeof" operator) statically at compile time; it is impossible to determine the size of an array from a pointerto its first element." The text in the article appears to suggest that some construct like the following examplewould work:

void myFunction (int (&anArray)[]) cout << sizeof(anArray) << endl;

It won't (you'll get a compiler error in the declaration of the function, as the size of a referenced array mustbe known statically at compile time).

(All of the above JulesH 11:06, 17 July 2006 (UTC))

Wondering about this quote "C++ features programmer­defined operator overloading. The only overloadedoperators in Java are the "+" and "+=" operators, which concatenate strings as well as performing addition."AFAIK the at least * is overloaded, i.e. it can multiply integers or reals.—The preceding unsigned comment was added

by 24.201.100.166 (talk • contribs) 05:26, 3 April 2007 (UTC)

I do not know whether multiplying integers uses a separate instruction from multiplying floating­point values(I assume by "reals" you meant "floating­point values" as integers are real numbers) in the JVM (it does onmost real processors). However, I do know that they are semantically the same (whereas addition andconcatenation are not), and as such it does not qualify as overloading from a language perspective. Thisapplies to addition, subtraction, division, and modulus, as well as all derived operations (+=, ‐=, etc.)—Kbolino 01:22, 4 April 2007 (UTC)

In:

In Java, parameters are passed using pass­by­reference for non­final objects and pass­by­value for finalobjects.

This is wrong. The problem is that pass­by­reference and pass­by­value have different meanings in differentcontexts and on the relative point of view. In contrast to C++ a program variable in Java cannot hold anobject but only a reference to an object. Therefore in Java there is only pass­by­value (it passes thereference as a value) but in terms of C++ Java passes objects by­reference.

Yeah, this is wrong. I've fixed it. This is the second time I've had to do so ­­ there seems to be generalconfusion about Java's parameter passing. SlitherM 14:52, 30 April 2007 (UTC)

Inaccuracies:

C++ is normally compiled directly to machine code which is then executed directly by the operatingsystem

Well no, at the level we're talking here, it's executed by the processor. 212.209.45.98 (talk) 09:35, 21 July2010 (UTC)

Arrays in C++[edit]

I edited the section on Java arrays vs. C++ arrays, to be clearer. To JulesH, the following construct is in factcorrect and works:

template<int N> void myFunction( int (&anArray)[N] ) cout << sizeof anArray << endl;

Another editor wrote these questions in the main article:

1. A pointer to an array is a pointer to the first element of the array, isn't it? 2. "sizeof" of a pointer to an array will produce the size of the pointer (probably four bytes)

to which the answers are:

1. No 2. You dereference the pointer before taking the sizeof.

Example:

int array[20]; int (*pointer)[20] = &array; cout << "size of array is " << sizeof *pointer << endl;

NB. I don't yet have a wiki username, my email is [email protected], time is 5 Sep 2006, 06:24 UTC.

Could somebody please explain why the answer to question 1 above is "No"? Why is a pointer to an array (or a reference, like &ArrayName) NOT a pointer to the first element of the array in C++?

Using int as an example:

An array of ints is similar to a pointer to an int.An array of an array of ints is similar to a pointer to an array of ints, which is similar to a pointer to apointer to an int.

That is why a pointer to an array is NOT a pointer to the first element of the array. You can look at the arrayas a pointer to the first element in the array.

OracleofTroy 20:52, 16 September 2006 (UTC)

Propaganda[edit]

As of now, this "encyclopaedia" material reads like a JAVA evangelist pamphlet, sorry. Totally unaceptable. —Preceding unsigned comment added by 85.138.1.15 (talk)

I would like to add to the same. The references section is a totally biased one except the one whichcompares C~ also. I kindly request the administrator to remove those links and discuss over the same untilan agreement on the same comes.

If you're implying that such prestigious organizations as the National Institute of Standards and Technology,Dr. Dobbs Journal, the Jet Propulsion Laboratory, and the University of Southern California produce biasedwork you are perhaps better off taking it up with them. derrick 23:43, 11 April 2007 (UTC)

To be very frank the institutions has nothing to do with what ever has been written. A paper presentationacceptance has to do only with the person who reviews it. There are situations when somebody has ropublish something to get a degree and the guide often closes his/her eyes. Here in wiki we don't have anysuch constraints :­) Jayaram Ganapathy

Jayaram Ganapathy doesn't say specifically what he/she thinks is biased about the references section, but itappears to be related to his/her comments in the #Performance section. Apparently, Jayaram believes thatthere are theoretical reasons why Java performance has to be slower than C++'s, and that therefore thereferences which say that this is not the case must be biased. There is a discussion about this in thatsection. If I've misunderstood Jayaram's reasons for thinking that the references are biased, then perhapshe/she could clarify. Otherwise, discussion should probably continue there. SlitherM 15:10, 30 April 2007(UTC)

Hi Friend, I have jotted something in the performance section. It will trigger your thoughts. What everoptimisation JAVA can do and gain in C++ if you do the C++ way you are better off. If you code in JAVA wayand the same way you map it to C++ way rather than writing in C++ then argue its difficult. Cheers(JayaramGanapathy)

What is the point of this article?[edit]

What is the point of this article except to allow a group of people to explain why they dislike C++? This doesnot belong in an encyclopedia. It is original research, unsourced and POV. I am proposing this article bedeleted since it seems more like a bulletin board for people who dislikes C++. Also, are we going to havearticles comparing every language out there? MartinDK 12:07, 10 November 2006 (UTC)

Proposal[edit]

OK since Doug objected to the article being deleted which is fine I make the following proposal:

The article is heavily tagged and with good reason. Someone needs to rewrite it and make it morebalanced and relevant. Also, please keep in mind that even though what you write may be true it must notbe original research. It needs to be either sourced or common knowledge as defined per policy. If youbelieve that something is common knowledge within a fairly specialized field like programming then

please explain why on the talk page. It doesn't have to be a long speech just a short explanation why youbelieve it is not original research.Alternatively I suggest that the content be merged into the Java and C++ articles.If all else fails I will nominate the article for deletion through AfD.

Dispute tags are not meant to stay on articles forever. They are meant to encourage other editors toimprove the article. When that doesn't happen it is unlikely that the article will be improved and so we mustconsider if it needs to be deleted or what else should happen to it. It cannot simply stay the way it is now.MartinDK 09:38, 11 November 2006 (UTC)

I don't disagree with any of your statements except for the notion of merging this into the Java and C++articles. Those articles already have enough to cover without including language vs. language comparisons,and duplicating these comparisons in each article is worse than having them here.

I would appreciate if you could expand on what you mean by "more balanced and relevant". Also in readingthis article I'm trying to understand the primary complaint behind the POV tag. The article seems fairly (notperfectly) balanced—I would think the primary issue would be to cite sources and maybe restructure so as tobe an article instead of an organized list.

Despite having spent some time improving this article in the past (if you think it is bad now, you reallywouldn't have liked it before), I'm not sure I will be the one to put the time in to improve it further. I simplythink that an article that's been edited by dozens of editors almost 300 times over more than 4½ yearsneeds to go through WP:AFD instead of WP:PROD. —Doug Bell 10:14, 11 November 2006 (UTC)

I can see how it has been greatly improved. I am going to go through the edit history and see when the tagswhere added and see whatever issues have already been resolved without the tag being removed.

Regarding balance and relevance parts are why I was reacting initially

C++ supports goto statements; Java does not, but its labelled break and labelled continue statementsprovide some structured goto­like functionality. In fact, Java enforces structured control flow, with the goal ofcode being easier to understand.Goto statements are very very rarely used by C++ programmers. C and C++ programmers generally try veryhard to maintain structure throughout the code to make it easy to understand. C++ programmers also useclasses like Java programmers to maintain structure (among other advantages).

Java also does support the goto statement, not just labeled break and continue. 165.199.1.50 (talk) 17:37, 3November 2011 (UTC) (School IP)

No, Java does not have a goto statement. The JVM supports a goto bytecode, but goto is not supported inJava source code. ­­ Schapel (talk) 21:04, 3 November 2011 (UTC)

A consequence 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 isno implicit narrowing conversion from int to boolean. This is handy if the code were a typo for if(a == 5), butthe need for an explicit cast can add verbosity when statements such as if (x) are translated from Java toC++.The part about forcing the programmer not to use implicit narrowing is fine. However, the last sentence does

talk•contrib

not seem relevant in a comparison of the two languages. It is not about the pros and cons of porting fromJava to C++ (which is often avoided anyway since the choice of language has been made to begin with andmost (not all though) C++ code predating Java has been heavily updated since.)

This additional functionality is available for C++ by (often free) third party libraries, but third party libraries donot provide the same ubiquitous cross­platform functionality as standard libraries.This point that Java is more portable than C++ is made throughout the article and bugs me. C++ wasdesigned to be portable. It contains no platform­specific parts itself. The STL was also meant to be portable.Also, the libraries the article talks about are in fact highly portable in most cases and maintained under theGPL. I think the point the article is trying to make is that the portability is largely implemented in the JavaVirtual Machine and not in the Java code itself. C++, being more low­level, does not enjoy this advantage.However, that is not due to C++ being flawed but rather because certain software vendors have decided toadd and change "features" that make it harder to port code that depends on low level system calls. But thenthe article should put it that way instead.

I can see why you would not want to merge the content into the two other articles. MartinDK 11:00, 11November 2006 (UTC)

OK the tone and not verified tags were added on March 6, well over 7 months ago. The article has beenheavily edited since then so I am removing them from the article. That leaves 2 tags that need to beremoved... that makes it easier. MartinDK 11:23, 11 November 2006 (UTC)

Intro[edit]

Cut from intro:

While C++ and Java share many common traits, their differences can make a simple task extremely difficultif the wrong language is chosen. For example, Java does not work well when it is forced to work directly withhardware, and C++ does not work well when reflection is required. If features from both languages arerequired, a programmer can use JNI to bridge between them, but that is outside of the scope of this article.

Where is any of this expanded on, after the intro? ­­Uncle Ed 20:31, 20 November 2006 (UTC)

Reasons for preferring one language over the other[edit]

I am totally neutral on which language is better, but I cut this:

As such, both C and C++ provide good support for both application and systems programming.

An evaluation like this ("good support") should be sourced to an authority or advocate. ­­Uncle Ed 20:38, 20November 2006 (UTC)

Furthermore, I would like to see comments from C++ and Java programmers (published comments, that is)on why various language features are more helpful, useful, convenient or harmful, difficult, etc. I do NOTwant to see an "overall" evaluation like "This language is best". Rather, on each specific aspect I want to seethe tradeoffs.

Like

The Java compiler supplied by Sun includes bounds­checking for arrays, and you can't turn it off. This isgood because blah, blah, blah. This is bad because yadda yadda yadda.C++ provides direct access to memory. This is good because, etc. This is bad because, etc.

Keep it neutral in terms of ducking any conclusions, but let all voices speak! ­­Uncle Ed 20:43, 20 November2006 (UTC)

When I studied this I read that C++ was not suitable for passing over the internet. If a glitch in a C++ pointerto memory occurred while passing over phone lines, it could be disastrous in the receiving computer. Java, Iread, was designed to be passed over the internet. Java avoided structures that if glitched could causeunending loops that would eat the receiving computer, or worse create an accidental internet virus. C++ ismore powerful, but also less stable in the unstable internet environment. Java is not as powerful, but muchmore stable against errors. My Flatley (talk) 05:42, 15 January 2011 (UTC)

Yes, Java is a safe language and C++ is an unsafe language, in the terminology of type safety. Java doesnot allow arrays to be accessed out of bounds or dereferencing arbitrary memory locations as C++ does. Ithink the article already discusses this point in plenty of detail. Do you think something should be changed oradded? Should we add the tradeoffs, such as Java does not allow buffer overflow errors which are commonin C++ programs, although C++ permits interfacing with low­level hardware by allowing arbitrary memoryaccesses which Java does not allow? ­­ Schapel (talk) 14:30, 15 January 2011 (UTC)

Note, that this argument was only true in 90s when the internet protocols didn't ensure failure­freecommunication. Since TCP­IP became widespread, the applications don't need to ensure the data integritythemselves as TCP­IP is failure­free protocol, so the argument is void. You may find interesting thatsupercomputers do not have any problems using C/C++ frameworks for communication between nodes.The result of any 'glitches' in the communication could be even more disastrous than you might think. Agood illustration of this is that supercomputers usually use error­free components even though they costseveral times more than consumer equipment. 1exec1 (talk) 12:27, 16 January 2011 (UTC)

You're misunderstanding what My Flatley was trying to say. To be honest, he didn't explain very well. Theproblems of C++ have nothing to do with communication. That's a red herring. The issue is that a Javaprogram cannot have a security issue such as a buffer overflow problem, which C++ programs can have.That's why it can be unsafe to download and run a C++ program. ­­ Schapel (talk) 13:09, 16 January 2011(UTC)

A new suggestion for approaching NPOV[edit]

Back in 2003 when I started making contributions to this article, I did most of my programming in Java andgenerally preferred Java to C++ (although I learned C++ first and had comparable amounts of experience inboth languages at the time). I now do most of my programming in C++, and generally prefer C++ to Java,but I don't disagree with any of what I contributed back then, or really even with very much of the othereditors' contributions at that time. In particular, I don't think the original organization of the article, with itsadvantages/disadvantages sections, was irreparably biased (however, I do think the current organization isbetter, for other reasons I will expand upon). The point of advantage/disadvantage sections in my mind wasthat there is overwhelming consensus on certain things that are difficult to do in each of the languages, andon certain things that are easy to do in each. There is also nearly as overwhelming a consensus on the

general points that C++'s syntax is in certain aspects overly complicated (for various reasons), but thatJava's simple syntax and lack of direct support for certain low­level functionality makes certain constructsthat are commonly used in C++ impossible to replicate exactly and difficult to emulate.

Simply put, there are both advantages and disadvantages to Java, and there are both advantages anddisadvantages to C++. Which language comes out better overall in the comparison, and indeed whichlanguage would seem to be better to an uninformed reader from the points made in the article, depends onwhich of the advantages/disadvantages the reader considers more important, which in turn depends on 1.what programming task they are trying to accomplish and 2. what programming style they are used to (andprobably several other factors).

The main reason I think the new organization is better (and in retrospect don't think the old organization wasvery good) is that there are plenty of points that are relevant to the article but can't be cleanly grouped intoone of the original two (advantages of each) or the expanded four (advantages/disadvantages of each)categories, namely:

1. differences that can not really be categorized as advantages or disadvantages at all (e.g. Java packagesvs. C++ namespaces, similar features with different syntax)

2. differences that would be considered, for example, an advantage of Java to some, a disadvantage ofJava to others, for reasons of personal bias (e.g. everything in Java belongs to a class)

3. design differences that manifest themselves in both advantages/disadvantages at the coding level in eachlanguage (e.g. multiple inheritance in C++)

4. differences whose status as advantage or disadvantage is real in most cases, but for which the languagethat comes out on top is highly dependent on problem domain (e.g. differences in handling of floating­point arithmetic), portability issues (e.g. differences in how prescriptive the standard is and what is"implementation­defined"), or experience and discipline of the individual programmer (e.g. Java'semphasis on and enforcement of structured programming)

5. differences whose status as advantage or disadvantage is real in most cases, and for which onelanguage consistently comes out on top, but whose importance is highly dependent on problem domain(e.g. operator overloading in C++), portability issues (e.g. Java's bytecodes, which allow the samecompiled program to be used as an applet on a web page regardless of client's machine, OS, orbrowser), or experience and discipline of the individual programmer (e.g. the presence of universalcoding conventions for Java)

6. differences that are highly dependent on the implementation of the compiler (and for Java of the VM) andchange with time (e.g. nearly all performance differences)

7. differences that for each language can be an advantage for the programmer, but a disadvantage for thecompiler implementor (e.g. complexity/flexibility of C++'s type system)

And so on. What concerns me most about the article currently, and about much of the debate on the talkpage, is that in the quest for "neutral point of view", it seems a lot of editors are unwilling to admit that therecould be any difference that is an advantage in Java, or (although this point seems to be far less commonlydisputed) an advantage in C++. Even as a C++ programmer, I have to say that some of the disputes onspecific differences that were originally listed as "Advantages of Java", and the resulting discussions onsome of these that found their way into the article at various times (although these have been trimmed downnicely in more recent versions), seem pretty nitpicky and don't contribute much. Again, I don't see it asmuch, but I would make the same point for any in­depth discussions of differences that were originally listed

as "Advantages of C++". It is also concerning to me how much content has been simply cut from the article,either because someone didn't agree with it or because consensus on the topic couldn't be reached on thetalk page.

I don't think it is helpful either to the readability of the article, or to getting a neutral point of view, to shy awayfrom an advantage/disadvantage viewpoint on every single difference. I think it would be much better to takea holistic approach to neutrality, and try to point out what individual differences are considered an advantageor disadvantage by a comfortable majority of programmers, even if not an overwhelming consensus. If thereis not even a comfortable majority opinion about a particular difference, then of course, I agree with nottrying to push either viewpoint.

Why do I care?

1. This article (or any article) should be useful to those who have little knowledge on the topic itself, but whohave enough general knowledge to understand most of it. Lots of arguments and counterargumentstends to bog this down and make an article fairly unencylopedic. The only reason an article should bemostly debate is if the article is about a debate (i.e. the article is not History of the C++ vs. Java debate). Iimagine the ideal article being most useful to someone who doesn't know much about one or other of thelanguages, or perhaps even both (e.g. someone who only knows VBscript). I imagine someone whodoesn't really care much about how either language is presented reading the article and at the end notthinking either "Wow, there was a lot of boring debate in that article" or "Wow, I was hoping the articlewould (give me good reasons I should be interested in one language or the other or both/help me choosea language for a project I need to do/give me some insight into why one language is used more often in aparticular industry) and it wasn't useful at all".

2. Rather than being neutral, the article as it stands now does have a point of view, albeit not overwhelmingeither a pro­Java or pro­C++ POV, but a somewhat strange POV that is probably an artifact of the wikiprocess, namely that "there are no real advantages or disadvantages of Java when compared to C++because everything is in the eye of the beholder". The pro­relativism bias that Wikipedia in generalsupports (or even creates) by its process is sometimes intractable (e.g. when the relativist position issomewhat popular and extends beyond the halls of Wikipedia), but I think on this topic it need not be aroadblock because nearly everyone is going to fall into one of three camps: 1. C++ is better, 2. Java isbetter, or 3. which language is better for a specific application depends on several factors.

Of course, let me know if you disagree. CyborgTosser (Only half the battle) 11:54, 25 January 2007 (UTC)

It sounds like you've given the matter a good deal of thought. I like your approach. How can I help? ­­UncleEd 14:27, 25 January 2007 (UTC)

The biggest improvement that I think could be made would be an introduction that summarizes some of thebigger differences, and some of the broad categories of differences, without avoiding pointing out if any arewidely recognized to be advantages or disadvantages (alternatively, strengths and weaknesses). In thisintroduction could be a mention of which applications are dominated by C++ and which by Java, along withsome of the widely recognized reasons for this split. The "advantages and disadvantages" topic doesn'tneed to be the focus of the introduction, but it should be present. The "Design aims" section is good, butdoesn't serve well as an introduction unless the article is to be primarily about the historical reasons for thedifferences. However, I think there is some advantage to waiting until after the "design aims" section to beginlisting many differences, and to make most of the claims about differences that are strengths and

weaknesses.

One thing that I would hope editors can keep in mind regarding the design aims section and how it relates tovarious concrete differences is that the designers of Java were able to learn from the experience (includingmistakes) of C++. There is no denying that C++ has some flaws (this is not specifically a Java perspective;look at the discussion around the next version of the C++ standard), and Java consciously avoided some ofthem. Of course, Java has its own unproven features that turned out to be of questionable value/quality(checked exceptions come to mind), and purposely left out some features that many C++ programmers findimportant, but these are separate issues that can be dealt with separately. With that in mind, it would beworthwhile for the design aims section to include well cited statements about what C++ flaws Java fixed (orpurportedly fixed), what new Java features are questionable, and what C++ features that Java is lacking arewidely missed by C++ programmers who have switched to Java.

An orthogonal concern is converting the bulleted lists into prose. I agree with the comments that the tone ofthis article currently is unencyclopedic, but I also think that due to the subject matter some bulleted lists willbe appropriate and necessary. One suggestion I would like to throw out there is that each section shouldstart with a couple paragraphs of prose, and that any discussion of differences as strengths or weaknessesbe kept in this part of the section. This would 1. keep the discussions of opposing viewpoints semi­general,rather than bogging down each difference with such discussion, and 2. make the bulleted lists in generalmore readable. In some cases, as with the design aims section, a table may be more appropriate to presentdifferences, and in other places contrasting code samples will do the trick. (A less informed reader might bewondering why a particular difference is often considered an advantage of Java, or of C++, and a codesample could show them instantly why one language lets you express a particular construct in a lessverbose/more intuitive/less error­prone way).

Finally, if someone wants to dig through the page history and find content that has been cut, I think thiswould be worthwhile. I have the feeling that a lot of content was cut by self­appointed NPOV police withoutgood discussion or careful consideration, and if there are any questions about what is appropriate toreinsert, the talk page should be used. Of course, most of this content could be reinserted over time bythose that originally contributed it, assuming the editing has cooled down somewhat since then.CyborgTosser (Only half the battle) 12:00, 29 January 2007 (UTC)

Preprocessing[edit]

One bullet in the miscellaneous section reads:

"C++ compilation features an additional textual preprocessing phase, while Java does not. Thus some usersadd a preprocessing phase to their build process for better support of conditional compilation."

Now, I am only really familiar with C (not so much C++), but I'm pretty sure that the two languages use thesame preprocessing techniques, and I know that all C++ files must be preprocessed. Any statement inC/C++ that begins with a pound sign/hash mark (#) is a preprocessor directive. Since almost every C/C++program at the very least includes some other file using the #include directive, it stands to reason that thepreprocessor must be run on every C/C++ source file­­if only to process the includes­­before it is passed tothe next stage.

The statement "some users add a preprocessing phase to their build process" doesn't make any sense,

because there is no way to "add a preprocessing phase" (it's always there).—Kbolino 07:15, 27 February2007 (UTC)

My guess is that what was meant here is that some Java users add a preprocessing phase to their buildprocess. I'm pretty sure that there are some code­gen tools out there for Java that work like the C/C++preprocessor (or it may be possible to use the C/C++ preprocessor on Java code, since preprocessing ismostly lexical and lexically Java is nearly identical to C/C++). Perhaps whoever added that bullet couldclarify. CyborgTosser (Only half the battle) 10:19, 27 February 2007 (UTC)

Please refer some System Programming book to get a clear understanding of what is a pre processor. It hasnothing to do with the house keeping tasks a build tool can do( I mean Ant). Don't comapre them. They aretotally different. Don't assume/imagine better to read. :­) Jayaram Ganapathy

Why the double standard here? What I imagined, and I still think is likely to be the case, is that the Cpreprocessor or some slight modification thereof, could be, and is sometimes, used for similar purposes onJava code. You seem to imply that:

If a preprocessor is used on Java code, it is mere "house keeping tasks"If a preprocessor is used on C/C++ code, it is wonderful and profound

By the way, I had to make a guess above because of ignorance of how some programmers might beenhancing their Java build process, not because of ignorance of the C preprocessor. CyborgTosser (Onlyhalf the battle) 09:34, 3 May 2007 (UTC)

Dear Friend, preprocessing which I discussed above is away from the build concept you are thinking. In C++you use utilities like make, nmake , clearmake etc.. In JAVA you have Ant, maven etc. A preprocessor issomething which creates source codes for compilation. Preprocessor is not used for house keeping tasks ofbuild where I think you imagine something like creating directory structure etc..(Jayaram Ganapathy)

Performance[edit]

Currently, the performance section has the statement "However critics claims that benchmarks are the onlyplace that Java can exceed or match C++'s performance, and in real­world applications Java is consistentlyslow. [5]". Unfortunately, the citation is to someone's personal web page, which is not only not peer­reviewed, but has questionable quality. I think that a rather dramatic statement like "in real­world applicationsJava is consistently slow" needs a reliable source, so I'm going to delete the sentence. SlitherM 18:35, 21March 2007 (UTC)

I would posit that the idea that Java byte code can possibly "exceed" the performance of native machinecode is impossible. At best, Java could operate as well as native code, but unless some magic is beingworked of which I am not aware, it cannot physically exceed the limitations imposed by the nativeenvironment any more than native code could.

It is possible, though, that under certain conditions, the performance of a complete Java program mightexceed that of a native program. But this would be very much dependent upon the environment, taking intoconsideration factors like compiler efficiency, optimization, architecture, sub­architecture, operating system,libraries, linking method, executable format, etc. Additionally, it would be difficult to determine if two

programs written in different languages and compiled in different ways are equivalent.

For these reasons, it is necessary to thoroughly examine and reconsider even the most reliable sources,and it may be impossible to achieve a truly objective assessment of Java's performance over theperformance of native programs at all.—Kbolino 01:35, 4 April 2007 (UTC)

The idea is not that bytecode is faster than native machine code, it is that:

better code can be generated by a compiler if it has access to the runtime milieu (that you mention)rather than making a priori assumptions

garbage collection compacts memory so that cache hits occur more frequently

the structured nature of Java code allows more aggressive optimization than freeform pointers andmemory access

—derrick 03:50, 8 April 2007 (UTC)

Hello Friends, I am the person who added the link to the page. I am very new to wiki editing. So there is avery high possibility of making mistakes in wiki standard. I apologise for the same. I use both the languagesJAVA and C++. What I would like you guys to think over is on the roots of computer science theories. ForJAVA you have one more level of interface between the OS and the executable program. So the load isalways more. On a benchmark exercise a person can produce results to favour one party. So please don'tget away with that. What ever performance a JAVA program delivers always a C++ program will deliver thesame or better. The logic and design of the programs plays a mojor role in the performance. The logic usedto write a JAVA program if you translate and say the C++ version is not fast it is wrong. You have to reworkthe same logic for appropriately using the features of C++, the specific compiler you use, the OS on whichyou deploy and the processor. PLEASE DON'T COMPARE THE ENTIRE JAVA PLATFORM WITH C++LANGUAGE, COMPARE JAVA PLATFORM WITH A C++ PLATFORM( C++, Compiler, OS and the processor).I am eagerly waiting for responses. :­) Jayaram Ganapathy

Jayaram, while I realize that the majority of benchmark results favorable to Java are from a relatively smallnumber of sources, you would be jumping to conclusions to assume that the benchmarks are artificiallychosen to make Java's performance look better. In addition, your comment about the extra level betweenapplication code and the operating system, while technically correct, is irrelevant here. If an application isrequired to go through the operating system for certain performance­intensive parts of the program, it isunlikely that Java could come out ahead. However, there are applications that rely on the operating systemvery little, and for which the perfomance­intensive parts of the program are all in application code. For theseprograms, how could the extra layer between the application and the OS guarantee that Java's performancewill be equal or worse, as you seem to imply here? This doesn't follow.

The choice of Java platform is very important in any performance assessments, as is the C++ compiler.However, the choice of OS is of significantly less importance in many of these benchmarks. In any case,many of the benchmarks are done with the same OS on identical machines. Perhaps there are OS choicesthat are more favorable to Java, but I don't think there is anything suspect about this. OSes have haddecades to become performance­friendly to C++ code, so I don't think that specific improvements that helpJava performance, if these are even an issue, are unfair to the benchmarks. They simply represent the factthat it took some time for OS support of Java to "catch up" after Java was introduced. CyborgTosser (Only

half the battle) 15:58, 17 April 2007 (UTC)

Hello Friend you said "If an application is required to go through the operating system for certainperformance­intensive parts of the program, it is unlikely that Java could come out ahead". You are going tothe hotspot optimization concept. If something is hotspot for JAVA same is hot spot for C++ too. So even inspecial case of hotspot codes where you see a performance benifit possibility, in the best case a JAVA canequal C++ which is determined by the CPUs capability. So your argument is irrelevent. Before making anassumption, just think if anything giving JAVA an edge is that not possible in C++? You will get answer tomost of your questions. You said " If an application is required to go through the operating system for certainperformance­intensive parts of the program, it is unlikely that Java could come out ahead. " An OS'sscheduling algorthm determines the performance. Can you get 100% CPU assigned to a process in all UNIXbased OSes? There is always a limit put by the OS how much attention a process can get at MAX. even ifCPU is available many OSes won't give. JAVA in a multiprocess model I can't see anything. So a JAVA appgetting 100% in windows box giving you a throughput may perform pathetically on Slightly older solarisversions :­). I have tasted this. What ever optimisation OS undergo to support JAVA, still it will not be able tocompete with C++ 1) JAVA is a language designed for easy programming. Its constructs are to preventmistakes by programmers where as C++ provides everthing to a programmer if he is good. 2) It isinterpreted 3) No control over Garbage collection 4) Operations on unsigned numbers give edge incryptography mainly which JAVA language doesn't support. 5) Type casting from one object to anotherobject if you knwo both objects have same kind of memory alighment and so memcopy will do in C++, butunfortumately I have to call getters and setters in JAVA. Above is a smal list of issues I tasted when I porteda big C++ apps architecture to JAVA version. I do coding in JAVA but many times I felt like coding with ahandicapped language. The truth is JAVA is surviving because industry lacks god programmers and peoplewho want to really learn things.(Jayaram Ganapathy)

Although a discussion page is probably not the place for deep technical discussions, I think statementsabove like "I would posit that the idea that Java byte code can possibly "exceed" the performance of nativemachine code is impossible" and "For JAVA you have one more level of interface between the OS and theexecutable program. So the load is always more." should be addressed, because they seem to keep re­occuring. These seem to make common, but incorrect assumptions about how Java and C++ are executed,and what influences performance. Briefly,

Both C++ and Java are compiled to native code. (In Java's case, by a JIT.)Although JITs impose a run­time cost, they have more information available to them than a standardcompiler, which can be used for optimizations.Garbage collection is much faster than malloc/freeGarbage collection has the effect of compacting memory, which reduces page faultsC++'s semantics cause it to be much harder to optimize, because there are many more potential aliases,and alias analysis is extremely hard

So, it is not hard to imagine that Java's performance can be as good or better than C++'s. Arguments thatJava HAS to have bad performance usually Incorrectly assume that Java is interpreted, or that malloc/free isfree while garbage collection is slow. SlitherM 20:59, 30 April 2007 (UTC)

JIT compilation occurs at runtime, resulting in a performance penalty. However, as the article states, it allows

further optimizations which could offset this penalty. Pcu123456789 01:59, 24 May 2007 (UTC)

Well everyone thinks JIT will improve performance and stress on the same point. Just imagine the facilitiesavailable on C++. A C++ program has a preprocessing stage. Here if because of size of a function if you arenot able to inline a code you can write functios in just macros. Here we are discussing about performanceonly. Please don't bring in maintainance and other jargons because here we compare performance. What isthere in JAVA? Macros in C/C++ save memory. A techy can understand how a #define PI 3.14 and constfloat PI = 3.14 will save memory. Performance also means space complexity :­). Now JIT. If you wantperformnace all good C++ developers will use target instruction compilation switch while compiling. So forgetabout JIT advantage. About GC please bring to your mind that the programmer doesn't have any controlover, when it will be freed. In C++ I have full control of memory. I can say when it is allocated and when it isdeallocated. If I find I need more performance because malloc/new is killing me, I can create memory poolsand won't hesitate to tune my app. Also note that a minimum JVM load into memory is required for a JAVAapplication. That is not coming for free. At the end of the day I have complete control on my application'sspace complexity and time complexity.(Jayaram Ganapathy)

"In contrast, C++ allows passing objects by value to functions, which can cause significant overhead in thecase that much memory must be copied or inefficient copy constructors must be called.": Negative. You can­ and generally, you used to ­ use references and pointers in implementation of algorithms. If you copysomething instead of passing reference then _it is not the same algorithm_. It is general practice to passreferences and constant references to functions and methods always when it is possible. Again: "... C++allows passing objects by value ..." does not mean "... C++ allows passing object only by value ...". I cannotsee the reason of this whole paragraph. And ­ also ­ it is not important how general these practices are. Thepossibility is there.

Java pass by value[edit]

Many java tutorials say everything in Java is passed by value. This is obviously true for native types.However, I view objects as being passed by reference: even though the bytes of the pointer are copied, thedata itself is referenced and not copied. In C, passing a pointer to another function would be consideredpass­by­value.

If you think I'm wrong, please explain on my talk page. Pcu123456789 01:57, 24 May 2007 (UTC)

I think it would be more accurate to say that primitives are passed by value and object references arepassed by value. 128.113.107.41 17:38, 26 May 2007 (UTC)

"References passed by value" is the definition of "pass by reference," though—Kbolino 18:23, 26 May 2007(UTC)

The Java Language Specification states explictly that Java always uses call­by­value. Period. SlitherM04:57, 27 May 2007 (UTC)

A page or section reference would be helpful.—Kbolino 19:13, 27 May 2007 (UTC)

Sections 15.12.4.2 and 15.12.4.5 describe how arguments are evaluated and the activation frame created.

For those who aren't comfortable reading language specification documents, in "The Java ProgrammingLanguage" by Arnold and Gosling, it says "All parameters to Java methods are `call by value'" (Section2.6.1, first edition, slight rewording of the same sentence in the second edition). SlitherM 23:08, 2 June 2007(UTC)

Here, here, and here all show that Java paramaters are passed by Value, not Reference. OverlordQ 07:01,25 June 2007 (UTC)

The problem is that "pass by value" is frequently interpreted (right or wrong) as "copy the whole objectgraph" http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_value which leads even this article tomisleading statements like: "Another discussion not often raised by Java programmers[weasel words] is thatJava is a pass­by­value language [1], which requires much more memory copy operations[citation needed]than pointers or mutable references". —Preceding unsigned comment added by Davebrink (talk • contribs) 01:29, 5 March 2009

(UTC)

Yes, I noticed that. The answer is that Java passes the reference by value, and therefore is as efficient aspassing a pointer by value, or passing an object by reference. I'll fix the mistake. ­­ Schapel (talk) 03:15, 5March 2009 (UTC)

I've corrected this twice again recently, and now have added a citation to The Java Tutorial published byOracle. If someone thinks that Java does something other than pass by value, we should discuss the matterhere. ­­ Schapel (talk) 16:13, 7 December 2010 (UTC)

Passing the reference to an object by value is essentially passing the object by reference. The formerwording is very unclear and should be avoided.1exec1 (talk) 20:54, 7 December 2010 (UTC)

I agree that it is very, very similar. In C++ you can pass a pointer by value, or you can pass an object byreference; these are similar because in both cases the address of the object is passed. But in Java, younever pass objects. You always pass references, and all passing is by value. So, even though you think thewording is unclear, passing references by value is in fact what Java is doing, and the Java LanguageSpecification, the official Java tutorial, and Sun's published Java FAQ all state what Java does in this way. ­­Schapel (talk) 22:21, 7 December 2010 (UTC)

"Pass a pointer by value"? "Passing references by value"? How else are you going to pass a pointer or areference? By reference to a reference? I think those phrases are almost meaningless tautologies, trying todraw distinctions that almost always do not exist or are irrelevant. So as 1exec1 says, they should beavoided. ­­Nigelj (talk) 12:01, 8 December 2010 (UTC)

These phrases are not meaningless tautologies. You can pass a pointer by value, by reference, by value­return, or by name. C++ can pass pointers by value or by reference. Java can pass references by value.The statements completely clearly explain how each language works, so is exactly the way the languagesshould be explained. I have a bachelors degree in Computer Science (graduated with highest honors), andam working on my masters degree in computer science at the University of Michigan. This is my profession,and I can verify that the official Java documentation explains things exactly the way they are. Java alwayspasses by value, both primitives and references. ­­ Schapel (talk) 12:17, 8 December 2010 (UTC)

Yes, in C++ you can pass a pointer by pointer or by ref, but very few people ever do, unless they want

incomprehensible or buggy code. The only examples I ever saw were deep in Microsoft's COM spec, to dowith IUnknown etc, and think how successful that would be if introduced afresh today. The point here isabout comparison with Java, which does not have pointers, so there's nothing to compare in those cases. InJava, objects (other than value types) are passed by reference, as they could be in C++, and no­one in C++would pass an object by reference to reference, or by pointer to reference, even if they could find a way todo it. The thing about programming is that there are thousands of things you could do, the art is know whichones not to do, so as to produce efficient, maintainable, understandable code. The same when explainingprogramming to others, e.g. in an encyclopedia. By all means let's say that there are pointers in C++ (andptr­to­ptr, and ref­to­ptr) and none of these in Java, but then in Java we just have value types and refs, bothof which are very similar to their equivalents in C++. ­­Nigelj (talk) 14:16, 8 December 2010 (UTC)

Java does have pointers; they are simply called references (hence the name NullPointerException). In Java,you cannot pass objects. In Java, you pass references. You pass them by value. It is very nearly the sameas passing a pointer by value in C++. Stating that Java always passes by value is very simple and is correct.Stating that Java passes objects by reference is incorrect, although I can see how some people might thinkof it that way because passing an object by reference is similar to (but not the same as) passing a pointerby value. In order to make sure that readers do not mistakenly think that Java passes objects by value, thisis clarified in the article by stating the references are passed by value. This is exactly how Java is defined towork in the Java Language Specification, is correct, and is as simple as can be. Also, we should clarify thatJava references are similar to C++ pointers but have a far more limited set of operations that can beperformed on them: there is no pointer arithmetic in Java and there are not "take the address of" and"dereference" operators as there are in C and C++. ­­ Schapel (talk) 16:37, 8 December 2010 (UTC)

You seem to misunderstand passing by reference in C++ a bit. In C++ reference is not the same as pointer.You can not pass a reference to an object by reference. You only can pass reference to it by value. So thedefinition of passing by reference is the same in C++ as is in Java. People call it just pass­by­reference. Asit's the same thing, why don't you adopt the simpler wording? The 'pass an object by reference which ispassed by value' is certainly confusing. 1exec1 (talk) 19:56, 8 December 2010 (UTC)

I'm not confused at all. A reference in C++ is certainly different from a pointer. A reference in Java is apointer. Passing a reference by value in Java is the same as passing a pointer by value in C++. Passing apointer by value and passing an object by reference are not the same thing. They are very similar, but notthe same. You are trying to argue that the statements Java passes reference by value and Java passesobjects by reference are equivalent, but they are not. In pass by reference, you pass the address of theargument. In pass by value, you pass the value of the argument. Java always uses pass by value. Youcannot use an object as an argument, only a primitive or a reference. This is specified in the Java LanguageSpecification. ­­ Schapel (talk) 13:54, 9 December 2010 (UTC)

A reference in Java is a reference in Java. It is not any C++ concept and not interchangeable with any C++concept. One similarity between references in C++ and references in Java is that we don't know (andshouldn't guess) how they are implemented, as there's nothing you can do about it, even if you find out (witha memory debugger or something). The way a reference is implemented in one implementation may or maynot be the same in a different implementation. That is why talking about 'passing a reference by value' ismeaningless in both languages ­ we don't know what the 'value' of a reference actually is in memory, and we

shouldn't care; it is a meaningless concept to a user of the language. (It may have some meaning to acompiler or runtime designer, but that's not the intended audience unless we are writing about a particularcompiler or JRE.) It is also equally meaningless to say 'a Java reference is a C++ pointer' or 'a Javareference is a C++ reference'. It is a separate concept ­ maybe somewhere between the two ­ but notcomparable in any way that refers to 'stack', 'heap', 'address', 'memory location', 'first byte' or any other low­level or hardware concept. The languages are different abstractions of actual computer hardware andmachine­code instructions; peeking behind, or guessing what's behind, the abstract scenery does not helpyou or the encyclopedia reader understand the language abstractions any better. ­­Nigelj (talk) 15:00, 9December 2010 (UTC)

I never said a reference in Java is a C++ pointer or interchangeable with a C++ pointer. I said it's a pointer. Apointer is a value that refers directly to another value in a computer program. In Java, a reference thatdirectly refers to an object, and is therefore a pointer. I have not spoken about how pointers areimplemented. You are correct that pointers could be implemented any number of different ways. One way isto implement pointers as machine code addresses. Another way is to implement them as integer indexesinto a large array. Regardless of how Java references are implemented, they are pointers. Passing areference by value is not meaningless at all! It explains exactly what is being passed and how it is beingpassed. This is why the Java Language Specification specifies Java's behavior in this way. Not only does'Java passes references by value' a completely meaningful and correct way to state Java's behavior, I knowof no other way to accurately and simply explain what Java does. Java certainly does not pass objects byreference. You cannot pass objects in Java and Java does not have pass by reference. Passing a pointer byvalue certainly is quite similar to passing an object by reference, but it is not the same. ­­ Schapel (talk)15:52, 9 December 2010 (UTC)

Let me give an example to understand how we can say Java passes by value, even though we may notknow how the value itself is implemented. When we pass an int in Java

a=3; foo(a);

Here a is an int. We do not need to know how ints are implemented in Java. We know that the value of a willbe passed to the method foo. If foo is defined as

void foo(int b) b=4

Then b gets the value of a (whatever that value is or however that value is implemented), just as if you hadassigned b=a. This is called pass by value. By changing the value of b in the foo method, we are onlychanging the local copy of the value. This has no effect on the value of a. We can state that Java passes intsby value, even though we do not know how those values are implemented!

Similarly, we can pass a reference:

a = new Integer(3); bar(a);

In this case, the reference is passed to bar. If bar is declared

void bar(Object b) b = new Integer(4)

Then b gets the value of a (whatever that value is or however that value is implemented, just as if you hadassigned b=a. This is called pass by value. By changing the value of b in the bar method, we are onlychanging the local copy of the value. This has no effect on the value of a. We can state that Java passesreferences by value, even though we do not know how those values are implemented!

Passing by reference is something different. In call­by­reference evaluation (also referred to as pass­by­reference), a function receives an implicit reference to the argument, rather than a copy of its value. We cansee that Java is receiving the value of the argument, not a reference to the argument, as defined in the JLS.­­ Schapel (talk) 16:14, 9 December 2010 (UTC)

I believe that if you dig deeply in the Java language specification, you'll find that the passing of references isimplementation defined. This means that it can be implemented in whatever way the developers selected.The method you describe can be one of the candidates for sure, it's implementation defined after all.However, I can assure that in reality it's definitely working differently than you describe. Functions make acopy of the object only if they modify it. This does not fit any of the standard pass­by­value or pass­by­reference definitions, since it's a bit more complex. Thus I agree with Nigelj, that C++ and Java conceptsshouldn't be treated as interchangeable. 1exec1 (talk) 23:06, 9 December 2010 (UTC)

No, functions never make a copy of the object they modify. When you pass a reference type to a method inJava, the method can change the object the reference refers to. This is just the same as in any languagewhen two pointers point to the same object. If you think Java is doing something other than pass by value,you horribly confused. ­­ Schapel (talk) 23:13, 9 December 2010 (UTC)

You can see a visual description of what's going on when you pass references to methods here. ­­ Schapel(talk) 23:18, 9 December 2010 (UTC)

Here's the description from the Core Java book I refer to in a citation. ­­ Schapel (talk) 02:03, 10 December2010 (UTC)

In case there's still any confusion about the matter, JLS section 15.12.4.2 states:

Now a new activation frame is created, containing the target reference (if any) and the argument values(if any), as well as enough space for the local variables and stack for the method to be invoked and anyother bookkeeping information that may be required by the implementation (stack pointer, programcounter, reference to previous activation frame, and the like). If there is not sufficient memory available tocreate such an activation frame, an StackOverflowError is thrown.The newly created activation frame becomes the current activation frame. The effect of this is to assignthe argument values to corresponding freshly created parameter variables of the method, and to makethe target reference available as this, if there is a target reference. Before each argument value isassigned to its corresponding parameter variable, it is subjected to method invocation conversion (§5.3),which includes any required value set conversion (§5.1.13).

Each argument value is assigned to its corresponding parameter variable. This is pass­by­value. ­­ Schapel(talk) 12:35, 10 December 2010 (UTC)

I don't know what you're trying to prove here, but we can't have mistruths in the article just to please you.You quoted books that said, "object references are passed by value" (your favourite phrase from above) and"A method call can pass [...] copies of references to objects". At the same time you added to the article,"reference types in Java [are] passed by value". That is not the same thing. Please don't write any morecode or lengthy explanations to justify it. Just accept that they are not the same thing. I'll go with that sillyphrase, used by both you and your book, "references are passed by value" (without asking again how else areference would possibly be passed) if you will please leave that part of the article alone in this compromise

state. For future reference, please remind yourself of WP:CONSENSUS, which is policy here. ­­Nigelj (talk)14:49, 10 December 2010 (UTC)

I didn't add "reference types in Java are passed by value". You added "Class types, interface types, andarray types are collectively called reference types in Java and passed by reference" which is completelywrong, and all I did was change "passed by reference" to "pass by value" which is correct. If you prefer thewording "object references are passed by value" that is also correct. As you say yourself, we can't havemistruths in the article just to please you ­­ all I did was correct your error. After that, I added two citationsthat allow any reader to verify that Java passes references by value. In any case, it looks like we've alreadyreached a consensus. We can discuss the matter further if anyone still has any concerns, but I think it's bestfor me to simply point to other people's explanations. Others explain in a variety of different ways, includingusing diagrams to clearly indicate what's going on, and many are professional authors and instructors. ­­Schapel (talk) 15:50, 10 December 2010 (UTC)

"neutrality" is counter to the point[edit]

Trying to avoid favoring one these languages over the others is to miss the point, or bury the lead. The one­sentence summary of this article should be that Java is an improvement upon C++; that it is more or less animproved version of C++. That's only to be expected since Java's design had the advantage of the lessonslearned from years of using C++ and other OO languages, and furthermore, C++ was handicapped by beingdesigned as an afterthought to a non­OO, low­level language. The programming language community wasable to learn a long list of lessons from C++ and and subsequent languages before the design of Java. Inshort, Java stands on C++'s shoulders.

Therefore, I suggest that the way to organize this page is NOT as a "C++ does this, Java does that" tablethat fails to show the progression from one to the other. Rather, it should be "C++ did this; Java changed it tothat, and here's why... ."

Even if folks don't want the article to say that Java is an advance over C++, it is still important for the articleto give the rationale behind the design choices. (And that doesn't mean giving, for each feature F, somescenarios S1..Sn where F is useful ­­ we can all agree that the existence of such scenarios does notconstitute, by itself, sufficient reason to include feature F in a particular language, right?)

MarkAb 00:50, 11 June 2007 (UTC)

Having used and studied both languages extensively I very much disagree. While Java does clean up somewarts in C++ (the static keyword comes to mind), Java is more of a dumped­down version of C++ than anadvance (very limited static polymorphism, little metaprogramming, no RAII, no unsigned arimetric, no const,no operator overloading and so on and on) plus a few extra features (e.g. platform independent bytecode,reflection) and a huge standard library (including 2 different GUI toolkits, encryption, 2D and 3D graphicsand much more) rather than a the very small and flexible library that C++ carries. It is much more fruitful toconsider Java a successor to COBOL and perhaps Pascal than C++. With this in mind, either language isbetter suited for different tasks. E.g., writing a somewhat efficient parser in Java is tedious or requires ancode generator, while boost::spirit demonstrates how easy it can be with the right language features. On theother hand, Java is much more suited to novice programmers and students, for exactly the same reasons. (Ireally wish I could come up with a reflection example that isn't silly, I must be tired). Esben 21:29, 11 August

2007 (UTC)

The "huge standard library" is precisely what makes java so productive. The implication that java is moresuited for novice programmers contradicts reality; there are plenty of smart, expert level programmersinvolved in large open source java­based projects. I think it's more precise to say that java is suited not onlyfor expert programmers, but for novice ones as well. One important goal which has been explicitly statedsomewhere is that a top goal for java is readability. In light of this, operator overloading is can be considereda negative (however a good ide can mitigate this problem). Java is smaller than C++. Yes, the java librariesare more extensive, but they are not visible if you don't use them; and the libraries that are most commonlyused, such as java.lang.Collections are relatively small. The point is it's a lot easier to learn thefundamentals of java than C++ (though both languages take a long time to master). As for reflection: it'sused everywhere in modern frameworks to great effect. —Preceding unsigned comment added by 128.107.248.220 (talk)

19:51, 15 September 2007 (UTC)

It is indeed well known that when Sun started working on Java they borrowed a lot from C++, as you said,and tried to remedy to various of its issues which were detrimental for productivity or security in specificapplication domains. I can certainly agree with you on that. However, Java is a higher­level language andshould be seen as such; it has advantages for application programming and productivity. This can be seenas an advancement for a particular type of applications. However it would be wrong to state that C++ is notbetter suited for other types of applications, i.e. those more closely tied with systems programming, or thosemore resource constrained. Java was never intended to generally deprecate C++ and such a belief would bea false impression. Similarily, C, a predecessor of C++ still remains widely used for certain domains such aslow­level kernel programming and is not about to die. 66.11.179.30 00:52, 18 June 2007 (UTC)

It is a myth that C++ fits as a low level language than High level language or JAVA is still a higher levellanguage than C++. JAVA is a language which sticks only to Object Oriented Model. C++ is a generalpurpose language which is suitable for a superset of programming models. If you compare C++ and JAVAlanguage features for OOP programming you can find a 1 to 1 mapping for the features. Actually in C++better OOP is possible. The key difference is JAVA don't allow non­OOP programming where as C++ allows.In that way JAVA defences the programmer but the cost is paid by real good programmers is the flexibility.

Note that Java is NOT a pure OO language. By allowing public static methods it allows writing functionsrelated to no object, like Math.sin(x). By allowing public static fields it effectively allows globals. Both arecounter to OO paradigms. Wikipedia lists Java as non­pure OO language. See the link.

Indeed, had Java been a pure object orient language would write x.sin(), possibly with "sin(x)" as syntaticsugar. Java is a multi­paradigm language moderate support for OO (very limited multiple inherited, not evenmixins), moderate support for procedural programming, very weak for functional (anonymous inline classes)and weak support for generic programming (Generics) Esben (talk) 12:37, 9 November 2009 (UTC)

As a language C++ needs lesser number of code to do a logic than JAVA. The productivity of JAVA comesfrom the IDE and the JSDK API. But the same library is ported to C++ the number of lines required will beless. Please note the multiple inheritance where code can be shared. There the common argument isdiamond of death. But a good designer will store the data smartly inside those classes which inherit from thecommon ancestor. So as language C++ is a superset of JAVA for me. As of today many open source librariesare available for C++ for multithreading, cryptography etc which are provided in JSDK. The only point is theyare not from a single vendor. May be a vendor like SUN can provide CPPSDK. C++ language is still evolving

and the version C++ 0X is awaited. If you compare JAVA EJB's with C++ equivalents, you have Tuxedo ATMIand CORBA from BEA systems. You have to pay for that, which is rock solid. Here the inout parameters areallowed. But in EJB if you want to return multiple objects then you have to pack them inside a vector. See itis still not matuared and the additional overload. If microsoft extends support to their COM/COM++/DCOM toUnix platforms that will literally be a revelution the industry. As you can see the clock speeds of CPU are notgetting increased. Now multi core systems are available but the scalability is not linear. The huge businesssystems which are built and runs on multiple geogrphic regions will impose strict time lines. Also the volumeof business increase is faster than the speed with which hardware speed increase Jayaram Ganapathy

Usage metrics[edit]

One thing that seems to be missing from this article is anything objectively measuring the relative marketshare and/or developer use of these two languages. Does anybody know of any studies that could be citedthat indicate whether Java is really replacing C++? 69.81.190.216 22:16, 18 June 2007 (UTC)

Yes, that would be interesting. I don't know if there are any statistics available and what they cover. Onepossibility to create such statistics is to mine data bases, basically searching for occurrences of java or C++code. My first idea was google code search, however the problem with google is that every time the numbervaries. A more realistic possibility would be to search academic articles for java and c++ the idea being tocount references from research to one of the two languages. This search could even allow chartingreferences by years. Ben / 12:49, 16 April 2009 (UTC)

Default parameters in Java[edit]

This turned up in the article today. "Starting with Java version 1.5 default values for functions is allowed." Ihave never heard this is possible, nor can I find anything that indicates that it can. So I will delete it in a fewdays unless a reference turns up. Esben (talk) 15:00, 19 December 2007 (UTC)

Generic programming: important parts missing[edit]

One of C++'s greatest features is generic programming, and is underdocumented here. The article makes itlook as if Java is just slightly less powerful in this regard, but actually it is VASTLY underpowered. Concepts ­the bread and butter of generic programming ­ can only be approximated with bound generics, which putsome serious constraints on the genericity (all generics parameters have to inherit from the bound type).Otherwise, things like:

class test < T > void foo(T t) t.do_something();

just won't work in a type­safe manner. Generic programming is also the area where operator overloading

TC

really starts to make sense. There are many examples available from Boost that could highlight this. ­­80.121.69.21 (talk) 10:46, 12 May 2008 (UTC)

Except that Concepts do not exist in the current version of C++. ­­Spoon! (talk) 11:47, 12 May 2008 (UTC)

Actually, the above would work today. You might be confusing the above with the Concept proposal forC++0x, which is meant for better compiler error messages. But concepts will not change what is possible todo safely. I would encourage a section where generics are compared to templates, but well down as it is anadvanced subject. Esben (talk) 09:40, 13 May 2008 (UTC)

It will "work" today if you somehow figure out how to use it correctly. There is nothing in the signature of theclass or function that tells you what kind of types T can be. When you use it with a type that doesn't have a"do_something" method, then it will blindly try to instantiate the template, and then fail halfway through,giving some convoluted message about a line inside the foo() method. That is about as "safe" as C macrosare "safe". Your code example above shows what is fundamentally "unsafe" about C++ templates. A "type­safe" language should not allow the above code, because its type declaration does not by itself guaranteethat it will work. In Java, that code would not be allowed, and the compiler would force you to bound the typeparameter in a way that makes sure it has such a method, which guarantees that it will work, completelyindependently of any other code. Any other code (which can be compiled separately) will have to follow thetype restrictions (if they do not follow it it gives an error on their end). That is the whole point of safety ­ therestrictions you place on it must convince the compiler that it will work. With Concepts in C++0x, you wouldbound the type T by some concept, which also achieves safety (which is important in its own right, not justfor better compiler messages); but this is not currently in C++. ­­Spoon! (talk) 10:43, 13 May 2008 (UTC)

First of, what you get from Java with those bound are available in C++, as a (boost) library. Secondly, thesafe typing is what is sometimes referred to as duck typing, which is considered by many to be just as safeas the hieraki. But I don't care to bicker with you, not here :) Esben (talk) 21:08, 19 May 2008 (UTC)

Reference to Compromised URL[edit]

Is it just me, or has this site been hacked?

It redirects to a fraudulent (viral) site:

Also, it seems the site's lease is going to expire soon anyways:

This will be posted in each of the following discussions at:http://en.wikipedia.org/wiki/Comparison_of_Java_and_C++ http://en.wikipedia.org/wiki/Aliasing_(computing)http://en.wikipedia.org/wiki/Restrict

76.64.33.246 (talk) 06:20, 2 January 2009 (UTC)

Organization?[edit]

I think this article's organization is unwieldy. • Some differences' placements are confusing. Why areunsigned arithmetic, operator overloading, and bounds checking considered "design goals"? Also, thedifference between semantics and syntax here is unclear. Shouldn't pointers be in syntax? And shouldn't

generics, templates, multiple inheritance, and multithreading support only be in language features?Differences like built­in support might be hard to place properly since they're language features in Java butlibrary features in C++. • Why does the article switch between bullet points and a table format? Was thisintentional? If not, I'd be happy to move the bullet points into a table format. If someone could explain thisorganization to me, then that would be great, and perhaps we could explain it in the intro. Otherwise, doesanyone object to me trying to reorganize it? I can place my suggestions for difference categorization herefirst. dmyersturnbull ⇒ talk 21:42, 22 May 2009 (UTC)

Some missing points[edit]

I think there are a few points that are either glossed over or not discussed thoroughly enough in this article.Here's a list of what I think could be covered better:

Java is a typesafe language. Many errors that can happen in C++ are either disallowed by Java'sbytecode verifier or trapped at runtime. Buffer overflow problems are just one example. On the otherhand, this can allow C++ to have better performance (reference).Java does not have the fragile binary interface problem problem that C++ does. This is glossed over bythe general term "binary compatibility", but the article doesn't seem to explain the repercussions of binarycompatibility or the lack of it.Java does not have separate header files as C++ does. This could be consider a strength or weakness,but some advantages are that makefile dependencies do not need to be updated in Java, and Javadoccomments allow documentation for classes and interfaces separate from the source code.C++ must be recompiled for each different platform.

I'm not trying to advocate Java over C++. I like both languages, and each has its strengths and weaknesses,but Java's main strengths seem to be mentioned only in passing in this article. ­­ Schapel (talk) 13:56, 13May 2011 (UTC)

Reading this article gave me quite a bit of pleasure, imagining how passionate some people can be aboutprogramming languages. The article itself is like a magnifying glass left on the top of a table filled with thehistory of programming languages ­ without the big picture it is hard to understand the details. There is nopoint in making a comparison between C++ and Java because the languages are not in competition, onlypeople can do this silliness. A more neutral way to present the whole topic is by language feature, say, howdo I declare objects, initialize them, pass them to methods, manage their allocation details and performancecharacteristics, etc. And not talk just about C++ and Java. Talk about SNOBOL, talk about Ada, talk aboutPROLOG. Stop living in the 21st century. Talk about the PDP/11, about Multics, about VAX/VMS, about thez80. Get serious. And take that object out of your pocket. 72.195.132.8 (talk) 01:12, 1 July 2012 (UTC)jcb

Bias and citing sources[edit]

I have added more info and deleted unneeded statements. There is huge bias on java. — Precedingunsigned comment added by 74.95.9.18 (talk) 01:58, 19 August 2012 (UTC)

The recent statements I have seen demonstrate a much higher bias for one particular side than what was inthe article before. The edits are also quite poor. Perhaps you should start slowly in Wikipedia, in a topic youare more familiar with. ­­ Schapel (talk) 02:05, 19 August 2012 (UTC)

You should also cite sources — content without citations may be removed if challenged. As you're doing that,you might realize why I suggested for you to start slowly and in an area you're more familiar with. ­­ Schapel(talk) 04:12, 19 August 2012 (UTC)

Stupid stuff in the performance section[edit]

It says "* All objects are allocated on the heap." Only to then backtrack a few sentences later to explain howthis is actually not true. The whole section is actually quite sad, and does not reflect the massive care thatmust have gone into it, judging from the size of the discussion page. 2620:0:1046:0:BE30:5BFF:FEE2:AFCF(talk) 19:35, 4 October 2012 (UTC)

remove bounds checking[edit]

It is said that "HotSpot can remove bounds checking". But as far as I understand it's only an optimizationtechnique which sometimes remove bound checking but not suppress it totally. Xavier Combelle (talk) 17:33,22 July 2013 (UTC)

Copyrights and patents[edit]

If we're going to say that "Various aspects of the language are covered by patents and copyrights held byOracle.", then we need a cite to back it up. Oracle_v._Google says the opposite, that provided they avoidcopying code, Google can implement Java (and all its APIs) even over Oracle's objections.http://www.javaworld.com/jw­10­1997/jw­10­lawsuit.html says "the complaint charges Microsoft withtrademark infringement, false advertising, breach of contract, unfair competition, interference withprospective economic advantage, and inducing breach of contract." That long list does not includecopyrights or patents. If we're wildly speculating, http://communities.mentor.com/community/cs/archives/cxx­abi­dev/msg01295.html is a list of possible patents over C++ implementations (not really from a reliablesource) and if GCC's C++ implementation violates any of them, so almost certainly does GCC's Javaimplementation, as they share an ABI... and IBM and Microsoft are the corporate names on those patents,not Oracle.­­Prosfilaes (talk) 08:24, 27 October 2013 (UTC)

Your last observation is interesting, but irrelevant here. The point is, Oracle may at any time assert it'sintellectual rights over various aspects of the Java language. Moreover, the verdict in the Oracle/Googlelawsuit does not in any way affect their right to sue even on the very same grounds laid out in that particularlawsuit, and however unlikely, they could still win such a lawsuit. And please note that a large part of thatlawsuit was simply an objection to Google duplicating the Java API of all things! Which means, of course,that the types of complaints filed in any future lawsuit are only limited by the creativity of Oracle's legaldepartment. Sebastian Garth (talk) 13:45, 27 October 2013 (UTC)

The point is, Microsoft may at any time assert its intellectual rights over various aspects of the Java and C++languages. So might IBM. So might any other huge patent holder. So might any designer of a pre­Java APIwho wanted to claim that Java's API is a copyright infringement of theirs. Looking at the results of the SCOtrial, it's not at all improbable that somewhere BSD­licensed code snuck its way into Oracle's Javaimplementation sans proper copyright notice. All of this might happen, and all of it is crystal­balling.

Yes, Oracle could sue on the same grounds. There's very few limitations on what people can sue on.

Speculating that they could win such a lawsuit is, again, crystal­balling, and again, Oracle is not unique inhaving a creative legal department.

Going back to the original statement, nobody has ever shown that a language can be covered by copyrights,and Oracle v. Google said they couldn't, or at least Java wasn't. Neither 6061520 or RE38104, the twopatents brought up in the Oracle trial, seem to be about Java as much as ways to implement Java. If wewant to make the claim under question, we should speak with specificity and with cites. (And we shouldavoid saying anything about Oracle's "intellectual rights" over Java. That's not a clear term. We shouldspeak specifically of copyrights, patents or trademarks, each of which has very different extents andlimitations.)­­Prosfilaes (talk) 17:40, 27 October 2013 (UTC)

I do understand your point but I still must disagree here. At any rate, I'm not going to press the issue anyfurther. Perhaps we'll revisit the discussion sometime in the future. For now, at least, we can leave thewording as it is. Sebastian Garth (talk) 19:36, 27 October 2013 (UTC)

Multiple Inheritance in Java[edit]

Guys/Gals,

Java does not support multiple inheritance. <­­­­ note that there's a period at the end of that sentence

I call your attention to: http://en.wikipedia.org/wiki/Inheritance_(object­oriented_programming)

Specifically, the fact that that article begins by stating that *implementation* is what is being inherited, NOTTO BE CONFUSED with subtyping:

Anyone who understands multiple inheritance and its problem(s) would know quite well that Java does notsupport multiple inheritance, and the creators of Java were very vocal and open about their reasons forexcluding multiple inheritance from the Java language spec.

Aquishix (talk) 12:19, 10 February 2014 (UTC)

Java Generics Inaccuracy[edit]

I believe there is an error in the generics vs. templates comparison section.

It says (as of 11/18/2015):

C++ Templates Java Generics

Templates can be specialized—a separate implementation could be provided fora particular template parameter.

Generics cannot bespecialized.

The below program shows an example of specializing a generic method for a specific template parameter.The "myCount" method is specialized for subclasses (inclusive) of Character. Is this not "providing aseparate implementation for a particular template parameter"? It seems to precisely match the definition of"Explicit template specialization" given here: Template (programming)#Explicit template specialization

import java.util.*;

public class Test

static <T> int myCount (Iterator<T> iterator, T val) int ret = 0; while (iterator.hasNext()) T entry = iterator.next(); if (entry.equals(val)) ++ret; return ret;

static <T extends Character> int myCount (Iterator<T> iterator, T val) System.out.println("weirdcount"); int ret = 0; while (iterator.hasNext()) T entry = iterator.next(); if (entry.equals(val)) ++ret; return ret*3;

public static void main (String[] args) List<Integer> nums = new ArrayList<>(Arrays.asList(1,2,3,3,3,4,5,2,1)); int count = myCount(nums.iterator(), 3); System.out.println(count);

List<Character> characters = new ArrayList<>(Arrays.asList('a','b','c','d','e','a','b')); int count2 = myCount(characters.iterator(), 'a'); System.out.println(count2);

Thanks, Vancan1ty (talk) 04:35, 19 November 2015 (UTC)

nested/inner classes[edit]

I think the article should also state that C++ nested classes differ from Java inner classes. C++ nestedclasses are kinda like a static class in Java and can not access fields in the outer class unless they are static(C++11)