I Android Dev

From rookie graduate to published app developer. Teaching others as you learn boosts your own learning. Thus as I learn, so I share...

Java Syntax And Structure

Java Syntax And Structure

Introduction

A time honoured tradition when learning to write computer code is to start with a hello world program. The idea is that the budding new developer inputs the smallest amount code possible to get an output that reads ‘Hello World’. In this post I will use a hello world example to illustrate some of the basic syntax and structure of Java.

The example code

Below is the code for a simple hello world program in Java.

If you were to copy this code into a Java IDE (for example IntellijIDEA) and hit run, the result would be an output to the console of the message ‘hello world’.

Java source files define Java classes

This code, saved in a file with the .java extension, would be what is known as a source code file. An application would likely be built from many source code files. Generally, each source code file will contain a definition for a single Java class, in the example code above the class definition begins on line 1 with

public class MessagePrinter {

and ends on line 9 with

}

In between these curly braces is the content of the class. There are four components to this piece of code:

  1. The access modifier - public - This means that any application can access the code that follows this modifier.

  2. Return type - class - This indicates that this piece of code will return a class when it is run.

  3. Name - MessagePrinter - Much like your own name, this is used to identify this block of code. The naming convention for classes in Java is for the class name to be a noun, for example Dog, House or MrSpock.

  4. Opening and closing braces - { } - These braces enclose all the code for the class, indicating where the class starts and finishes.

Note that the class name starts with a capital letter and uses the convention known as camel case whereby subsequent words are capitalised.

Java classes define objects (generally, but not always)

A class is often written to be used as a blueprint for creating a Java object. The example code above defines a class called MessagePrinter which can be used as a blueprint to create a MessagePrinter object. Like real world objects a Java object will have what is known as state and behaviour. Consider a light switch; this object can be in an on state or an off state and, when a user flips the switch, the switch’s behaviour is to open or close the electric circuit and thus effect the state. A java class will define an object’s state using variables and its behaviour using methods.

Variables

Variables store values, for example numbers, letters or words. In the example above there is one variable, defined on line 3 as

private static String messageToPrint = "Hello World!";

This statement, in plain English, tells the computer to take the phrase Hello World! and store it in a little box with a label on it, and to write the name messageToPrint on that label so we can easily find the box later and see what we put in it. The box being a small part of the computer’s memory.

There are six components to this piece of code:

  1. Access modifier - private - This means that this variable is only accessible from within this class. Note the keyword static is discussed below.

  2. Variable type - String - This indicates that this is a String variable. Strings are used to hold a sequence of characters. Java is considered a strongly typed language, this means that you must explicitly declare what type of data the variable will hold. Once declared that variable can only ever be used to hold values of the type for which it was declared.

  3. Name - message - This is a unique name used to identify this variable, note that the first letter is lower case, not upper case as it was for the class name.

  4. Assignment operator - = - This does NOT mean equals! In Java (and many other programming languages) this symbol is used as the assignment operator. It assigns the value indicated on the right to the variable declared on the left.

  5. Value - "Hello World!" - The value to be stored in the String variable in this example is the sequence of characters Hello World!. The quotation marks are not stored in the variable, they are used to indicate the start and finish of the sequence of characters that are stored.

  6. Statement end - ; - The final semicolon ; indicates the end of the statement, much the same way as the closing brace } indicates the end of the class.

Methods

Methods define the steps and outcomes of a particular function, for example adding two numbers together and returning the result or concatenating some words together to make phrase. A method can even be defined to call another method, or a whole bunch of methods. In the example code above there is one method, defined on lines 5 to 7 as

public static void main (String[] args) {
  System.out.println(messageToPrint);
}

There are eight components to this piece of code (or scope as it is also known):

  1. Access modifier - public - This method is accessible to any other class, application etc.

  2. Keyword - static - As outlined above, a class is a blueprint for an object, not the object itself. As such, methods can only be run once an object has been instantiated from a class. For example, a light switch cannot be turned on an off by using mould that created the light switch. In Java, if you add the keyword static to a method signature it allows you to run the method directly from the class without the need to instantiate a java object. Note; object creation will be covered in a future article.

  3. Return value - void - This states that the method does not return a value. It does not mean it doesn’t do anything, simply that whatever it does will not return a value to the code that called the method. Note that, in this case, although the method prints a phrase to the console it is not returning this as a value to another piece of code.

  4. Method name - main - Like variables and classes, methods require a unique name to identify them so they can be called upon to run. The naming convention in Java is for method names to begin with verbs, for example AddTwoNumbersTogether, SayHello or SunbatheInTheGarden. However, in this case the method name is NOT a verb! All programs need to start running from a pre-defined point in the code, in the case of Java applications they always start by running the main method. There should be only one main method per application.

  5. Arguments - (String[] args) - Values written in between the parentheses of the method signature () are the input arguments to the method. These can be used within the method body or can be ignored (as is the case here). For example, a method which adds two numbers together could take the two numbers here as inputs.

  6. Opening and closing braces - { } - The end of the method signature is marked by an opening brace {. This also indicates the start of the method body. At the end of the method body there is a corresponding closing brace }. This closing brace marks the end of the method code.

  7. Method body - System.out.println(messageToPrint); - In this example the method body calls another method - println. The println method is part of the Java framework and can be found in a package called out which in turn can be found in a package called system. The println method takes in a single String as an argument and prints the value of that string to the console. In this case the value is the variable messageToPrint which holds the value Hello World!

Summary

  • Java source files are stored with the .java extension
  • Source files contain class definitions
  • Classes are blueprints for creating Java objects
  • Like real world objects, Java objects have state and behaviour
  • Classes define state and behaviour by declaring variables and methods
  • Variables store data of some kind
  • Methods perform some function, logical, arithmetic, or anything else, print hello! for example
  • Much like grammatically correct written human language, Java has very specific rules of syntax and structure.
  • Class and method declaration:
    AccessModifier ReturnType Name(Arguments) { Class / Method Content }
    
  • Variable declaration:
    AccessModifier VariableType Name = Value