This is how you run the program:
java FooFirst, notice the command to run a Java program is called java. The compiler, by contrast, is called javac (pronounced Java-see).
Second, you give the name of the class, without any extension. In particular, you do not put Foo.class (nor Foo.java).
What happens when a program is run? It looks for the main() method, and runs all the statements in the body.
For example, suppose the following code is in Foo.java.
public class Foo { public static void main( String [] args ) { System.out.println( "Greetings, fellow programmer!" ) ; int count = 2 ; count *= 2 ; System.out.println( "I say \"hi\"" + count + " times " ) ; } }There are four statements in main(). The first statement prints a greeting. The second statement declares count and initializes it to 2. The third statement does a compound assignment statement, and multiplies count by 2 which makes it 4. Finally, the last line prints: I say "hi" 4 times. Notice that we needed an escape sequence to print out the double quotes within a String.
C and C++ programmers may be surprised to learn that more than one class can have a main() (in C/C++, there can only be one main()---and it's isn't even in a class!).
This doesn't cause a problem. When you run a program, you must pick a single class, and it runs the main() method of that class. If that class does not have a main(), then the program won't run.
Classes can also have other methods besides main(). Here's an example:
public class Foo { public static void main( String [] args ) { System.out.println( "Greetings, fellow programmer!" ) ; int count = 2 ; count *= 2 ; System.out.println( "I say \"hi\"" + count + " times " ) ; } void printHi() { System.out.println( "Hi" ) ; } }
Now you might ask "Why would you write a method in a class that's not run? Why write it in the first place?". It turns out these methods can run, but you have to do something special to make it happen. These methods have to be invoked (which means that somewhere else, some method must "call" this method). Only main() is automatically invoked when you run it.
Methods in a class (except main()) don't run, unless they are invoked. Alas, you have to wait to figure out this means. For now, only the code in main() runs, and then only if you call java on the class which this main() exists.