At a glance, Java codes looks very similar to that
of C /C++, but as you start to compare them many differences soon
Here we discuss here the differences at the syntax
level. In Chapter 3: Supplements
we discuss the differences between Java and C++ at the higher object-oriented
level, such as class descriptions, methods, etc.
Unlike C/C++, standard Java has:
- No preprocessor or header files
- all Java code occurs within the class structure. Java methods
can be invoked (i.e. called) before they are defined so
they are not declared as in C/C++.
- No global variables - all
variables belong to a particular class. Java static class variables
can serve the same purpose as global variables but without the
collisions in namespace that occur in C/C++.
- Automatic garbage collection
- the JVM manages memory allocation and removal. The programmer
does not need to allocate memory or delete data directly. Memory
leaks (loss of free memory space) can still occur in Java
but they are much less of a problem.
- No pointers - Java does
not allow direct access to memory addresses. This removes a huge
source of errors and security problems.
- Type safety - all data must
have an explicit type and you cannot arbitrarily cast one type
to another. For example, you cannot cast a reference to a primitive
type as can in C where a pointer can be cast to an integer to
obtain a memory address value.
- Strict lengths for primitive types
- all of the integer types have a fixed number of bits (in C/C++
these can vary with platform) Floating point exponents, though,
can vary with the platform unless the strictfp
modifier is used.
- Unrestricted location of variable declarations
- you can define local variables in a method at the place where
you use them rather than only at the beginning.
- No goto
statement - though long discouraged by computer science
teachers, the infamous goto
spaghetti code maker is nevertheless available in C/C++.
- No typedef
- no way is provided in Java to give alias names to types or classes.
- No union
- memory can only have a single type. No overlapping types as
in a union.
- No struct
- replaced by class in Java.
- No bit fields - cannot specified
the number of bits spanned by a field.
- No enum
- can use object constants instead.
- No comma operator - while
Java allows a comma in the for
i=0, j=2; i<5; i++, j++)...
this is not the same as the comma operator in C that evaluates
two expressions and returns the value of the one to the right
of the comma.
& Web Resources
Latest update: Dec.11.2003