Java and C++ both share a common heritage in the C language. C++ is an object-oriented extension of the C language, while Java was designed as a simplified successor for C++.
All of these languages share the same core language features, including the following
The structure of C++ programs
The first major syntactical difference between Java and C++ source files is the use of separate header and source files in C++.
Here is an example of a simple Java class.
public class Example
{
private int x;
public Example() {
x = 0;
}
public int getX() { return x; }
public void incrementX() { x++; }
public static void main(String[] args) {
Example e = new Example();
e.incrementX();
e.incrementX();
System.out.println("x is now " + e.getX());
}
}
In Java all of the code for the methods belonging to a particular class appears in the class declaration. Further, the Java language requires that the class declaration be saved in a file whose name (Example.java) matches the name of the class.
In C++ classes are frequently spread across two files, the header file and the source file. The header file typically contains the class declaration, which declares the data and function members of the class. The C++ class declaration equivalent for the example class above is
class Example
{
private:
int x;
public:
Example();
int getX();
void incrementX();
};
There are two major syntactical differences here. The first is that the declaration uses private/public sections to declare which date or function members are private or public. The second syntactical difference is the presence of the semicolon at the end of the class declaration.
The class declaration will usually be stored in a C++ header file named "Example.h".
The code for the member functions is typically stored in a separate file called the source file. The source file typically has the same name as the header file and a file extension of '.cpp'.
Here are the contents of the "Example.cpp" file.
#include <iostream>
#include "Example.h"
using namespace std;
Example::Example() {
x = 0;
}
int Example::getX() {
return x;
}
void Example::incrementX() {
x++;
}
void main()
{
Example e;
e.incrementX();
e.incrementX();
cout << "x is now " << e.getX() << endl;
}
Here are some things to note about the syntax of this example.
Include statements
The C++ equivalent of the Java import statement is the #include statement. Includes come in two different varieties. System includes are denoted by the use of angle brackets around the included file name and are used to import declarations related to the C++ standard library and other resources. User includes are denoted by quote marks around the included file name are used to import declarations stored in header files that you have created as part of your project.
#include <iostream> // Used to import C++ input/output streams #include <fstream> // Used to import C++ file streams #include <string> // Used to import the string class #include "Example.h" // Used to import a header file you have written
Java uses the package mechanism to reduce the potential for name conflicts. All classes are required to belong to a package. Two classes with the same name can coexist, as long as the two classes belong to separate packages.
C++ namespaces are the rough equivalents of Java packages and serve the same purpose. To create a namespace and put some items in the namespace you use a namespace declaration.
namespace MyStuff {
// Declare classes, functions, and variables in here
}
Since we are only going to be writing small programs in this course we won't actually need to create any namespaces.
If you want to use something that was declared inside a namespace you have to do one of two things. Your first option is to use the qualified name which includes the name of the namespace. For example, if you want to use the string class that comes with the C++ standard library you have to use its fully qualified name.
std::string str = "Some text";
Your second option is to import a namespace with a using declaration.
using namespace std; // Import the std namespace string str = "Some text"; // Now we can use string without std::
The using declaration typically appears at the top of a source file, right after the #include statements.
cin, cout, and file streams
Java was designed with the expectation that most programs written in the Java language would use a graphical user interface. Indeed, GUI applications are much easier to write in Java than in C++. The expectation in Java was that relatively few applications would use text input and output through a console. In C++ the expectation is that programmers will frequently write applications that use text input and output in a console window. Consequently, C++ makes it much easier to write console applications.
The basic mechanism for doing text input and output is the iostreams facility. To use this facility, you place the include statement
#include <iostream>
at the top of any source file where you want to do text input and/or output.
To do text output, use the cout object in combination with the stream injection operator <<. The endl output manipulator causes a line break in the output, so that the next thing that gets output appears on the following line in the output.
int x = 5; float y = 6.3; cout << "x is " << x << " and y is " << y << endl;
Compare this with the Java equivalent:
System.out.println("x is " + x + " and y is " + y);
To do text input from the console, use the cin object in combination with the stream extraction operator >>. Here is a typical example.
int s; float t; cout << "Enter an integer and a float: "; cin >> s >> t;
Upon encountering a statement involving cin program execution will pause and await appropriate input from the user. Once the user has typed in the data requested by the cin statement execution will continue.
Input and output from text files uses a similar syntax. To use the file streams facility, use the include statement
#include <fstream>
Here is an example showing how to open and use a file stream for output to a text file.
ofstream out; // Create an output file stream object
out.open("numbers.txt"); // Associate the stream with a file
out << "Hello, world!" << endl;
out.close();
Using a text file for input is similar.
int x, y;
ifstream in; // Input file stream object
in.open("data.txt"); // Open the data file
in >> x >> y; // Read two ints
in.close();
Arrays in C++ use a syntax very similar to Java array syntax. Here is a Java example using arrays.
class ArrayExample
{
static int findLargest(int a[]) {
int largest = a[0];
for(int n = 1;n < a.length;n++)
if(a[n] > largest)
largest = a[n];
return largest; }
public static void main(String[] args) {
int x[] = new int[100]; // Create an array to hold 100 ints
int random = 5;
// Fill the array with 100 pseudorandom numbers
for(int n = 0;n < 100;n++) {
x[n] = random;
random = (random*541)%1223;
}
int max = ArrayExample.findLargest(x);
System.out.println("The largest number is " + Integer.toString(max));
}
}
Here is the same example in C++.
int findLargest(int a[],int length) {
int largest = a[0];
for(int n = 1;n < length;n++)
if(a[n] > largest)
largest = a[n];
return largest; }
int main() {
int x[100]; // Create an array to hold 100 ints
int random = 5;
// Fill the array with 100 pseudorandom numbers
for(int n = 0;n < 100;n++) {
x[n] = random;
random = (random*541)%1223;
}
int max = findLargest(x,100);
cout << "The largest number is " << max << endl;
return 0;
}
There are only two minor differences here. The first is the slightly different syntax for declaring the array of ints. The second is the fact that there is no way to examine an array in C++ to determine what its size is. This makes it necessary to pass size information as an additional parameter.
Below is the source code for a Java program based on code from chapter 6 of the Liang Java text we used for CMSC 150 and 250. Translate this program to C++.
// BinarySearch.java: Search a key in a sorted list
import java.util.Scanner;
public class BinarySearch
{
/**Main method*/
public static void main(String[] args)
{
int[] list = new int[10];
// Create a sorted list and display it
System.out.print("The list is ");
for (int i=0; i<list.length; i++)
{
list[i] = 2*i + 1;
System.out.print(list[i] + " ");
}
System.out.println();
// Prompt the user to enter a key
System.out.print("Enter a key ");
Scanner in = new Scanner(System.in);
int key = in.nextInt();
int index = binarySearch(key, list);
if (index != -1)
System.out.println("The key is found in index " + index);
else
System.out.println("The key is not found in the list");
}
/**Use binary search to find the key in the list*/
public static int binarySearch(int key, int[] list)
{
int low = 0;
int high = list.length - 1;
return binarySearch(key, list, low, high);
}
/**Use binary search to find the key in the list between
list[low] list[high]*/
public static int binarySearch(int key, int[] list,
int low, int high)
{
if (low > high) // The list has been exhausted without a match
return -1;
int mid = (low + high)/2;
if (key < list[mid])
return binarySearch(key, list, low, mid-1);
else if (key == list[mid])
return mid;
else
return binarySearch(key, list, mid+1, high);
}
}