Java Lesson 2: Basic Syntax

1
20

Introduction

Similar to letters, punctuation, and grammar rules in human languages, the language of Java programs consist of a variety of symbols, concepts, and rules; which we will learn in this tutorial.

Java Syntax and Rules

Program Structure

When you write a program in Java, you create at least one file with the extension .java that contains the source code. Java programs consist of one or more classes and methods, one of which must be main(). The Java interpreter always begins executing the program at the main() method. In the main() method, statements are normally executed sequentially in order of their appearance. The program tells the computer what operations are performed, much like a cooking recipe tells a chef how to prepare a meal.

All of our Java programs in the first few tutorials will have a basic structure like this:

The program filename must be the same as the ClassName, and have an extension of .java; so a program with a class name of Program1 will be named Program1.java on the disk.

Java Keywords

There are over 50 keywords defined in the Java language or reserved for future use, although more could be added in later versions. These keywords cannot be used as identifiers, variables, classes, or methods.

Java Keywords
abstract assert boolean break byte
case catch char class const
continue default do double else
enum extends final finally float
for goto if implements import
instanceof int interface long native
new package private protected public
return short static strictfp super
switch synchronized this throw throws
transient try void volatile while

 

Java Reserved Words (but not used)
const goto

 

Java Predefined Values
true false null

Identifiers

Identifiers are names given to program elements, such as classes, variables, arrays, and methods. Identifiers consist of letters, numbers, and underscore (_), in any order, except that the first character must not be a number. Uppercase and lowercase letters are ok, although by convention:

  • variables and methods start with lowercase letters
  • classes start with uppercase letters
  • constants are entirely uppercase letters
  • keywords are entirely lowercase letters

An identifier can be quite long, although most implementations have some practical limit. Generally, an identifier should be long enough to make its meaning apparent, but not excessive.

Examples of Valid Identifiers
x radius f12 salary MAXNUM
hourlyRate tempFahrenheit sum_total count area51_notSeen

 

Examples of Invalid Identifiers and the Reason Why They Are Not Valid
7th first character must be a letter
size of circle may not contain illegal character (space)
check-number may not contain illegal character (dash)

Literals

A literal is a constant value in Java. A literal can be used anywhere a value of its type is permitted.

Examples of Literals
32 An integer number.
3.14159 A floating-point number.
“A String can be one or more characters” A string.
‘T’ A character constant.

Indention and Whitespace

In most instances Java does not need or care about indentation or whitespace (spaces, tabs, or newline). However, good programming style suggests their use makes the code easier to read because related blocks of code, such as the contents of a method, are clearly identifiable. It is also permissible and suggested to use blank lines. Future examples will demonstrate good style.

Comments

Comments are not executed at run time; rather, they enable the developer to insert clarifying information into the program to provide assistance to anyone reading the program; including the original developer. Comments can and should be used frequently.

Comments may appear anywhere in a program as long as they are placed after the // character sequence or within the delimiters /* and */.

Separators

Some special characters are separators. The most common is the semicolon used to terminate statements. Other separators are shown below.

Symbol  Name Purpose
; Semicolon Statement terminator.
{} Braces Define a block of code, classes, methods, and local scopes. Also used to contain automatically initialized arrays.
() Parenthesis Contains lists of parameters in method definitions and invocation. Also used for defining operator precedence in expressions, containing expressions in control statements, and surrounding cast types.
[] Brackets Declares array types.
, Comma Separates consecutive identifiers in a variable declaration, and within a for statement.
. Period Separates package names from subpackages and classes. Also separates a variable or method from a reference variable.

Blocks of Code

It is common to put a number of related statements that should be executed as an entire group together into a code block. Codeblocks are surrounded by curly braces. The for loop in the following code snippet uses a codeblock.

A Short Discussion of Java Class Libraries

The Java environment also includes a large (and growing) collection of built-in class libraries which provide support for math functions, strings, input/output (I/O), windows graphics, networking, and time and date calculations, among many others. These are similar to (but not identical to) the C language stdio.h or the Python standard library. The print and println methods shown above make use of these. You will find that the Java architects and supporters have already provided many coding solutions; your task will be to discover them so you don’t have to “reinvent the wheel”.

We will use many library classes and methods throughout these tutorials. A few of the many thousands that exist are listed below.

Sample Java Libraries / Methods
String class
length() The length of the string. Eg. “four” has a length of 4.
toString() Converts data into its string representation.
charAt(n) Returns the single character at position n of the string.
equals() Compares two strings to see if they are equal.
Math class
sin(x) Returns the sine of the angle specified by x in radians.
cos(x) Returns the cosine of the angle specified by x in radians.
pow(y, x) Returns y raised to the x power.
sqrt(x) Returns the square root of x.
abs(x) Returns the absolute value of x.
random() Returns a pseudorandom number between 0 and 1.

Example Program2

Let’s put all this together and create, compile, and run our second Java program. Use your text editor to enter the following code example and save it in a file called Program2.java

[syntax_highlighter mode=”Java” height=”” font_size=”” line_height=”” wrap=”1″]JTJGJTJBJTIwUHJvZ3JhbTIlMjBpcyUyM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UyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMFN5c3RlbS5vdXQucHJpbnRsbiUyOCUyMiUyQyUyMGdpdmluZyUyMCUyMiUyMCUyQiUyMHN1bSUyOSUzQiUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCU3RCUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyRiUyRiUyMEZpbmFsbHklMkMlMjBkaXNwbGF5JTIwdGhlJTIwc3VtJTIwYWZ0ZXIlMjBhbGwlMjBudW1iZXJzJTIwaGF2ZSUyMGJlZW4lMjBhZGRlZC4lMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjBTeXN0ZW0ub3V0LnByaW50bG4lMjglMjJUaGUlMjB0b3RhbCUyMHN1bSUyMGlzJTIwJTIyJTIwJTJCJTIwc3VtJTI5JTNCJTBBJTIwJTIwJTIwJTIwJTdEJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTBBJTdE[/syntax_highlighter]

Enter the command

at the Command Prompt to compile the program. A file called Program2.class is created by the Java compiler.

Then enter the command

to execute the Program2.class file. The program runs and the output is displayed.

Tutorial2_1
Program2 output

Summary

In this tutorial we learned the basic grammar and punctuation rules of the Java language, and used it to run our second tutorial program. All Java developers use these rules to build programs, large or small, that can be understood by the Java compiler and translated into the low-level bytecode that the JVM runs on the computer.

Next Lesson

Next we will move on with Basic Data Types.

1 COMMENT

Leave a Reply