Your First Java Application¶
This lab might be super easy for you, but don't skip through it, and, especially, don't copy-and-paste the code. Start teaching your fingers to type Java!
Write a Hello.java file¶
Create a new file called Hello.java
and type (don't copy/paste) the following
code into that file, then save it.
public class Hello {
public static void main(String [] args) {
System.out.println("Hello!")
}
}
Compile It¶
Before you can run the code, you need to compile it using javac
,
telling it the name of the Java source file to compile.
javac Hello.java
Error?
One of the most important skills to learn as a Java developer is reading the error messages carefully.
Hello.java:4: error: ';' expected
System.out.println("Hello.")
^
1 error
Verify Compilation¶
Success!
If you fixed the error (or you automatically typed the semi-colon when you were
typing in the code!), you should now have a Hello.class
file.
Let's check that we have everything by doing an ls
(or dir
if you're on Windows):
$ ls
Hello.class Hello.java
If you see those two files, you're all set.
Running it¶
You can run the program by passing the name of the class to the Java virtual machine (VM):
java Hello
If all went well, you'll see the text Hello
output and then the program ends.
Class Name = Filename
Just a reminder that Java requires the name of the class to match the name of the file. There are some exceptions to this, but 99.99% of the time, you should follow this rule.
Using Hello.class
What happens if you try to run it with the full file name of Hello.class
?
java Hello.class
Error: Could not find or load main class Hello.class
The error message, alas, is not terribly helpful, but now you know what's wrong if you ever see it.
Questions?¶
That's all for this lab. If you have any questions, or anything was confusing, be sure to note them in your Learning Journal.
You can move on to Lab 2.