Java Basic Syntax Tutorial

In this Java tutorial we learn what syntax in programming is.

We also discuss documenting our code, naming things, and special reserved keywords.

Lastly, we take a look at how Java defines scope and what it means, as well as curly brace conventions.

What is Syntax

Simply put, syntax is the specific way we write code. It defines a set of rules for developers, and every programming language defines its own syntax.

As an example, consider the following code that we used to create our first app.

Example:
public class Program {

    public static void main(String[] args) {

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

You’ll see all kinds of weird words, curly braces, parentheses etc. This makes up the syntax of the document.

We can’t change the code however we want. If we do, the compiler won’t understand it and show us all kinds of scary errors.

Example:
make class Program public:

    make function main public and static -- return nothing:
        print text: "Hello, World!"

The example above doesn’t follow Java syntax rules. The code has to be written in a specific manner, for example the public keyword comes before the class keyword, not the other way around.

Throughout the tutorial course we’ll show what the syntax of a concept looks like, as well as an example of it that can be compiled and run in your IDE.

In this lesson, we’ll discuss some of the basics.

Comments

We’ll start of with comments. Comments allow us to document our code and enhance its readability.

Comments are ignored by the compiler, which means the compiler won’t try to execute any text or code written inside a comment.

In most cases, we shouldn’t need comments, our code should be written cleanly and clearly enough so that it’s obvious as to what the code does.

That said, there are many situations where we should make use of comments.

  • When learning programming, or a new language, it’s helpful to comment our understanding of the code.
  • When working on large projects as part of a group, we should provide comments so that other developers immediately understand what’s going on.
  • When using external libraries it may be useful to include short comments so it’s not neccesary to visit the library’s documentation that often.
  • When we’re working with complex code, it may not be immediatly clear what the code is supposed to do. Commenting would make it easier if we need to come back to the code at a later time.
  • When we’re debugging/testing. We may want to temporarily remove pieces of code from execution by commenting them out.

Java supports both types of C++ comments, block comments and single line comments.

Block comments consist of an open tag and a close tag. The open tag is a slash, immediately followed by an asterisk. The close tag is an asterisk, immediately followed by a slash.

Anything between the comments, even if it spans multiple lines, is considered a comment by the compiler.

Syntax: block comment
/*
    anything between the open and
    close tags is a comment even
    if they span multiple lines
*/

Line comments are prefixed with two slashes and is only used on a single line.

Syntax: line comment
 // This is a single line comment

Most programmers prefer to use single line comments, even if they write multiple lines.

Example:
// maybe it's because it's simply
// faster, but most devs like to
// use line comments instead of
// comment blocks

Most IDEs will have a keyboard shortcut to quickly comment and uncomment code.

In Eclipse, select one or more lines that you want to comment and press Ctrl + Shift + C (or Cmd + Shift + C on a Mac). The same applies to uncomment a commented line.

Identifiers (names)

An identifier is the name we use to identify things like variables, functions etc.

There are a few rules and conventions when it comes to naming our identifiers, let’s go through some of them now.

1. A name cannot start with a number, but may contain a number inside of it.

Example:
// not allowed
21_Jump_Street

// allowed
mambo_number_5

2. A name may start with uppercase or lowercase alphabetical letters (A - Z or a - z), underscores ( _ ) or dollar symbol ( $ ).

Example:
// allowed
Name
name

// allowed but not
// conventional
_name
$name

3. A name may not contain special characters such as @, % etc.

Example:
// not allowed
*^_^*
user&name
#lostsock#thestruggleisreal

4. Most names are case sensitive, which means that a name with lowercase letters is not the same as a name with uppercase letters.

Example:
// not the same
learning
LearNing
LEARNING

5. A name should not contain a Java specific keyword. Keywords are words that are reserved for special uses.

Example:
if
enum
static

Let’s take a look at the recommended convention to name identifiers in Java. Typically, developers will use PascalCase or camelCase to name identifiers.

Conventions aren’t enforced by the compiler. Some enterprises may have their own conventions different from those below.

When using pascal case, the first letter of a word is uppercase. If the name has multiple words, each new word is directly connected to the previous word but the first letter is also uppercase.

Example:
// pascal case
Name
FirstName

Typically, classes, interfaces and enums use pascal case.

When using camel case, the first word of a name is lowercase. If a name has multiple words, each new word is directly connected to the previous word but the first letter is uppercase.

Example:
// camel case
name
firstName

Typically, functions, function parameters, methods and fields use camel case.

Constants are written in only uppercase and words are separated with underscores.

Example:
// constants
FIRST_NAME

Packages are written in all lowercase letters.

Example:
// packages
first.name.eng

As mentioned, it doesn’t really matter which convention you use, as long as you stay consistent.

If you name a variable in snake_case, like Python developers, don’t name other variables in camel or pascal case later in the code.

We use and recommend the popular convention showcased above.

We can use our first app from the previous lesson as an example. Here the class ‘Program’ is named in pascal case and the functions ‘main’ and ‘println’ is named in camel case.

Example:
public class Program {

    public static void main(String[] args) {

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

Keywords

Keywords are reserved words that have a special meaning to Java compiler.

If we consider the first program again, some of the keywords would be public, class and void.

Example:
public class Programhell {

    public static void main(String[] args) {

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

Following is a list of keywords for Java.

abstractcontinuefornewswitch
assertdefaultgotopackagesynchronized
booleandoifprivatethis
breakdoubleimplementsprotectedthrow
byteelseimportpublicthrow
caseenuminstanceofreturntransient
catchextendsintshorttry
charfinalinterfacestaticvoid
classfinallylongstrictfpvolatile
constfloatnativesuperwhile
yield_ (underscore)   

You don’t have to memorize the list, for the moment it’s enough to simply know they exist. We cover most in more detail throughout the course.

Scope

Java uses open and close curly braces to define a local scope.

This means that everything inside a pair of open and close curly braces belongs to that local scope.

Example:
public void logger() {

    // 'msg' belongs to
    // 'logger'
    String msg = "Hello World";
}

In the example above, the variable ‘msg’ is between the logger() function’s curly braces.

The variable is in the function’s local scope, it belongs to the logger() function and cannot be used outside of the curly braces.

Because it belongs to the logger() scope, we can have other variables called ‘msg’ outside of the function.

Brace convention

In Java we’re allowed to place our open curly braces on the same line as the header, or on its own line.

Example:
// official Java convention
void logger() {

    String msg = "Hello World";
}

// C/C++ style convention
void logger()
{
    String msg = "Hello World";
}

The official Oracle convention is to place opening curly braces on the same line as the header.

Many Java developers favor the compactness of writing the brace with the header. Others prefer, as is sometimes necessary, a visual break after the header.

Example:
// compact
void logger() {
    String msg = "Hello World";
}

// visual break
void logger() {

    String msg = "Hello World";
}

However, many developers feel that when a visual break is used, it shows clearer when the brace is on the line of the break, like in C++.

Example:
// visual break
void logger() {

    String msg = "Hello World";
}

// cleaner visual break
void logger()
{
    String msg = "Hello World";
}

Even though we typically prefer the C++ style, we will use the official Oracle convention with a visual break in this tutorial course.

Your employer or team may require you to follow their own convention. Otherwise, choose the one that you prefer, but stay consistent.

Further reading

While not necessary, feel free to browse to the following external links for more information on some of the subjects of this lesson.

Official Oracle:

Official Java 13 Specification:

Summary: Points to remember

  • Syntax is the way we write code. Each programming language defines its own syntax.
  • Comments are used to document our code and are indicated with either a double slash, or slash-and-asterisk tags.
  • Identifiers are the names we give our variables, classes, functions etc.
    • Identifiers cannot use keywords as their names.
    • Convention in Java use pascal case (mixed case), camel case, all uppercase snake and all lowercase.
  • Keywords are reserved words that have a special meaning to the compiler.
  • Scope in Java is defined with open and close curly braces where everything inside belongs to its local scope.
  • The official curly brace convention in Java is to write the curly brace on the same line as the header.