Java - First Impressions for a C++ Programmer

Steven Zeil

Last modified: Apr 03, 2014

Contents:
1. Program Structure
2. Program Structure == File Structure
3. Swimming in Pointers
4. Exceptions
5. Corresponding Data Structures

Moving from C++ to Java


I’m not going to lecture on the basics

1. Program Structure


Hello Java

The traditional starting point:

public class HelloWorld {

  public static void main (String[] argv)
  {
    System.out.println ("Hello, World!");
  }
}


Class Syntax

C++

class MailingList {
private:
   struct Node {
      Contact data;
      Node* next;
   };
   Node* first;
public:
   MailingList() 
   {first = 0;}
     ⋮
};

Java

public class MailingList {
   private class Node {
      Contact data;
      Node next;
   }
   private Node first;
public MailingList() 
  {first = null;}
     ⋮
}


Packages

A Java package is like a C++ namespace:

C++

namespace myUtilities {
  class Randomizer {
    ⋮
  };
};

Java

package myUtilities;
class Randomizer {
   ⋮
}

C++ Java
myUtilities::Randomizer r; myUtilities.Randomizer r;

We Can Have Short-Cuts

C++

using myUtilities::Randomizer
   ⋮
Randomizer r;

Java

import myUtilities.Randomizer;
   ⋮
Randomizer r;


We Can Have Shorter Short-Cuts

C++

using namespace myUtilities;
   ⋮
Randomizer r;

Java

import myUtilities.*;
   ⋮
Randomizer r;


Cultural Difference

2. Program Structure == File Structure


Class == File

A class named “Foo” must be placed in a file named Foo.java * And upper/lower case do count!


Classes are not Split into Two Files

mailinglist.h

    and

*  definitions: usually placed in a compilation unit (.cpp file)

mailinglist.cpp

MailingList.java


Package == Directory


Packaging and Compiling 1

Suppose we are building a Java project in ~/jproject.

If we have a class

public class HelloWorld {

  public static void main (String[] argv)
  {
    System.out.println ("Hello, World!");
  }
}

cd ~/jproject
javac HelloWorld.java
java HelloWorld


Packaging and Compiling 2

Suppose we are building a Java project in ~/jproject.

If we have a class

package Foo;

public class HelloWorld {

  public static void main (String[] argv)
  {
    System.out.println ("Hello, World!");
  }
}

cd ~/jproject
javac Foo/HelloWorld.java
java Foo.HelloWorld


Packaging and Compiling 3

Suppose we are building a Java project in ~/jproject.

If we have a class

package Foo.Bar;

public class HelloWorld {

  public static void main (String[] argv)
  {
    System.out.println ("Hello, World!");
  }
}

cd ~/jproject
javac Foo/Bar/HelloWorld.java
java Foo.Bar.HelloWorld


Is Java Just Trying to Be Annoying?

Actually, no.

3. Swimming in Pointers


Primitives are Familiar

int x = 2;
int y = x;
++x;
System.out.println ("x=" + x + " y=" + y);

prints “x=3 y=2”


Everything Else is a Pointer

void foo(java.awt.Point p) {
  p.x = 1;
  java.awt.Point w = p;
  w.x = 2;
  System.out.println ("p.x=" + p.x + " w.x=" + w.x);
}

prints “p.x=2 w.x=2”

  java.awt.Point w = p;

causes w to point to the same value that p does.


Lots of Allocation

Because all new class variables are really pointers, all new class values have to be created on the heap:

C++

Point p (1,2);

Java

Point p = new Point(1,2);


Arrays of Pointers

C++ programmers need to be particularly careful dealing with arrays:

C++

int a[10];
Point* p = new Point[10];

Java

int[] b = new int[10];
Point q = new Point[10];
for (int i = 0; i < q.length; ++i)
   q[i] = new Point();

Without the loop, q would actually be an array of null pointers.


Because there are so many pointers


Beware of ==


equals

To compare objects to see if they have the same contents, use the equals function:

Point p = new Point(1,2);
Point q = new Point(1,2);
if (p.equals(q))
   System.out.println ("That's better.");
else
   System.out.println ("Pay no attention...");

4. Exceptions

An exception is a run-time error signal.


Playing Catch

Try compiling and (if successful), running each of the following:

OpenFile1.java

OpenFile2.java

OpenFile3.java

using both the names of existing and non-existing files, or no name at all.


Unchecked Exceptions

Exceptions come in two main kinds: checked and unchecked


Checked Exceptions

checked exceptions are more specialized


Another Cultural Difference

5. Corresponding Data Structures


The Java API

The Java API is huge, but well documented


Strings

C++ std::string : Java java.lang.String

C++

string s = ...
s[s.size()/2] = 'b';
s = s + s;

Java

String s = ...
s = s.substring(0,s.length()/2)
  + 'b' 
  +  s.substring(s.length()/2+1);
s = s + s;


If You Need to Change a Java String…

…use a StringBuilder

StringBuilder sb = new StringBuilder();
String line = input.readline();
while (line != null) {
  sb.append(line);
  sb.append("\n");
  line = input.readline();
}
String allTheText = sb.toString();


vector : ArrayList

C++

vector<string> v;
v.push_back("foo");
cout << v[0] << endl

Java

ArrayList<String> v = new ArrayList<String>();
v.add("foo");
System.out.println (v.get(0)); 


list : LinkedList

C++

list<string> L;
L.push_back("foo");
cout << L.front() << endl

Java

LinkedList<String> L = new LinkedList<String>();
L.add("foo");
System.out.println (L.getFirst()); 


set : HashSet

C++

set<string> s;
s.insert("foo");
cout << s.count("foo") << endl

Java

HashSet<String> S = new HashSet<String>();
S.add("foo");
System.out.println ("" + S.contains("foo")); 


map : HashMap

C++

map<string,int> zip;
zip["ODU"] = 23529;
cout << zip["ODU"] << endl

Java

HashMap<String,Integer> zip
     = new HashMap<String,Integer>();
zip.put("ODU", 23529);
System.out.println (zip.get("ODU"));