Comparison Of Java And C++.

Design Aims.


The differences between the C++ and Java programming languages 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 C programming language. To this procedural programming language designed for efficient execution, C++ has added support for statically typed object-oriented programming, exception handling, lifetime-based resource management (RAII), generic programming, and template metaprogramming, in particular. It also added a standard library which includes generic containers and algorithms (STL), as well as many other general purpose facilities.

Java is a general-purpose, concurrent, class-based, object-oriented computer programming language that is specifically designed to have as few implementation dependencies as possible. It relies on a Java virtual machine to be secure and highly portable. It is bundled with an extensive library designed to provide a complete abstraction of the underlying platform. Java is a statically typed object-oriented language that uses similar (but incompatible) syntax to C++. 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
Extension of C with object-oriented programming, still able to run C code.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 programming, object-oriented programming,generic programming, and template metaprogramming. Favors a mix of paradigms.Allows procedural programming, functional programming (since Java 8) and generic programming (since Java 5), but strongly encourages the object-oriented programming paradigm. Includes support for the creation of scripting languages.
Runs as native executable machine code for the target instruction set(s).Runs in a virtual machine.
Provides object types and type names. Allows reflection through RTTI.Is reflective, allowing metaprogramming and dynamic code generation at runtime.
Has multiple binary compatibility standards (commonly Microsoft (for MSVC compiler) and Itanium/GNU (for virtually all other compilers)).Has a single, OS- and compiler-independent binary compatibility standard.
Optional automated bounds checking (e.g., the at() method in vector and string containers).All operations are required to be Bound-checked by all compliant distributions of Java.HotSpot can remove bounds checking.
Supports native unsigned arithmetic.No native support for unsigned arithmetic.
Standardized minimum limits for all numerical types, but the actual sizes are implementation-defined. Standardized types are available through the standard library<cstdint>.Standardized limits and sizes of all primitive types on all platforms.
Pointers, references, and pass-by-value are supported for all types (primitive or user-defined).All types (primitive types and reference types) are always passed by value.
Memory management can be done manually through new / delete, automatically by scope, or by smart pointers. Supports deterministic destruction of objects. Garbage collection ABI standardized in C++11, though compilers are not required to implement garbage collection.Automatic garbage collection. Supports a non-deterministic finalize() method whose use is not recommended.
Resource management can be done manually or by automatic lifetime-based resource management (RAII).Resource management must be done manually, or automatically via finalizers, though this is generally discouraged. Has try-with-resources for automatic scope-based resource management (version 7 onwards).
Supports classes, structs (POD-types), and unions, and can allocate them on the heap or the stack.Classes are allocated on the heap. Java SE 6 optimizes with escape analysis to allocate some objects on the stack.
Allows explicitly overriding types as well as some implicit narrowing conversions (for compatibility with C).Rigid type safety except for widening conversions.
The C++ Standard Library was designed to have a limited scope and functionality but includes language support, diagnostics, general utilities, strings, locales, containers, algorithms, iterators, numerics, input/output, random number generators, regular expression parsing, threading facilities, type traits (for static type introspection) and Standard C Library. The Boost library offers more functionality including network I/O.
A rich amount of third-party libraries exist for GUI and other functionalities like: ACE,Crypto++, various XMPP Instant Messaging (IM) libraries, OpenLDAP, 
The standard library has grown with each release. By version 1.6, the library included support for locales, logging, containers and iterators, algorithms, GUI programming (but not using the system GUI), graphics, multi-threading, networking, platform security, introspection, dynamic class loading, blocking and non-blocking I/O. It provided interfaces or support classes for XML, XSLT, MIDI, database connectivity, naming services (e.g. LDAP), cryptography, security services (e.g. Kerberos), print services, and web services. SWT offers an abstraction for platform-specific GUIs.
Operator overloading for most operators. Preserving meaning (semantics) is highly recommended.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 inheritance via the Interfaces construct, which is equivalent to a C++ class composed of abstract methods.
Compile-time templates. Allows for Turing complete meta-programming.Generics are used to achieve basic type-parametrization, but they do not translate from source code to byte code due to the use of type erasure by the compiler.
Function pointers, function objects, lambdas (in C++11), and interfaces.References to functions achieved via the reflection API. OOP idioms using Interfaces, such as Adapter, Observer, and Listener are generally preferred over direct references to methods.
No standard inline documentation mechanism. Third-party software (e.g. Doxygen) exists.Extensive Javadoc documentation standard on all system classes and methods.
const keyword for defining immutable variables and member functions that do not change the object. Const-ness is propagated as a means to enforce, at compile-time, correctness of the code with respect to mutability of objects.final provides a version of const, equivalent to type* const pointers for objects and const for primitive types. Immutability of object members achieved through read-only interfaces and object encapsulation.
Supports the goto statement.Supports labels with loops and statement blocks.
Source code can be written to be platform-independent (can be compiled for Windows,BSD, Linux, Mac OS X, Solaris, etc., without modification) and written to take advantage of platform-specific features. Typically compiled into native machine code, must be re-compiled for each target platform.Compiled into byte code for the JVM. Byte code is dependent on the Java platform, but is typically independent of operating system specific features.

Language Features.

Syntax.



  • Java syntax has a context-free grammar that can be parsed by a simple LALR parser. Parsing C++ is more complicated. For example, Foo<1>(3); is a sequence of comparisons if Foo is a variable, but creates an object if Foo is the name of a class template.
  • C++ allows namespace-level constants, variables, and functions. In Java, such entities must belong to some given type, and therefore must be defined inside a type definition, either a class or an interface.
  • In C++, objects are values, while in Java they are not. C++ uses value semantics by default, while Java always uses reference semantics. To opt for reference semantics in C++, either a pointer or a reference can be used.
  • 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 variables
    // are declared as private to
    // enforce encapsulation
    //initialized to 0 by default
    public Foo() { // Constructor for Foo
    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 a{args};
    Foo a;
    // declares a to be a reference to a Foo object
    a = new Foo();
    // initializes 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.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.x = 5; // modifies the object referenced by a
    
    cout << b.x << endl;
    // outputs 0, because b is
    // a different object than a
    System.out.println(b.x);
    // outputs 0, because b points to
    // a different object 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
    cout << d->x << 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 code from modifying it. Functions and methods can also guarantee that they will not modify the object pointed to by a pointer by using the "const" keyword. This enforces const-correctness.
  • In Java, for the most part, const-correctness must rely on the semantics of the class' interface, i.e., it isn't strongly enforced, except for public data members that are labeledfinal.



SHARE THIS

Author:

Previous Post
Next Post