Home

Java vs. C++

The assumption in CSCI221 is that you have prior experience programming with Java. This should mean you have seen virtually all the features of the Java language that appear on this page. We will learn the basics of C++ by looking at the similarities and differences with Java.

Also consider:

A note about completeness

Some techniques not mentioned here, e.g., if’s, for loops, math operations like +, -, %, etc., work the same in Java and C++.

Hello World

Java C++
public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello, world!");
  }
}
#include <iostream>
using namespace std;

int main() {
  cout << "Hello, world!" << endl;
}

Compiling, running

Java C++
$ javac HelloWorld.java
$ java HelloWorld
$ g++ -o hello_world hello_world.cpp
$ ./hello_world

Primitive data types

Java C++
  • byte — 8 bits, -128 to 127
  • short — 16 bits, -32768 to 32767
  • int — 32 bits, -231 to 231-1
  • long — 64 bits, -263 to 263-1
  • float — 32 bits, IEEE 754
  • double — 64 bits, IEEE 754
  • booleantrue or false
  • char — 16-bit Unicode character
  • char — (equiv to byte in Java)
  • short — at least 16 bits
  • int — at least 16 bits, usually 32 bits
  • long — at least 32 bits, usually 64 bits
  • long long — at least 64 bits, usually 64 bits
  • float — 32 bits, IEEE 754
  • double — 64 bits, IEEE 754
  • long double — usually 80-bit floating point
  • booltrue or false

String functions

In both languages, strings are arrays of char’s. The String class is built into Java, so you don’t need to do anything special to use it. In C++, you must write #include <string> at the top of your file. Note that String is capitalized in Java (like all Java classes), while in C++ it is not.

Java C++
Create a string:
String msg = "Test...";
Create a string:
#include <string>
using namespace std;

//...
string msg = "Test...";
Test if two strings are equal:
String msg1 = "Abc";
String msg2 = "Xyz";
if(msg1.equals(msg2)) {
  // they are equal
}
Test if two strings are equal:
string msg1 = "Abc";
string msg2 = "Xyz";
if(msg1 == msg2) {
  // they are equal
}
Append strings:
String s1 = "Abc";
String s2 = "Xyz";
String s3 = s1 + s2;
Append strings:
string s1 = "Abc";
string s2 = "Xyz";
string s3 = s1 + s2;
Copy a string:
String s1 = "Abc";
// Don't do this with other class types!
// It works with String because Strings
// are immutable.
String s2 = s1;
Copy a string:
string s1 = "Abc";
string s2 = s1;
Get the length:
String msg = "Abc";
int msgLength = msg.length();
Get the length:
string msg = "Abc";
int msgLength = msg.length();
Get a particular character:
String msg = "Abc";
char letterB = msg.charAt(1);
Get a particular character:
string msg = "Abc";
char letterB = msg.at(1);
char letterC = msg[2];
Extract a substring:
String longMsg = "AbcXyz";
// substring args: start_idx, end_idx-1
// if end_idx is missing, take rest
// result for both commands: "Xyz"
String shortMsg = longMsg.substring(3, 6);
String shortMsg2 = longMsg.substring(3);
Extract a substring:
string longMsg = "AbcXyz";
// substr args: start_idx, length
// if length is missing, take rest
// result for both commands: "Xyz"
string shortMsg = longMsg.substr(3, 3);
string shortMsg2 = longMsg.substr(3);
Search for a string:
String s = "AbcXyz";
int pos = s.indexOf("Xyz");
// pos equals 3
int pos2 = s.indexOf("foo");
// pos2 equals -1
Search for a string:
string s = "AbcXyz";
int pos = s.find("Xyz");
// pos equals 3
int pos2 = s.find("foo");
// pos equals -1
Convert a string to a number:
String s = "123";
int x = Integer.parseInt(s);
String s2 = "123.45";
float x2 = Float.parseFloat(s2);
String s3 = "123.45";
double x3 = Double.parseDouble(s3);
Convert a string to a number:
// this needs: #include <sstream>

string s = "123";
stringstream my_converter(s);
int x;
if(!(my_converter >> x)) {
  // conversion failed
  x = 0; // default value
}

// same technique for float, double, etc;
// just change x's data type
Convert a number to a string:
String s = Integer.toString(123);
String s2 = Float.toString(123.45);
String s3 = Double.toString(123.45);
Convert a number to a string:
// this needs: #include <sstream>

stringstream my_converter;
my_converter << 123; // or a variable
string s = my_converter.str();

my_converter << 123.45;
string s = my_converter.str();

Input/output (keyboard/console)

Java C++
Read from the keyboard:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
float x = sc.nextFloat();
String line = sc.nextLine();
Read from the keyboard:
#include <iostream>
#include <string>
using namespace std;

// ...
int i;
cin >> i;
float x;
cin >> x;

// cin with a string gets a word, not a line!
string word;
cin >> word;

string line;
getline(cin, line); // get the whole line
Print to the console:
System.out.println("Hello, world!");
int x = 5;
System.out.println("X = " + x);
// print y with four decimal places
double y = 4.35;
System.out.format("Y = %.4f%n", y);
// print h in hex
int h = 5038;
System.out.format("H in hex = %X%n", h);
Print to the console:
#include <iostream>
#include <iomanip>
using namespace std;

// ...
cout << "Hello, world!" << endl;
int x = 5;
cout << "X = " << x << endl;
// print y with four decimal places
double y = 4.35;
cout << "Y = " << setprecision(4)
     << fixed << y << endl;
// print h in hex
int h = 5038;
cout << "H in hex = " << hex << h << endl;

Input/output (files)

Java C++
Write to a file:
FileWriter fout = new FileWriter("foo.txt");
PrintWriter out = new PrintWriter(fout);
out.println("Hello, world!");
out.close();
Write to a file:
#include <iostream>
#include <fstream>
using namespace std;

// ...
ofstream out;
out.open("foo.txt");
out << "Hello, world!" << endl;
out.close();
Read from a file:
FileReader fin = new FileReader("foo.txt");
BufferedReader in = new BufferedReader(fin);
String line = in.readLine();
int x = Integer.parseInt(line);
in.close();
Read from a file:
ifstream in;
in.open("foo.txt");
int x;
in >> x;
in.close();

Math functions

Java C++

Math.abs(-15);
Math.ceil(2.35);
Math.floor(2.35);
Math.round(2.35);
Math.log(2.35);
Math.max(5, 3);
Math.min(5, 3);
Math.pow(5, 3);
#include <cmath>
using namespace std;

// ...
abs(-15);
ceil(2.35);
floor(2.35);
round(2.35);
log(2.35);
fmax(5, 3);
fmin(5, 3);
pow(5, 3);

Classes

Java C++
Define a class. This code must be in a file with the same name as the class, i.e., `MyClass.java`.
public class MyClass {
  public int x;
  private float y;

  public MyClass(int x) {
    this.x = x;
    y = 35.25;
  }

  public float getY() {
    return y;
  }

  private void incrementX() {
    x++;
  }
}
Typically in C++, we declare the class in a file like `myclass.h` and define its methods in a file like `myclass.cpp`.
// myclass.h

class MyClass {
  public:
    int x;
    MyClass(int x);
    float getY();
    
  private:
    float y;
    void incrementX();
}

// myclass.cpp
#include <myclass.h>

MyClass::MyClass(int x) {
  this->x = x;
  y = 35.25;
}

float MyClass::getY() {
  return y;
}

void MyClass::incrementX() {
  x++;
}

Type casting and polymorphism

Java C++
Cast primitive types:
float a = 5.5;
int b = 3;

int x = (int)a;
float y = (float)b;
Cast primitive types:
float a = 5.5;
int b = 3;

int x = (int)a;
float y = (float)b;
Single inheritance:
public class A { ... }
public class B extends A { ...}
This means that class B inherits all public members (variables, methods) of class A. Furthermore, those public members of A are public in B. (Note, I'm ignoring "protected" members and their inheritance rules.)
Single inheritance:
class A { ... }
class B : public A { ... }

This means that class B inherits all public members (variables, methods) of class A. Furthermore, those public members of A are public in B. (Note, I'm ignoring "protected" members and their inheritance rules.)

Another variant:

class A { ... }
class B : private A { ... }

This means that class B inherits all public members (variables, methods) of class A. Furthermore, those public members of A are private in B.

Multiple inheritance: Not possible. Use interfaces (see below) as a work-around. Multiple inheritance:
class A { ... }
class B { ... }
class C : public class A, public class B
{ ... }
This means that class C inherits all public members of classes A and B. If both A and B include some of the same members (e.g., same function names), then code in class C must be explicit about whether it is referring to members inherited from A or B.
Override inherited methods:
public class A {
  public void foo() { ... }
}

public class B extends A {
  // override inherited foo()
  public void foo() { ... }
}
Override inherited methods:
class A {
  public:
  virtual void foo();
}

class B : public A {
  public:
  // override inherited foo()
  virtual void foo();
}
In other words, only virtual functions can be overridden in the way you would expect from Java. The virtual keyword activates polymorphism. So, if we have a B object but cast it to an A object, and then call its foo() method, it would use B's foo() method. If foo() was not virtual in the base class, then after casting our B object to an A, A's foo() function would be used and B's foo() function would be inaccessible.
Interfaces:
interface Foo {
  void methodA();
  int methodB(int bar);
}

class Quux implements Foo {
  void methodA() { ... }
  int methodB(int bar) { ... }
}
Interfaces in C++ are accomplished with "pure" virtual functions, e.g., class functions that have no code, but must be defined in descendent classes.
class Foo {
  virtual void methodA() = 0;
  virtual int methodB(int bar) = 0;
}

class Quux : public Foo {
  virtual void methodA() { ... }
  virtual int methodB(int bar) { ... }
}

Arrays

Java C++
Create and initialize arrays:
int[] xs = new int[10];
int[][] matrix = new int[5][7];
int[] ys = {1, 2, 3, 4};

// ragged array
int[][] matrix2 = { {1, 2}, {3, 4, 5} };
Create and initialize arrays:
int xs[10];
int matrix[5][7];
int ys[] = {1, 2, 3, 4};

// ragged array is not possible
// without multiple lines of code
// (often involving a loop)

// instead, try this rectangular
// 2d array
int matrix2 = { {1, 2, 3}, {4, 5, 6} };

Collections

Java C++
Lists:
Integer myint = new Integer(5);
List<Integer> mylist = new ArrayList<Integer>();

mylist.add(myint);
boolean yeah = mylist.contains(myint);

// get from index 0
Integer myint2 = mylist.get(0);

int count = mylist.size();
mylist.clear();
Vectors are used more commonly:
// this needs #include <vector>
// and #include <algorithm>
// (the latter for the find() function)

vector<int> mylist;
mylist.push_back(5);
vector<int>::iterator myIt;
myIt = find(mylist.begin(), mylist.end(), 5);
if(myIt != mylist.end()) {
  cout << "found the number 5." << endl;
}

int x = mylist[0];
mylist.clear();
Maps (key-value pairs):
Map<String, Integer> mymap =
  new HashMap<String, Integer>();
mymap.put("foo", 5);
Integer c = mymap.get("foo");
mymap.remove("foo");
Maps (key-value pairs):
// this needs #include <map>

map<string, int> mymap;
mymap["foo"] = 5;
int c = mymap["foo"];
mymap.erase("foo");

Generics / Templates

Java C++
public class Foo<T> {
  T value;
  T func(T arg) { ... }
}
template<typename T>
class Foo {
  public:
  T value;
  T func(T arg);
}
CSCI 221 material by Joshua Eckroth is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. Source code for this website available at GitHub.