Java programs have a specific structure in how the code is written. There are key elements that all Java programs share.

The Program

Here, we have a program called HelloWorld.java. It is a classic first program!

// This program outputs the message "Hello World!" to the monitor public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }

This program writes the phrase Hello World! to your terminal.

Case-Sensitivity

Java is a case-sensitive language. Case sensitivity means that syntax, the words our computer understands, must match the case. For example, the Java command for outputting is System.out.println(). If you were to type system.out.println() or System.Out.println(), the compiler would not know that your intention was to use System or out.

Let's go over this HelloWorld.java program line by line:

Comments

// This program outputs the message "Hello World!" to the monitor

This is a single-line comment that documents this code. The compiler will ignore everything after // to the end of the line. Comments provide information outside the syntax of the language.

Classes

public class HelloWorld { // class code }

This is the primary class of the file. The naming must match: our file is HelloWorld.java and our class is HelloWorld. We capitalize every word, a style known as camel-case. The curly braces {} mark the scope of the class. Everything inside the curly braces is part of the class.

Methods

public static void main(String[] args) { // Statements }

Every Java program must have a method called main(). A method is a sequence of instructions for the computer to execute. This main() method houses all of our instructions for our program.

Statements

System.out.println("Hello World!");

This code uses a method known as println() to send the text "Hello World!" to the terminal for output. println() comes from an object called out, which is responsible for various types of output. Objects are packages of state and behavior, and they're often modeled on real-world things.

out is housed within System, which is another object responsible for anything to do with our computer!

This line of code is a statement, because it makes something happen. Statements are always concluded with a semicolon.

Whitespace

Java programs permit judicious use of whitespace (tabs, spaces, newlines) to create code that is easier to read. The compiler ignores whitespace, but humans need it! Make use of whitespace to indent and separate lines of code to increase the readability of your code.

Practice

The structure of a Java program will feel familiar the more you work with this language. Continue learning at Codecademy and you'll be a Java pro in no time!

For reference:

Twitter Java Style Guide

Google Java Style Guide

Made with️❤️in NYC © 2019 Codecademy