Lesson: Basic Syntax
Understand the syntax rules of Java, basic program structure, naming conventions, code blocks and comments.
As we move forward, we will start to acquire new vocabulary at an increasing rate. It is normal for vocabulary to take a while to stick, so don’t give up! Additionally, syntax is something you will learn by doing (and messing up!). Syntax is a challenge that you will always be getting better at, and is something nobody is perfect at.
All of these things (other than statements) have names. Names in Java (also called identifiers) follow these rules:
- Start with a letter, $ or _ (underscore). After the first character, you may use any combination of characters.
- Java Keywords cannot be used as names.
- Names are case sensitive. That means MyName is not the same as myname or myName.
While not requred by Java, most programmers follow this convention:
- Class names start with an upper case letter. (MyClass rather than myClass)
- Variable and method names start with a lower case letter. (myVariable rather than MyVariable)
- When names are made up compound words, the first letter of the second word is upper case: MyClass, myVariable, myMethod.
- Upper case all words in a constant and separate compound words with an underscore: MY_CONSTANT, WHEEL_DIAMETER, CAMERA_IP.
Keywords are reserved words used by Java. A list of the keywords can be found here. The meanings of the keywords will be discussed later. Note: when something is ‘reserved’ it means you cannot use it as a name of a variable or class. If you try to use a keyword in this way, the program will not compile.
Whitespace is also a form of commenting. Whitespace is blank lines, indents, extra spaces used to make your code easier to read. Again, this is both for yourself and others that may have to read your code. Use whitespace to separate operations, groups of statements and dense lines of code.
Note that braces { } are used to identify blocks of code that are treated as a group. All of the code for a class is enclosed in braces just as all code in a method is enclosed in braces. Just like a set of parentheses can have multiple layers like (x - (y-2)), so can braces. It is not uncommon for the end of a program to have many closing braces as each layer is closed off. Making sure each opening brace is paired with a closing brace is essential.
Finally, all statements end in a semicolon.