You are on page 1of 6

The designers of Java based much of its syntax on the programming languages C

and C++ so that developers who know those languages would feel comfortable
using Java. However, Java should not be thought of as a revision of C++. There
are many critical differences between the two.
I

comparing java to C++


In fact, Java has integrated the best characteristics of several programming
languages. At the heart of Java are important tenets of program design and imple-
mentation that are fundamentally distinct from the approach of C++. However,
because of the similar syntax and the popularity of C++, comparisons between
these two languages are inevitable.
This appendix compares and contrasts Java and C++. It is a focused summary
of the primary similarities and differences, and is intended for developers with
experience using C++.

primitive types
There are several important differences between Java and C++ concerning prim-
itive data types and their use. Figure I.1 summarizes these differences.
Each variable in a Java program is either associated with a primitive type
(boolean, char, byte, short, int, long, float, or double) or is a reference to
an object. C++ has various primitive types, plus structs, unions, enums, arrays,
and pointers. C++ pointers might or might not refer to objects.
C++ structs are subsumed by Java objects. Java does not currently have an
enumerated type. Java designers thought the concept of unions to save memory
space was unnecessary. All Java primitives are signed and have a consistent size
no matter what platform is used, enhancing portability.

Java C++
Two type categories. Various type categories.

All nonprimitive types are objects. Separate types for structs, unions, enums, and arrays.

All numeric types are signed. Signed and unsigned numeric types.

All primitive types are a fixed size for all platforms. Primitive type size varies by platform.

16-bit Unicode characters. 8-bit ASCII characters.

Boolean data type primitive. No explicit boolean data type.

Conditions must be boolean expressions. Integer results are interpreted as boolean conditions.

Variables are automatically initialized. No automatic initialization of variables.

figure I.1 Java versus C++: Primitive types


716 APPENDIX I comparing java to C++

All Java implementations are based on the international Unicode character set,
whereas most C++ implementations use ASCII (American Standard Code for
Information Interchange). However, since ASCII is essentially a subset of
Unicode, this distinction is transparent for programmers used to using ASCII.
Unicode characters can be used in identifiers and literals in a Java program.
The boolean type in Java cannot be cast to any other type, and vice versa. Java
integers cannot be used as logical conditions. In C++, there is no built-in boolean
type, and integers are used for decision making.
No Java variables can contain garbage since they are set to a default value if
not initialized when created. However, Java compilers may warn against the use
of variables before their value has been explicitly set, whether intentional or not.

pointers and data structures


The absence of pointers in Java is a key difference between the two languages.
Figure I.2 summarizes the differences concerning the use of pointers, references,
and basic data structures.
Java uses references that provide the functionality and versatility of pointers
without their involved syntax and dangerous characteristics. Linked data struc-
tures are accomplished with references as you would with pointers in C++, but in
Java it is impossible to get a segmentation fault since a reference can only refer to
an object, not an arbitrary memory location.

Java C++
References, with no explicit pointer manipulation Pointers, with dereferencing (* or ->) and address (&)
and no pointer arithmetic. operators.

Array references are not translated to pointer arithmetic. Array references translate to pointer arithmetic.
Arrays automatically check index limits. No automatic array bounds checking.
Array lengths in multidimensional arrays can vary Array lengths in multidimensional arrays are all the
from one element to the next within one dimension. same size in a given dimension, fixed by the declaration.

Strings are objects. Strings are null-terminated character arrays.


Built-in string concatenation operator (+). String concatenation through a library function.
Use string concatenation operator for long string literals. Use line continuation (\) for long string literals.
No typedef. typedef to define types.

figure I.2 Java versus C++: Pointers, references, and basic data structures
APPENDIX I comparing java to C++ 717

Arrays and character strings are objects in Java, with appropriate support
methods. String concatenation is a built-in operation in the Java language, and
array bounds checking is automatic.
Multidimensional arrays in Java are actually arrays of arrays, in which each
array is a distinct object. Therefore, for example, each row in a two-dimensional
array can have a different number of elements. The length of each array is deter-
mined when each array object is instantiated, not when the initial declaration is
made.
Defining explicit type names is not necessary in either Java or C++ since the
declaration of larger structures, such as classes, implicitly defines a type name.
C++ includes the typedef operation for compatibility with C.

object-oriented programming
Both languages are object oriented but have significantly different philosophies
and techniques, as summarized in Fig. I.3.
C++ supports the object-oriented approach, but it doesn’t enforce it. Since C++
is essentially a superset of C, which is a procedural language, a program written
in C++ could be a hybrid mix of procedural and object-oriented techniques. Java
is a pure object-oriented language since it enforces the object-oriented approach.
As such, all functions in Java are methods, defined inside a class.
Several constructs and techniques that are a part of C++ are not included in
Java, mainly to keep the complexity of the language down. These include multi-
ple inheritance, parameterized types, and operator overloading. However, Java

Java C++
Pure object-oriented language. Hybrid between procedural and object-oriented.
All functions (methods) are part of a class. Can have stand-alone functions.
No multiple inheritance. Multiple inheritance.

Formal interface specifications. No formal interface specifications.


No parameterized type. Templates as a parameterized type.
No operator overloading. Operator overloading.

All methods (except final methods) are dynamically Virtual functions are dynamically bound.
bound.

figure I.3 Java versus C++: Object-oriented programming


718 APPENDIX I comparing java to C++

has the ability to define a formal interface specification, which gives the most
important characteristics of multiple inheritance to Java programs. Both lan-
guages support method overloading.
In C++, a method must be explicitly declared as virtual in order to allow run-
time dynamic binding of a method invocation to the appropriate definition. In
Java, all methods are handled consistently and are dynamically bound, except for
methods that are defined with the final modifier.

special characteristics
Some of the most highly promoted aspects of Java concern its relationship to the
Web and other special characteristics that distinguish it from C++. Figure I.4 sum-
marizes these differences.
Links to Java applets can be embedded in HTML documents, then retrieved
and executed using Web browsers. The Java API has specific support for network
communication.
A C++ programmer must perform explicit dynamic memory management,
releasing objects and other dynamically allocated data space when it is no longer
needed. In Java, garbage collection is automatic. An object in a Java program is
marked as a candidate for garbage collection after the last reference to it is
removed. Therefore Java does not support destructors, though there is the ability
to define a finalize method for other cleanup activity.
Java source code is compiled into bytecode, a low-level representation that is
not tied to any particular processor. The bytecode can then be executed on any
platform that has a Java interpreter. Java is therefore considered architecture
neutral.

Java C++
Specifically attuned to network and Web processing. No relationship to networks or the Web.

Automatic garbage collection. No automatic garbage collection.


Combination of compiled and interpreted. Compiled.

Slower execution when interpreted. Fast execution.

Architecture neutral. Architecture specific.


Supports multithreading. No multithreading.

Automatic generation of documentation in HTML No automatic documentation generation.


format.

figure I.4 Java versus C++: Special characteristics


APPENDIX I comparing java to C++ 719

When interpreted, Java programs have a slower execution speed; however,


because they are already compiled to a low-level representation, the interpre-
tation overhead is not problematic for many applications. C++ compilers are spe-
cific to each type of processor.
The Java language supports multiple threads of execution, with synchro-
nization mechanisms. It also has a special comment syntax, which can be used to
generate external documentation in HTML format about the contents and struc-
ture of a Java system.

general programming issues


Several specific differences between Java and C++ affect basic programming prac-
tices. Figure I.5 summarizes these differences.
Java does not support variable-length parameter lists for methods. It also does
not allow parameters to be given a default value, which essentially makes them
optional during invocation.

Java C++
Method bodies must be defined inside the class to Method bodies must be defined inside the class to
which they belong. which they belong.

No forward referencing required. Explicit forward referencing required.

No preprocessor. Heavy reliance on preprocessor.

No comma operator. Comma operator.

No variable-length parameter lists. Variable-length parameter lists.

No optional method parameters. Optional function parameters.

No const reference parameters. const reference parameters.

No goto statement. goto statement.

Labels on break and continue. No labels on break and continue.

Command-line arguments do not include the Command-line arguments do not include the
program name. program name.

Main method cannot return a value. Main function can return a value.

No global variables. Global variables.

Character escape sequences can appear in a program. Character escape sequences must appear in a string
or character literal.

Cannot mask identifiers through scope. Can mask identifiers through scope.

figure I.5 Java versus C++: General programming issues


720 APPENDIX I comparing java to C++

Java has no comma operator, though its for loop syntactically allows multiple
initializations and increments using the comma symbol. Java does not allow vari-
ables to be declared with global scope. In C++, you must use an explicit forward
reference (function prototype) to inform the compiler that a function will be used
prior to its definition, but in Java no such forward referencing is needed.
Java does not rely on a preprocessor. Most of the functionality that is provided
by the C++ preprocessor is defined in the Java language itself.
There is no goto statement in Java, though goto is included in the Java
reserved words. Java allows statements to be labeled, and the break and
continue statements can jump to specific labeled points in the code.
Finally, in Java, an identifier name cannot be masked by another declaration
and scope, as it can in C++. For example, the following code segment is valid in
C++ but causes a compile-time error in Java:

{
int x = 12;
{
int x = 25; // same variable name with
// distinct memory space
}
}

You might also like