Class 2: More Intro


Code to executing program: C++ vs. Java
In C++ we
  1. use an editor to create source code (a .cpp file).
  2. Then we use a compiler to create object code (.o file) from the .cpp file, i.e. machine-code version.
  3. Then a linker links that object code with object code from libraries and other files to create an executable program.
  4. Then we run the executable directly on a machine.

In Java we

  1. use an editor to create source code (a .java file).
  2. Then we use a compiler to create bytecode (.class file) from the .java file, i.e. version for the Java Virtual Machine.
  3. Then we use the virtual machine to interpret the bytecode, i.e. run the program.

The simplest program

It's worth taking a second to compare the simplest programs in C++ and Java. Note that they do nothing!

The Simplest C++ Program The Simplest Java Program (file Ex0.java)
int main()
{
  return 0;
}
class Ex0
{
  public static void main(String [] args)
  {
    return;
  }
}

Hello World

It's tradition to have the first program you see in a new language be the "Hello World!" program. So here it is. Sadly, it's the second Java program you've seen!

Ex1.java
public class Ex1
{
  public static void main(String[] args)
  {
      System.out.println("Hello World!");
    return;
  }
}

$ javac Ex1.java ← compiles Ex1.java to Ex1.class
$ java Ex1       ← starts virtual machine & has it execute Ex1's main()
Hello World!
$

Note that the print statement

	    System.out.println("foo");
	  
is really not that differnt from cout << foo;, because, although you've likely been blissfully unaware of this, the long version of the C++ statement is
	    std::cout.operator<<("foo");
	  
... which maps pretty nicely to the Java version.

A simple program with input and output

Writing output to standard out in a Java program is quite simple. The input requires a bit more scaffolding. The process of breaking up a sequence or stream of characters into meaningful chunks is, in computer science at least, called scanning. In Java, standard in is System.in. However, all you can do with a bare input stream like that is read raw bytes. If you want the raw bytes to be converted into an int (or double, or float, or ...) for you, you typically use a Scanner object to do that for you.

Ex2.java
import java.util.*;

public class Ex2
{
  public static void main(String[] args)
  {
    Scanner s = new Scanner(System.in);
    int n = s.nextInt();
    System.out.println("n = " + n);
    return;
  }
}
$ javac Ex2.java ← compiles Ex2.java to Ex2.class
$ java Ex2       ← starts virtual machine & has it execute Ex2's main()
13 ← the user's input
n = 13
$


Christopher W Brown
Last modified: Wed Aug 19 11:00:04 EDT 2009