Student: Professor, you’ve been lying to me.
Prof: Oh?
Student: You’ve shown me a bunch of programs and said they were Java programs. But when I run them using the
java command, nothing happens or I get errors. Look at what happened in the terminal the other day; I made a file called DefineX.java and ran it:Student: What gives?
Prof: You’re right, I haven’t told you the whole truth. There’s a good quote about this – “Education is the art of telling progressively smaller lies.” Cohen, Stewart, and Pratchet whimsically said that teaching often involves giving “a statement that is false, but which nevertheless leads the child’s mind towards a more accurate explanation”. I’ve fudged some details here, by saying things like “the book prints” instead of “Java prints”. So I tried not to say anything false, but I was definitely sneaky.
Student: That’s not reassuring, I’m not a child, and it seems like you’re just making excuses. Just tell me what’s going on!
Prof: OK so here’s the deal. We set up the book to be able to write examples very easily, so we allow writing a bunch of definitions, and the book prints them when you click “Run”. We’ll keep doing that! We want the examples to be short.
Prof: But when you use the
java command on a .java file, it looks for a method definition a the top level called main. It calls that method to “start the program”, and whatever happens in the main method is the program’s behavior. And if main isn’t there, it gives an error like the one you saw.Student: Hmm OK so I need to define a
main method? How do I do that?Prof: There’s actually a few ways. With recent versions of Java, you can write it like this:
Student: Uh… are you sure that worked? I don’t see anything.
Prof: Right! It ran the method… which just had a single definition. Without the infrastructure of the book, nothing prints.
Student: OK, so how I do I write a program that does something? Can I like, print it out myself?
Prof: Yup. There’s a method called
System.out.println that takes a value and prints it. If you run it from your terminal it will print there; in the book it will show on the page.Prof: A lot of courses show something like this as the first program:
Prof: And an important detail – you are not allowed to write
System.out.println(...) at the top level of a program, outside of any method. Calling a method on its own like that, without any definition, is called a statement, and is only allowed inside methods.Student: OK, I think I see at least how to get things running. Make a
main method, use println.Practice
greeting is already defined. Finish main so that running this file prints it.void main() {
String greeting = "Good morning, Java!";
}
String greeting = "Good morning, Java!";
}