Java to C++

 

This site is designed to help Java programmers translate the concepts they know into C++. Fortunately the basic syntax of the two languages are very similar. This site will focus on the differences. This is not a good place to begin to learn how to program. It is assumed that you already know that. This is to help you over the Java to C++ transition. This guide is not exhaustive. It is meant to get you started quicker, but it is no substitute for a good book on C++.

Similarities

  • Declaration of variables, assignment, arithmetic
  • Control statements such as if, while, for, switch

Major Differences

  • Java manages the reclamation of all storage. If you do a new in Java and stop using that storage, the system will clean it up. In C++ you must reclaim all storage yourself. In particular you must learn about delete and class destructors.
  • Handing of pointers. Pointers in Java are pervasive and implicit. You need to know about them, but Java takes care of them for you. In C++ pointers are fundamental and must be carefully addressed.
  • Input/output streams. The concepts are the same, but the syntax is very different. This is particularly true when writing the screen and reading from the keyboard.
  • Source code dependencies. In Java you simply declare the import of a package and everything else in handled for you. In C++ a much older include mechanism with header (.h) files is used and must be understood.
  • Parameter passing. In Java all simple values, such as int or double, are passed as copies and all objects are passed as pointers. Because of the pointer concepts in C++ there are a variety of parameter passing strategies and they must be declared explicitly.

Minor Differences

  • The use of boolean values. In C++ they are really just integers with no type checking support. Watch for errors
  • Syntax for declaring classes. The basis syntax is different and methods have their definitions and their code body declare separately to accommodate the include file mechanism.
  • Strings have some minor differences.

Example program comparisons

The following are a series of example programs. Each example is coded in both Java and in C++ to do the same thing. Then there is an explanation of the differences between the two implementations.

1 - HelloWorld

2 - Variables and Arithmetic

3 - Strings

4 - Input from the keyboard

5 - Pointers and structs

6 - Compiler directives (include and .h)

7 - Simple classes

8 - Multiple related classes

9 - Methods and parameters

10 - Arrays

11 - Files