Java Basic Structure

As previously mentioned, Java is an Object-Oriented Programming (OOP) Language. Object Oriented Programming is based around the concept of objects, where an object is made up of Attributes, or Variables, that can contain data, and Methods, that describe actions of an object. A person can be used as a real-world example of an object. A person has attributes such as height, weight, eye colour, hair colour and so on, as well as methods or actions such as, walk, talk and eat.

A Class is a blue print, or template, of an object that describes its attributes and methods. From this template, multiple objects can be created. A Class can be compared to an architects drawing of a building, which describes how it needs to be built. From this drawing, one or more buildings can be made to the specification of the drawing.

The basic structure of a Java Class can be seen below. A Java program can contain one or more Classes. Within a Class or Classes of a program, there must be one Class with a Method called ‘main’, which is executed when the program starts.

// Class definition.
public class Class_name {

   /* Main method of a Java application.
   Excutes when the application starts. */
   public static void main(String[] args) {

      // Statement(s) to execute.

   }
 
}

The words in blue in the above example are known as reserved words and have a specific meaning in Java. These words cannot be used for anything other than the purpose that the language defines. The green lines of text are comments. When programming in any language it is useful to add comments to the code to describe what is happening and why. This is useful when the code is revisited at a later date to make enhancements, or for debugging purposes. Single line comments are preceded by ‘//’, whilst comments over multiple lines start with ‘/*’ and end ‘*/’.

The Class below is a simple example of a program that just outputs the message ‘Hello World!’ in a console window.

public class Hello {

   public static void main(String[] args) {

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

   }

}

In order to run a program like the one above, you must first compile it. This process can vary depending on what you are using to create the program. To compile a program from the command line the following command can be used.

javac filename.java

The program can then be run as follows, where ‘Class_name’ is the name of the class in the file that has just been compiled.

java Class_name

If you are using an Integrated Development Environment, or IDE, such as IntelliJ IDEA, there are menu options to carry out these tasks.