In Java we
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;
}
}
|
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.
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 $ |