C++ For Java Programmers

Topics:
Arrays (1D)
Arrays (2D)
Classes
Comments
File IO
Functions
Libraries
Loops
Operators
Parameters (const and reference)
Pointers
Program Structure
Selection (decisions)
Simple input/output
Struct
Variable declarations

NOTES:
Arrays (1D)
In Java, an array is an object.  Arrays have a variable named length which always contains the number of slots allocated for that array.  Attempts to access an element outside the array bounds (which are from 0 to size-1) result in an exception.  In C++, arrays are not objects.  You must keep track of the length yourself.  If you attempt to access an element outside the array bounds, the system allows it.  This leads to very unpredictable results (e.g., you may overwrite other data, you may cause your program to abort, etc.).  

C++ example:
const int MAX_ITEMS = 10; // common to use const for array size
double array[MAX_ITEMS];  // allocates space for 10 doubles

int count = 0;  // you must maintain the count (may also be true in Java, if array not filled)
do {
    cout << "Enter a double: ";
    cin >> array[count];
    count++;   // count updated
    char reply;
    if (count < MAX_ITEMS)
    {
        cout << "More? ";
        cin >> reply;
    }
} while (count < MAX_ITEMS && reply == 'y');

// As in Java, index bounds are from 0 to size-1.
// A for-loop is often used to process all elements.
for (int i=0; i < count; i++)
    cout << array[i] << endl;

// The following yields unpredictable results
cout << array[10] << endl;

Java example:
final int MAX_ITEMS = 10;
// declare array, then allocate space (can be done on one line)
double[] array;
array = new double[MAX_ITEMS];
// The following displays 10
System.out.println("Array size is: " + array.length);

// The following causes an exception
System.out.println(array[10]);

Arrays 2D
As with 1-dimensional arrays, space is allocated for a 2D array when the array is declared.

Example:
int matrix[3][4];
// often processed with nested for loops
for (int row=0; row<3; row++)
    for (int col=0; col<4; col++)
        matrix[row][col] = 0;

Classes
Both Java and C++ use classes to encapsulate data and functionality (class methods).   The similarities and differences are described in a separate document, available here.
 

Comments
As in Java, C++ comments can be single line, designated by // or multi-line, surrounded by /* and */.  The /** */ comments used with javadocs can be used, but have no special significance in C++.

File IO
File IO is similar to screen IO.  As in Java, files must be opened before being read and should be closed when you are done using them.  You must include the fstream library to do file IO.

C++ Example code:
ifstream infile;  // ifstream used to read from file
ofstream outfile;  // ofstream used to write to file

infile.open("numbers.dat");  // open makes connection to file on disk
if (!infile)  // error checking
    {
    cout << "Error opening input file numbers.dat\n";
    exit(1);  // aborts program, requires cstdlib
    }

outfile.open("numbers.out");  
if (outfile.fail())  // another way to do error checking
    {
    cout << "Error opening output file numbers.out\n";
    exit(1);  // aborts program, requires cstdlib
    }

double number;
infile >> number;  // reads 1 floating point number from file, stops at white space
outfile << number; // writes 1 value to file

infile.close();
outfile.close();
Corresponding Java code:

        FileReader reader = new FileReader("numbers.dat");
        BufferedReader fileIn = new BufferedReader(reader);
        double value;
        value = Double.parseDouble(fileIn.readLine());
   
        // File output not covered in MACS 261



Functions
In Java, functions (normally referred to as methods) exist only within classes.  In addition to class methods, C++ may have functions that are independent of any object. These functions are similar to static methods in Java, except that no class name is needed to invoke the function.   The syntax of defining and using C++ functions is described below.

Prototypes, definitions and function calls
In C++,  a function prototype is typically placed at the top of file, a function definition is placed at the bottom of the file.  The function call can occur in main or some other function.

A prototype is basically the header for the function, followed by a semicolon.  The prototype specifies the return type, name and parameters for the function, such as:
double sqrt(double);
void printArray(int numbers[], int size);

The definition provides the body of the function.  It consists of the header followed by the set of statements that perform the action of the function, surrounded by braces. For example:
void printArray(int numbers[], int size)
{
    for (int i=0; i < size; i++)
        cout << numbers[i] << endl;
}

The function call transfers control to the function.  It consists of the function name followed by the list of parameters in parentheses.  Note that the parentheses must be used even if there are no parameters.

The compiler uses the prototype to verify function calls (correct number and type of parameters, etc.).
Parameters do not require names in the prototype, as the compiler only checks data types.  Function definitions do require names, so parameter values can be accessed.  

Example:
#include <iostream>

// Example prototypes at top of file:
// void functions do not return a value.  
void Welcome(int);
// empty parameter list
void Greetings();
// function that must return a value, parameter names are optional
double doCalc(double a, double b);
//  Example calls in main:
int main()
{
  Welcome(5);    

  Greetings();
  double a = 4.3;  // just to show passing an argument

  double value = doCalc(a, 16.5);
}
// Example function definitions
// Notice that the function header (first line) is the same, except prototypes have a
// semicolon at the end.  
// start with function header, then function body
void Welcome(int numStars)
{
    for (int i=0; i<numStars; i++)
        cout << "*";
    cout << endl << "Welcome\n";  // "\n" forces line feed
}

void Greetings()
{
    cout << "Greetings, earthling\n";
}

double doCalc(double a, double b)
{
    return a*a + b*a;  // must have return of type double
}


Libraries

Used for
Library to include
Screen IO
<iostream>
File IO
<fstream>
Various, such as exit, rand, etc.
<cstdlib>
Math
<math>
IO formatting
<iomanip>

Loops
Loops in C++ are essentially the same as loops in Java.  Remember that braces are needed if there is more than one action in the loop body.

C++/Java examples:
char reply;
do
{    
    cout << "Enter y or n: ";
    cin >> reply;
} while (reply != 'y' && reply != 'n');

sum = 0;
count = 1;
while (count < 10)
{
    sum += count;
    count++;
}

sum = 0;
for (int count=1; count<10; count++)
    sum += count;
Operators
Java and C++ have essentially the same operators, and same operator precedence.
Mathematical: + - / * % += -= /= *= %=
Relational: < > <= >= !=
Logical: || && !
Also bitwise operators, which have not been covered in MACS 261.

Parameters (const and reference)
In C++ function parameters can be passed by value or passed by reference.  The default is pass by value.  

void doSomething(int x)  // makes a local copy, initialized with parameter value
{
    x = 2 * x; // modifies local copy, in this example x is assigned 20
}

int main()
{
    int y = 10;
    doSomething(y);

    cout << y << endl;  // y will still have the value of 10
}
Parameters can also be passed by reference, which means that the address of the variable is passed in, so both the function and main are referencing the same memory location.   Note the & after int, which indicates this is a reference parameter (similar to a pointer, but it doesn't need to be dereferenced).

// parameter MUST be a variable... can't change the value of a literal
void doItAgain(int& x)  // x looks at memory location of parameter

{
    x = 2 * x;
}

int main()
{
    int y = 10;
    doSomething(y);
    cout << y << endl;  // y will now have the value of 20
}

Pointers
A pointer is a variable that contains a memory address.  This concept should be familiar to Java programmers, as object references are essentially memory addresses.  However, in C++ there is an explicit pointer type, with its own declaration syntax.  As in Java, the new operator is used to allocate space from the heap for a pointer.  Unlike Java, pointers require special syntax (called dereferencing) to access the memory which has been allocated.  Also, C++ programmers must return the memory to the heap when they are done using it (Java has automatic garbage collection).

In both C++ and Java, pointer variables may be initialized to NULL (null in Java) when they do not contain a valid memory address.

C++ example:
// pointer declaration uses *, must include the data type
int* iptr;  
// new is used to allocate space, just one int in this example
iptr = new int;
// pointer must be dereferenced using * to access contents
*iptr = 3;
cout << "iptr value: " << *iptr << endl;
// without dereferencing, you would be printing the memory address
cout << "address: " << iptr << endl;
C++ example 2 (commonly use pointers with arrays)
// pointer declaration same above, initialize to NULL for safety
int* arrayPtr = NULL;
// by specifying size in brackets, arrayPtr is now an array
arrayPtr = new int[10];
// normal array syntax can be used to access
for (int i=0; i<10; i++)
    arrayPtr[i] = 0;
// assume arrayPtr is used in some way here
// now return the memory to the heap
delete[] arrayPtr;






Program Structure
Java is an object-oriented programming language.  Every program in Java must have at least one class.  One class in Java will have the function main, which is the starting point for the program.   C++ was developed as a set of object-oriented extensions to the C language.  C is a  procedural language.  There are no classes.  It is therefore possible to create C/C++ programs that do not include any objects.  

Example C++ program:

// Libraries are listed at the top
#include <iostream> // library for IO


using namespace std;
// every C/C++ program must have a main method, which will should be int.  
//main is the function invoked when you execute the program.
int main()            
{   // as in Java, function bodies are surrounded by braces

    cout << "Hello World\n";     // see Simple input/output

}

Corresponding Java program:
// program is included within HelloWorld class, main is a static function (can
// be called with no object).  

public class HelloWorld {
        public static void main(String[] args) {
                System.out.println("Hello World");
        }
}
Selection (decisions)
Decisions in C++ are essentially the same as in Java.  Remember that braces are needed if there is more than one action in the loop body.   Coding pitfalls are also the same in both languages.

C++/Java Examples:
char reply;
cout << "Enter y or n: ";
cin >> reply;
if (reply != 'y' && reply != 'n')
    cout << "Invalid response!\n";

// score is an int containing test grade
if (score >= 90)
    cout << "Grade: A\n";
else if (score >= 80)
    cout << "Grade: B\n";
else if (score >= 70)
    cout << "Grade: C\n";

// can use compound conditions
if (score >= 80 && score < 90)
    cout << "Grade: B\n";

// the following assumes a menu was displayed
int menu;
cin >> menu;
switch (menu) {
    case 1:        // equivalent to if (menu == 1)
        doOne();
        break;  // remember that without this, control continues to next case
    case 2:
        doTwo();
        break;
    default:
        cout <<  "Invalid menu option!\n";
    }



Simple input/output

requires <iostream> library

cout and cin are stream objects, similar to System.out and System.in in Java.
Input is done with extraction operator (>>), output is done with insertion operator (<<).
The type of data is determined by the variable into which the data is placed.

Example C++ code:
int number;  
cout << "Enter a number: ";  // displays a prompt on the screen
cin >> number;  // reads 1 integer, stops at white space
cout << "You entered " << number << endl;  // endl moves to next line
Corresponding Java code:
int number;
System.out.print("Enter a number: ");
number = Integer.parseInt(stdin);  // assumes stdin appropriately declared
System.out.println("You entered " + number); // println forces move to next line

Struct
A struct provides a mechanism in C++ for collecting a set of data fields into a named unit.  It can be thought of as an object that doesn't have any member functions.   Using the struct keyword and a list of members, you define a new data type.  You can then declare variables of that type.  Data members are accessed using the dot operator.

Example:

// define the Date data type.  The identifier is called the structure tag.
struct Date

{ 
// list the members
int month, day, year;

};   // end with a semicolon.  

int main()
{ 
// Use the Data datatype, which allocates 3 ints for each variable.
Date birthday, expiration;

// members can be accessed using the dot operator
birthday.month = 1;

birthday.day = 10;
birthday.year = 1980;

// structs can be treated as a whole
expiration = birthday;

expiration.year = 2002;

cout << "Birthday\n";
// members must be printed individually, << is not defined for the struct
cout << birthday.month << "/" << birthday.day << "/" << birthday.year;
cout << "Expiration\n";
cout << expiration.month << "/" << expiration.day << "/" << expiration.year;
}


Variable declarations
The rules for variable names are essentially the same in both languages, except that Java identifiers can be greater than 32 characters and can have a dollar sign ($) as part of the name.

Many of the data types are the same in both languages, as shown in the example declarations in the tables below.   Although the language declarations are similar, there may be some differences in how memory is actually allocated. For example, Java uses Unicode (16-bits) for characters, while C++ uses ASCII.

In both languages, when a primitive type (int, double etc.) is declared, space is allocated for that variable. However, when an object is declared in C++, space is allocated.  In Java, the declaration allocates enough space for an address (i.e., a reference).  You must always use the new operator to allocate space.  In C++, you will use the new operator only when you declare a pointer.

Primitive types (partial list);

C++
Java
Comments
int anInt; int anInt; whole numbers, also have short, long etc.
double aDouble; double aDouble; decimal numbers, also have float.
char aChar; char aChar; Single quotes 'Y'
bool found;
boolean found;
true/false.  C++ recognizes 0 as false, any other value as true.

Constants

C++              
Java                    
Comments
const int MAX = 5;
final int MAX = 5;


Objects (assume class Point is defined)

C++
Java
Comments
Point aPoint; Point aPoint;
In C++, the declaration allocates space.  
In Java, new must be used.

Arrays

C++              
Java                    
Comments
int nums[10];
int nums;
nums = new int[10];
In C++, declaration allocates space.  
In Java, new must be used.

Pointers

C++              
Java                    
Comments
int* p;
p = new int[5];
n/a
C++ has a pointer type.  Allocates space for the pointer, but not for the data.  In Java, ALL object declarations are references.