Every Java program (no matter how simple or complex) contains a fundamental structure. The simplest thing you can do in a Java program is print some text.
This tutorial focuses on:
- Java program core code
- Printing text
- Including comments in Java code
Java program core code
Fundamental structure of a Java program consists of these elements:
A class declaration - A class is a grouping of related variables and functions (methods) that is used to achieve something. We explain variables and methods shortly, don't worry if right now you don't know what they are. All the source code for a Java program will be placed within the class definition. The class is given a name and the code within it is sorrounded by curly brackets.
A main() method - A method is a grouping of code that executes when it is called. One method used in every Java program is the main() method, it's what makes a Java program work. The main() method has to be set with a few special keywords and a certain parameter like in the example below.
The above example is a 'bare bones' Java program. It doesn't do anything, only contains the fundamental Java program structure.
You can use two methods to print text in Java. Use double quotes for the text within each method.
System.out.print() method - prints a line of text
System.out.println() method - prints a line of text followed by a line break
NOTE: Every line of code in a Java program must end with a semicolon or an error will be generated!
Including comments in Java code
Comments are declared so that code would be easier to understand and to navigate. Comments can be placed anywhere within code. You can have single line comments or multi-line comments.
Single line comments - declared with two / symbols (span a single line)
multi-line comments - declared with a starting /* and an ending */ (span as many lines as you want)