|
|
|
Java and C++ Similarities and Differences |
|
This is breif similarities and differences in Java and C++. There is detailed article
below this. you can read that for comprehensive studies. |
|
C++ |
JAVA |
|
const |
Final |
|
public and private sections, started by the keywords public and private |
each individual item must be tagged with public or private. |
|
There is a semicolon at the end of the class |
|
|
object variables hold values |
object references |
|
new operator is never used when constructing objects in C++ |
|
|
C++ supports instance methods and static functions of classes, but it also permits
functions that are not a part of any class. Such functions are called global functions |
In Java, every function must be an instance method or a static function of a class. |
|
In particular, every C++ program starts with the global function main |
|
|
By convention, the return value of main is zero if the program completed succesfully,
a non-zero integer otherwise |
|
|
object variables hold object values |
an object variable only is a reference to an object value that is stored elsewhere |
|
In C++, a variable that can refer to an object is called a pointer |
|
You must apply the * operator to access the object to which a pointer points
(*p).setSalary(91000); The parentheses are necessary because the . operator has
a higher precedence than the * operator.
|
|
|
responsibility of the programmer to manage memory, If you forget to delete an object,
then you can eventually exhaust all memory. This is called a memory leak |
Java has a garbage collector that automatically reclaims all objects that are no
longer needed. |
|
you use : public |
extends |
|
By default, functions are not dynamically bound in C++ |
|
|
you must call the superclass constructor outside the body of the subclass constructor |
As in Java, there is special syntax for a constructor to invoke the constructor
of the superclass. Java uses the keyword super |
|
you use the name of the superclass and the ::operator instead |
super keyword when a subclass method calls the superclass method |
|
C++ has control over hardware |
Java has absolutely no control over hardware |
|
C++ has pointeres |
Java has no pointers |
|
|
Java's class declaration syntax is alot easier than C++ |
|
|
Java has no header-files |
|
|
Multithreaded |
|
Preprocessor |
no Preprocessor |
|
classes, structures, and unions |
Only classes |
|
Multiple inheritance is a feature of C++ |
Multiple inheritance by using interfaces in Java |
|
primitive data members of a class cannot be initialized in the class definition
in C++. |
you can initialize primitive data members in the class definition,You can also initialize
them in the constructor. If you fail to initialize them, they will be initialized
to zero |
|
|
no destructors in Java, garbage collector |
|
|
no virtual keyword in Java |
|
|
Java does not support default arguments |
|
|
Java has no templates or other implementation of parameterized types |
|
|
Similarities Between C++ and Java |
|
We will progress through the similarities between the C++ and Java languages by
discussing the basics and then moving on to the more advanced features of the Java
language
|
|
Comments |
|
The Java programming language supports comment characters of C++: both the block
sequence /* */ and the single line comment pair // characters are supported by Java.
In Java, comments have an added benefit. By using special character tokens in your
source files and the javadoc utility program, you can produce documentation for
your source files. A documenting comment must begin with the character sequence
/** and must end with the sequence */. Special document keywords, preceded with
the @ symbol, are used to specify comment sections. You can also imbed HTML tags
within the document block. The following example demonstrates the document commenting
feature:
/**
* sleepMethod - sleeps a specified number of milliseconds
* @param long millis - milliseconds to sleep
* @return void * @exception IOException
* @author: Some Java Developer
* @version: 1.0 */
public void sleepMethod( ) thows IOException
{
//...
}
You execute the javadoc utility program, specifying one or more source
files to parse. The javadoc utility outputs HTML files containing documentation
for the parsed source files. This documentation can then be viewed using a Web browser.
|
|
Data Types |
|
Java divides data types into two distinct categories: primitive types and reference
types. Java has no struct or union types—these are replaced by classes. More important
to C++ programmers, Java has no pointers. All nonprimitive types are passed by reference;
Java takes care of the garbage collection (cleaning up memory) for you
|
|
Primitives Data Types |
|
The eight primitive data types supported by Java are byte, boolean, char, short,
int,
long, float, and double.Below lists the primitive data types
and their respective sizes. |
|
Type |
Size |
|
byte |
1 byte (signed 8-bit) |
|
boolean |
1 byte (signed 8-bit) |
|
char |
2 bytes Unicode (signed 16-bit Unicode) |
|
short |
2 bytes (signed 16-bit integer) |
|
int |
4 bytes (signed 32-bit integer) |
|
long |
8 bytes (signed 64-bit integer) |
|
float |
4 bytes (signed 32-bit integer) |
|
double |
8 bytes (signed 64-bit integer) |
|
|
Each Java primitive data type is classified into one of two categories, either numeric or
Boolean. The numeric category consists of the integral and floating-point
types byte,
short, int, long, char,
float, and
double. The Boolean category, of course, consists solely of the boolean
data type. char is a special primitive
type for character representation. Each Java data type maintains its size for every
platform supported. This helps to maintain Java’s platform independence. Note that
Java does not support unsigned types. The data types listed in above are considered
native data types. Java also offers class types, specifically Integer, Long, and
Character (note the capitalization). The native types are smaller and more efficient
than the class types, but are passed into and out of methods by value rather than
by reference |
|
The char Data Type
|
|
A character in Java is represented using two bytes and employs the international
Unicode scheme. Java therefore allows you to represent most of the international
character sets. Although the char data type provides support for various international
character sets, you cannot simply convert and display characters from, say, English
to Japanese. The support for Unicode must also be provided by the operating system. |
|
The boolean Data Type |
|
The boolean data type supported by Java is a true Boolean, not just an integral
type. The only two values that can be stored to and retrieved from a boolean are
true and false. The result of a conditional expression must be Boolean and not integral.
The following code snippet shows legal and illegal uses of the boolean type:
boolean result = false ;
int value = result ;
this. value = 1 ;
result = value ;
result = (boolean)value ;
|
|
The byte Data Type |
|
Java’s byte data type is comparable to the C++ char data type, but is not a direct
replacement. The Java byte is stored as an 8-bit signed integer and maintains a
range of values from –128 through 127. Some C++ programmers new to Java want to
use an array of byte to simulate C++ (and C) strings. Java does not support this
use of byte; the Java library provides a String class for this purpose
|
|
Reference Data Types |
The three types of references are class, interface, and array. A reference in Java
is very similar to a reference in C++: It is a variable that is bound to some object
other than itself. Let’s look at an example in C++:
int value = 5 ;
int & rv = value ;
In this example, rv actually refers to value. You can access the contents
to which rv refers, namely the contents of value.
Something similar occurs in Java. The following is an example of a reference in
Java. (Some Java programmers refer to references as handles.)
String str = new String( ) ;
System.out.println( “str is: “ + str.length()
+ “ characters long.”);
In C++, the new operator returns a pointer. In Java, the new operator returns
a reference to the object on the heap—and this is the only access you ever have
to that object. You do not have to worry about freeing the memory—Java takes care
of that for you. Also, this is the only way to create an object in Java; all objects
are dynamically allocated, and you always use the reference to the object, rather
than the object itself.
|
|
Operators |
|
All the usual arithmetic, relational, and conditional operators are available in
C++ are also found in Java. The + operator, in addition to providing arithmetic
operations, is used for string concatenation.
You’ll be happy to discover that the bitwise operators are also available. Java
adds a new one to the mix: the (unsigned) triple-right-shift. The triple-right-shift,
>>>, is a logical operator used to shift the bits of an integral value
to the right. The supplied operand determines the number of bits to shift. When
shifting the bits, zeros are inserted on the left side. The following example shows
how to divide a number by 2 using the tripleright- shift operator:
import java.io.* ;
public class Test
{
public static void main( String args[] )
{
int anInt = 10 ;
System.out.println( “anInt before is:” + anInt ) ;
anInt = anInt >>> 1 ;
System.out.println( “anInt after is:” + anInt ) ;
}
}
The output from this application is shown here:
anInt before is: 10
anInt after is: 5
|
|
Control Flow Statements |
|
All the statements used to control the flow of a C++ application are also provided
for in Java. For decision making, you have the if-else and switch-case statements;
for looping, you have for, while, and do-while; for exception handling, there is
try-catchfinally and throw; and finally, in the miscellaneous category, you have
break, continue, label:, and return. Exception handling is discussed later in this
chapter. The keyword goto is reserved, but is not supported by the Java language.
You should also be aware that the result of a control flow expression must be Boolean
|
|
Differences Between C++ and Java |
|
Now that we have briefly summarized some of the similarities between Java and C++,
let’s move on to some of the differences between the two languages |
|
Memory Management |
|
The Java garbage collector automatically reclaims memory allocated for an object
once all references to that object have been released. Take note that all references
to an object must be redirected. When the garbage collector runs, it searches out
all objects that are no longer being referred to and reclaims the memory |
|
No Pointers |
|
There are no pointers in Java. Because of this, some esoteric techniques are difficult,
but programming without pointers with the built-in garbage collection of Java generally
proves to be quicker and more robust than having to handle the memory management
problems involved in using pointers in C++. |
|
No Preprocessor |
|
Java does not use include files, #define directives, or typedefs and so has no preprocessor. |
|
No Destructor |
Java uses the facilities of a garbage collector to reclaim memory consumed by objects
that are no longer referenced. Although Java offers the new keyword to allocate
objects at runtime, there is no corresponding delete keyword as is found in C++.
Quite simply, all you need to do in Java is allocate an object with new; you do
not have to worry about explicitly destroying the object.
Java does offer the finalize() method, but finalize() is not quite the same as a
destructor. The garbage collector will call the finalize() method for an object
that has been determined to be garbage (no longer required). You will never know
when finalize() will run; that is not under your direct control.
Any resources managed by an object should be released at the point that object goes
out of scope. If a class owns resources that will have to be released, you should
define a member function to act as a destructor. You could call this member function
cleanup() or some such name. This is rarely needed as the built-in garbage collection
should be sufficient in most cases.
You should also get in the habit of setting a reference to an object to NULL when
you are done with the object. This gives a hint to the garbage collector that you
are finished with that particular object. This, of course, does not mean that the
garbage collector will run and reclaim the object; there may be other references
lingering about that refer to the same object. The following example demonstrates
our intention of releasing some object:
InterestingObject yoohoo = new InterestingObject( ) ;
yoohoo.yodel( ) ; yoohoo.cleanup( ) ;
yoohoo = null ;
You should be in the habit of performing this “closure” when working with objects.
Doing so assists the garbage collector in reclaiming memory as quickly and efficiently
as possible.
|
|
Access Specifiers |
An access specifier allows you to control the visibility of member functions and
attributes. Java offers the same access keywords C++ does, but with a twist: They
are part of the declaration syntax. In other words, you explicitly specify the visibility
of each individual class and class member. In C++, you specify access to members
with block scope. In Java, you end up typing more, but you have finer control over
the visibility (and placement) of individual members. To clarify access control,
the following example demonstrates how visibility is specified in
C++. class Goofy
{
public:
Goofy ( ) ;
~Goofy( ) ;
int getValue( ) ;
protected:
int negotiateValue( const int valueIn );
private:
bool verifyValue( const int valueIn ) ;
int value ;
} ;
To contrast the preceding C++ example, here is the same declaration in Java:
public class Goofy
{
public Goofy( )
{
/* ... */
}
public int getValue( )
{
return value ;
}
protected int negotiateValue( int valueIn )
{
return value ;
}
private boolean verifyValue( int valueIn )
{
return true ;
}
private int value ;
// … and so on and so forth
}
If you do not explicitly specify access, the member defaults to package. Package
access specifies that the member is accessible to other classes within the same
package. |
|
Method Parameters |
|
Another distinction between Java and C++ is that the const keyword is not applied
to method parameters. The const keyword (or some variation of it) is not required
in Java because Java uses pass-by-value for primitive type arguments to a method.
This means that you cannot change the value of the object argument. Within the member
function, you operate on a copy of the original object, not the actual object referred
to by the argument. In Java, if you pass an object (nonprimitive), a reference is
passed, not the object itself. You cannot change the reference passed in, but you
can access the actual object’s public methods and instance variables. T
Example:
import java.io.* ;
public class Goofy
{
public Goofy( )
{
/* ... */
}
public void doubleArg( int value )
{
value *= 2 ;
}
static public void main( String arg[] )
{
int theValue = 5 ;
System.out.println(“1. theValue is: “ + theValue
) ;
Goofy g = new Goofy( ) ;
g.doubleArg( theValue ) ;
System.out.println(“2. theValue is: “ + theValue
) ;
}
}
The output of this application is as follows:
1. theValue is: 5
2. theValue is: 5
This code demonstrates that the member function doubleArg() merely gets a copy of,
not a reference to, the original object theValue. If you pass a reference to the
member function, you actually operate on the referenced-to object.
import java.io.* ;
public class Int
{ // this class will need to be in it’s own file
public Int() { /* ... */ }
public int intValue = 5 ;
}
public class Goofy
{
public Goofy( ) { /* ... */ }
public void doubleArg( Int value ) { value.intValue *= 2 ; }
static public void main( String arg[] )
{
Int theValue = new Int( ) ;
System.out.println(“1. theValue is: “ + theValue.intValue ) ;
Goofy g = new Goofy( ) ;
g.doubleArg( theValue ) ;
System.out.println(“2. theValue is: “ + theValue.intValue ) ;
}
}
The output from this application is shown here:
1. theValue is: 5
2. theValue is: 10
One last note in closing: Arrays are first-class objects in Java. In the previous
example, if
theValue was an array of int, then the member function doubleArg() would change
the
actual passed-to argument.
|
|
External Functions
|
|
In Java, every function must be a member of a class. There are no global functions.
|
|
Enumerations
|
|
In C++, the enum keyword is available to specify an entity that contains enumerated
values.
Java does not offer the enum keyword, but you can simulate enum by creating a class
that only contains instance variables that are static final. By declaring the instance
variables as static final, you are, in effect, defining the variables as constant.
The following
example demonstrates a simulated enum in Java:
public class DrawingColor
{
public static final int red = 1;
public static final int yellow = 2;
public static final int green = 3;
}
//...
pen.color( DrawingColor.red ) ;
//...
There is a drawback to the C++ (and C) enum: Each member of an enum must have a
unique name with respect to other enums and variables. Consider the previous example’s
equivalent declaration in C++. If you had an additional enum named WindowColor that
contained member variables named red, yellow, and green, you would have a name
clash. This sort of problem does not happen in Java
|
|
Strings
|
In Java, there is no equivalent representation of a string as there is in C++. Strings
in C++, of course, are represented as an array of char (terminated by the NULL character).
In Java, the immutable String object is available to represent strings and is considered
a first-class object. In Java, you can create quoted (literal) strings as you can
in C++, but the compiler actually converts this representation to a String object.
For example:
String str = “This is a quoted string” ;
The Java compiler creates a String object for the quoted string and then assigns
it to str. String is immutable; you cannot modify the contents of a String object.
If you require a mutable string, Java offers the StringBuffer class. Although Java
does not offer operator overloading, the String class does offer the + operator
for the concatenation of Strings. Remember that String objects are immutable, so
you cannot concatenate a String onto another String; the result of the concatenation
must be a new String. The String class also offers the member function length()
to obtain the length of a String object.
|
|
Arrays
|
|
Arrays in Java are considered first-class objects. You access the elements of a
Java array in the same way you access the elements of a C++ array: You use array
indexing. Java offers runtime array-bounds checking. Java arrays contain an instance
variable named length that holds the number of elements (depending on the context)
of the named array. The placement of the brackets can be on the left or right side
of the array name. In Java, you cannot specify the array dimension at the point
of declaration as you can in C++. Arrays in Java must be allocated using new. Let’s
look at an example of declaring
and using a Java array:
#1: int array1[] ; // brackets on right
#2: int [] array2 ; // brackets on left, both are okay
#3: int array3[10] ; // ERROR, can’t specify dimension!
#4: Object [] array3 = new Object[10] ;
#5: array1 = new int[10] ;
#6: array2 = new int[10] ;
#7: array1[1] = 5 ;
#8: array1[12] = 5 ; // ERROR, beyond boundaries
#9: for( int i = 0; i < array1.length; i++ )
#10: array1[i] = i ;
The first two statements merely declare a reference to an int array; we have not
yet defined the dimension of the two arrays. The third line produces a compiletime
error. Line 4 allocates an array of 10 Objects, and array3 is the named reference
to those objects. Lines 5 and 6 allocate 10 ints and bind them to the array names.
An assignment happens on line 7: The value 5 is assigned to the second element of
array1. Line 8 is interesting because, although the compiler allows the statement,
you get a runtime diagnostic: java.lang.ArrayIndexOutOfBoundsException. Finally,
line 9 uses the lengthmember variable of array1 to determine the upper bound.
|
|
|
|