Tino APCS

First Program

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.

  1. In the main BlueJ window, click the New Class button or choose Edit-->New Class from the menu.
  2. Name the class MyFirstProgram and note the convention for class names:
    • Class names should start with a capital letter. (If not, they might be confused with an object reference which you'll understand later.)
    • Spaces are not allowed. Since spaces are not allowed in class names Java programmers capitalize the first letter of each word to make the name more readable.
    • Class names must start with a letter but may have numbers anywhere after the first character.
    • Class names can legally contain a few special characters like underscores and dollar signs but doing so isn't common. The expected convention when naming classes yourself is to use only letters in upper-camel-case WhichIsWhenYouCapitalizeTheStartOfEachWord

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

Dark Mode

Outline