Variables and Arithmetic Java to C++
This example shows the basic types, use of variables and arithmetic. Most of these concepts are the same between Java and C++. A few of the differences are shown here.

Java

C++





*Something.java[2] means the file "Something.java" at line 2.

Constants

To create a constant value in Java[3] requires the rather cumbersome notation of static final before the variable declaration. Note that the constant MAX in C++[4] uses the much simpler and more direct const keyword.

Variables and Arithmetic

In Java[6-8, 10-11] the declaration of variables and the use of them in assignment statements and arithmetic is the same as in C++[7-9, 11-12].

Boolean values

Boolean values are handled differently in Java[13-17] than in C++[14-18]. The declaration in C++[14] is bool instead of boolean. However, that is not really true. In C++ the keyword bool actually creates an integer value. C++ does not recognize booleans as a separate type. Note that in the C++[14] code the variable t is set to the number 7 rather than a true value. In C++ any non-zero value is treated as true. That is why the if statement in Java[14-17] behaves exactly the same as the one in C++[15-18] even though the variable t was set to 7 rather than true. Because of this C++ does not type check the values you provide to if statements, while loops or for loops. You can make mistakes and C++ will not warn you in places where Java would report an error.

Output

Note that in Java[9] a complex line of output is assembled using + to concatonate strings together. In C++[10] this is done using the << operator. This same thing can be seen when comparing Java[12] to C++[13].