Java Program Structure
In this lesson we will explore the structure of the Java program to understand its basic anatomy.
Every Java program has the following nested components:
- Project – all encompassing umbrella
- Package – sub sections or project
- Class – self contained code segment
- Method – smaller, task specific code segment
- Statement(s) – individual command(s)
The package acts like a folder for storing classes and other resources needed for the program. In Netbeans the package is automatically added to the top of the class like a label.
A class is self contained code block. It holds the multiple methods used to perform tasks within the program. A class can be private or public (although usually public so that it can be used and seen by other parts of the program). The naming of a class follows the same rules as variable naming. After the class name the contained code must be wrapped in 2 curly brackets so the computer knows when it starts and when it ends.
A method is a small block of code designed to do a specific task. In every program you create there will be ONE “main method” (as seen above). The main method is the starting point for the entire program. Multiple other methods can be created within the same program but this will be covered in more detail in a later lecture. The naming of a method follows the same rules as variable naming (see variables lecture). After the method name the contained code must be wrapped in 2 curly brackets so the computer knows when it starts and when it ends
A statement is the nuts and bolts of the Java language. The are single line commands that perform a specific job. In the above example the statement is telling the computer to print the phrase “Hello world” to the output box. Statements must always end in a semi-colon (;). Think of them as the full stop of the Java language.
You have a working Java program as long as you have at least:
- one package
- one class
- one main method
- one statement
Be sure to use the correct syntax throughout your program. If any syntax is incorrect your entire program will come to abrupt end. Java is unforgiving in this regard.
In this lesson you learnt about the structure of the Java program to now understand its basic anatomy.