The smallest possible Java program is a class with a proper class header but no additional code.
public class MyFirstProgram {
}
Create the class shown above in BlueJ.
We know that each Java program needs a main() method to start in. Therefore, let's add one. Please type this part by hand every time! (In fact, you should be typing everything in this lesson by hand.)
public class MyFirstProgram {
public static void main(String[] args) {
}
}
The two basic printing methods in Java are System.out.print() and System.out.println(). The first method prints whatever information you specify and keeps the text cursor on the same line. The second method prints whatever information you specify and then moves the text cursor to the next line.
For example,
public class MyFirstProgram {
public static void main(String[] args) {
System.out.print("Me");
System.out.print("Like");
System.out.println("Java");
System.out.print("Beans");
}
}
prints this output to the terminal window:
MeLikeJava
Beans
Note that every Java instruction ends with a semicolon. Semicolons are required after each command, and they are not used in class declarations or method headers. Although it is syntactically legal to put more than one command on a single line as shown below, please don't. It's generally poor practice.
System.out.print("Me"); System.out.print("Like"); System.out.println("Java");
System.out.print("Beans");
Also note the curly braces and indenting pattern of the code. A class contains methods and those methods contain commands. Each level is enclosed in curly braces (a starting brace and ending brace) and the contents of each enclosure is indented by one tab to show what it belongs to. BlueJ does a good job of coloring each level of indentation. If the coloring of your program looks strange then you are likely missing a curly brace or have improper indentation.
Last modified: December 12, 2022
Back to Main Method