- Special Edition Using Java, 2nd Edition -

Chapter 5

Java Versus C++


by Jonah Neugass

Because Java is based on C++, two look very much the same. However, there are some very important differences. Because Java was designed to be a cross-platform Internet enhancement tool, several key modifications were made. Included in these modifications were the removal of pointers and the addition of exception handling and Threads. In this chapter, you delve deeper into some of the more basic differences between the two languages.

Java: C++ Simplified?

Although C++ and Java syntax are very similar, they are not the same language. Several fundamental changes differentiate the two and make Java easier to understand syntactically. These changes include the removal of the preprocessor, header files, typedefs, and #defines. This makes Java easier to learn, as there are fewer quirks to memorize. For example, look at the following C++ code fragment:

#include<string.h>
#define foo 23
class foobar{
public:
foobar(){I=1);
private:
int I;
};

Now look at the Java equivalent:

import java.lang.*
class foobar{
public foobar()(I=1);
public static final int=23;
private int I;
}

As you can see, Java removes all of the preprocessor directives such as #define, making the code easier to understand. To replace the #include statement in C++, Java uses the import statement, which allows the incorporation of other class objects into your own code.

Java Unicode

In Java, characters, strings, and identifiers are composed of 16—bit characters, this number gives greater flexibility to programmers as it removes the constraints of the 8—bit character set in C++. In the Unicode set, the first 256 characters are identical to the ASCII characters 0x00-0xFF(ISO8859-1). Because most computers cannot display all of the Unicode set, special Unicode escape sequences represent these characters. The syntax for accessing these sequences is \uh, where h can represent one to four hexadecimal values.

Java supports C++ escape sequences such as \n, \r, and \t. However, their use is confined to character and string constants.
 

Data Types: Primitive and Reference Variables

In addition to all of the C++ primitive data types, Java has two more: boolean and byte. The size of a boolean variable is one byte, and it can contain a value of true or false. A byte variable is eight bits long and can contain a value of -128 to 127. The character type in Java is also slightly different, having 16 bits instead of the 8-bit character of C++. Regarding integers, as the size of an integer in C++ is system dependent, it is not comparable to a Java integer that is 32 bits. Table 5.1 will help you become more aquatinted with Java primitive data types.

Table 5.1 Primitive Data Types

Type Contains Size Max Min
boolean true,false 1 bit -
char Unicode char. 16 bits \u0000 \uFFFF
byte signed integer 8 bits -128 127
short signed integer 16 bits -32768 32767
int signed integer 32 bits -2147483648 2147483647
long signed integer 64 bits -9223372036854775808 8223372036854775807
float floating point 32 bits ±3.40282347E+38 ±1.40239846E-45
double floating point 64 bits ±1.79769313486231570E+308 ±4.94065645841246544E-324

In addition to these primitive data types are objects, arrays, and strings, which are manipulated differently by Java, because they are passed and copied by reference rather than by value. I will demonstrate the difference between the two methods of handling the different variable types in the following example in which you create two instances of the same class and then assign the second object to the first.

int j,k;
Box b1, b2; //2 Objects of type Box
public CopyPDT(){
j=5;
k=23;
j=k; //j now contains 23
}
public CopyBox(){
b1=new Box(2,2); //create instance of the Box Object with dimensions of 2x2
b2=new Box(3,3); //create instance of the Box Object with dimensions of 3x3
b1=b2; //b1 and b2 now refer to the same 3x3 Box. The Box with dimensions of 2x2
// has disappeared as there are now no variables that reference it.
}

Arrays

In addition to variable types, arrays and strings are also reference types, but each type has its own special rules. Arrays in Java are slightly different from arrays in C++. First, in Java, arrays must be dynamically allocated, like all other reference types, with the new command:

C++ array declaration: int myArray[10]; //creates an integer array of 10 values;
Java array declaration: int [] myArray=new int[10]; //creates a dynamically allocated array of 10
//integer values

Also, when no longer referred to, Java reclaims the memory used by the obsolete variable.

Another difference between C++ and Java arrays is the new way to declare them. As shown in the previous example, you can now place the brackets after the data type as well as after the variable name. You can also use this syntax when passing arrays in methods.

public syntaxExample(int [] thisInt, char thisChar[]){}
//demonstrates 2 ways to pass arrays

Strings

In Java, strings are handled much as they are in C++ with some important exceptions. The most significant exception is that once a string is declared, its contents may not be changed. To actually modify the string, you must create a StringBuffer object that can be initialized with a string and then modified. You can then create a new string with the contents of the StringBuffer:

String thisString=new String(“This is a Strng”); //create the initial String object
StringBuffer correction=new StringBuffer(thisString);
correction.insert(12,’i’); //inserts the character i into the
//StringBuffer object

String fixedString=new String(correction); //Creates a new String with the contents of
//the StringBuffer object correction

Classes and Objects

Java was designed completely as an object-oriented programming language, as opposed to C++, whose object-oriented paradigm is clouded by remnants of C. Java does away with C++ structures such as structs, unions, and procedures. These structures are replaced with methods, interfaces, and a much more highly developed class structure.

The syntax for creating classes in Java is different from C++ in the way that Java handles inheritance. When deriving a subclass from a parent class (or superclass), Java uses the extends keyword in the classes derivation:

public class MyString extends String{}

The class MyString has now inherited all of the methods and variables of its superclass. This is different than the class:mode superclass{ declaration that C++ uses.

Java has also replaced functions and procedures with constructs called methods. Methods work very much the same way that procedures did in C++, except that a method may not be independent of a class (except for interfaces, which are covered in Chapter 12, “Interfaces”).

Java, like C++, allows multiple constructors, thus giving the programmer the ability to initialize an object in a number of different ways. There are two main rules when declaring constructors: the constructor name and the class name must be the same, and no return type is specified when declaring the constructor. Just as with other reference variables, you must dynamically allocate classes with the new keyword. The following example shows a class declaration with multiple constructors.

public Class MyString extends String{
public String x;
public MyString(){
x=new String(“Default String”); //a call to the constructor of class String
}
public MyString(String x){
this.x=new String(x);
}

Notice the use of the keyword this in the previous example. Java uses it just as C++ does—to help distinguish references between class variables and method variables.

Another way to create a class is with the superclass constructor using the keyword super. Here is a simple example:

public class ParentClass{
int x,y;

public ParentClass(x,y){
this.x=0;
this.y=0;
}
}
public class ChildClass extends ParentClass{
public ChildClass(x,y){
super(x,y); //call to the constructor of the superclass
}
}

Class methods are much like constructors but may return any type.

public int ClassMethod(int j){
x+=j;
y+=j;
return (x+y);
}

To create an object, you must use the new keyword to create an instance of the class. You may then use the methods and variables of that class using the “.” operator.

Listing 5.1 Public class MyClass

public class MyClass{
int x,y,z;
public MyClass(int x, int y, int j){
this.x=x;
this.y=y;
this.z=z;
}
public int addValues(){ //public method
return (x+y+j);
}
}
public class UseClass{
int sum;
MyClass test=new MyClass(1,2,3); //creates an object of type MyClass

public void getSum(){
sum=test.addValues(); //calling method addValues in class MyClass
}
}

Statements

Java supports most of the same control statements as C++ with some additions for exception handling and threads.

The loop statements in Java are identical to their counterparts in C++. However, Java has added functionality to the break and continue statements. In general, these statements work the same as they do in C++, allowing transfer of control out of a loop. Java lets the programmer add labels to the statements, giving the ability to transfer control to any place within the method definition. Here is an example:

start: for(int j=0;j<20;j++){
for(int k=0;k<20;k++){
for(int l=0;l<20;l++){
if ((j+k+l)==20) break start; //control will be transferred back to the top of the loop
}
}
}

Java has also removed the goto statement and replaced it with labeled break and continue statements.

With multithreading added to one of Java’s many features, the authors have added the statement synchronized to deal with sections of code where multiple threads might modify objects simultaneously, possibly corrupting the object. The synchronized statement deals with these critical sections by blocking the execution of code until exclusive access to the object can be acquired. The syntax for the synchronized statement is:

synchronized (expression) statement

Expression is the name of the object to be protected, and statement is a block of code to be executed once primary control of the object is acquired.

public swapFirstValues(int []k){
synchronized(k){
int temp;
temp=k[0];
k[0]=k[1];
k[1]=temp;
}

}

Do not use the synchronized statement if the object is never accessed by more than one thread.

Operators and Overloading

The list of operators that Java supports is almost identical to that of C++, as is the order of precedence in which the Java executes those. Java does add the following operators to that list, as shown in table 5.2.

Table 5.2 New Operators

Operator Operation
instanceof Used to determine whether the object on its left side is in instance of the class listed on its right side. This operator returned true or false, depending on the result of the operation.
+ Used for String concatenation. If one of the operands is a primitive type, it is automatically converted to a string. For all other types, it is converted with a call to the method toString().

Table 5.3 shows all the Java operators and their precedences.

Table 5.3 Operator Precedence

Precedence Operator Operand Types Operation
First ++ Arithmetic Unary, pre or post increment
-- Arithmetic Unary, pre or post decrement
+ Arithmetic Unary plus
- Arithmetic Unary minus
~ Integral Unary, bitwise compliment
! Boolean Unary, logical compliment
(type) Any Cast
Second * Arithmetic Multiplication
/ Arithmetic Division
% Arithmetic Remainder
Third + Arithmetic Addition
- Arithmetic Subtraction
+ String String concatenation
Fourth << Integral Left shift
>> Integral Sign extended shift right
>>> Integral Right shift, no extension
Fifth < Arithmetic Less than
> Arithmetic Greater than
<= Arithmetic Less than or equal
>= Arithmetic Greater than or equal
Sixth == Primitive Equal to
!= Primitive Not equal to
== Object Equal (refer to same object)
!= Object Not equal (reference differs)
Seventh & Integral Bitwise AND
& Boolean Boolean AND
Eighth ^ Integral Bitwise XOR
^ Boolean Boolean XOR
Ninth | Integral Bitwise OR
| Boolean Boolean OR
Tenth && Boolean Conditional AND
Eleventh || Boolean Conditional OR
Twelfth ?: Boolean, any, any Ternary operator
Thirteenth = Variable, any Assignment
*=,/=,*=,

%=,+=,-=,

<<=,>>=,

>>>=,&=,

^=,!=

Variable, any with operation Assignment

Name Spaces

The last topic covered in this chapter is that of name spaces. There are several differences between Java and C++ name spaces. The first difference is that there are no global variables or functions of any type. This keeps name-space violations and conflicts to a minimum.

. Java has also used packages, which are basically precompiled sets of classes that you can incorporate into any Java program with the import statement. Each package must be in a directory with the same name as the package name. For example, if the package name is foo.bar.myClass, then the directory the package must be in is /FOO/BAR/. To import the package into a applet or application, you must add the following line to the code:

or

The following list of rules applies to packages, classes, and fields in Java:

The Java name space also supports local variables. They have the same syntax and behavior as they do in C++.
 

Java and C++ are very much alike, but they are very different as well. The new features of Java make it an ideal language for network programming and object-oriented applications of all types. Java's cross-platform capabilities and multithreading will also help make Java the language of choice for many programmers.


Previous PageTOCNext Page

| Previous Chapter | Next Chapter |

| Table of Contents | Book Home Page |

| Que Home Page | Digital Bookshelf | Disclaimer |


To order books from QUE, call us at 800-716-0044 or 317-361-5400.

For comments or technical support for our books and software, select Talk to Us.

© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.