Chapter 3: Syntax of the Java Language
Java has all the features of any powerful, modern language. If you are familiar with C or C++ you will find most of its syntax very familiar. If you have been working in Visual Basic or related areas you should read this chapter to see the differences. You'll quickly see that every major operation you could carry out in Visual Basic has a very similar analog in Java.
The two major differences between Java and Visual Basic are that Java is case sensitive (most of its syntax is written in lower case) and that every statement in Java is terminated with a semicolon(;). Thus Java statements are not constrained to a single line and there is no line continuation character.
In Visual Basic, we could write
y = m * x + b 'compute y for given x
or we could write
Y = M * X + b 'upper case Y, M and X
and both would be treated as the same. The variables Y, M and X are the same whether written in upper or lower case.
In Java, however, case is significant, and if we write
y = m * x + b; //all lower case
or
Y = m * x + b; //Y differs from y
we mean two different variables: "Y" and "y." While this may seem awkward at first, having the ability to use case to make distinctions is sometimes very useful. For example, programmers often capitalize symbols referring to constants:
Const PI = 3.1416 ' in VB final float PI = 3.1416; ' in Java
Note the final modifier in Java means that that named value is a constant and cannot be modified.
Programmers also sometimes define data types using mixed case and variables of that data type in lower case:
class Temperature //begin definition of //new data type Temperature temp; //temp is of this new type
We'll see much more about how we use classes in the chapters that follow.
The major data types in Java mirror those in Visual Basic:
Java | Visual Basic | |
boolean | true or false |
Boolean |
byte | signed 8-bit value | Byte |
short | 16-bit integer | Integer in VB16 |
int | 32-bit integer | Long |
long | 64-bit integer | |
float | 32-bit floating point | Single |
double | 64-bit floating point | Double |
char | 16-bit character | |
String | 16-bit characters | String |
Note that the lengths of these basic types are irrespective of the computer type or operating system. For example, in Visual Basic 3.0, an integer was 16-bit and a Long 32-bit, while in 32-bit Visual Basic 4.0, both Integers and Longs are 32-bit.
Characters and Strings in Java are always 16 bits wide: to allow for representation of characters in non-Latin languages. The 32-bit version of Visual Basic 4.0 also represents characters in strings as 16-bit entities. Both use a character coding system called Unicode.
You can convert between variable types in the usual simple ways.
float y; //y is of type float int j; //j is of type int y = j; //convert int to float
to promote an integer to a float.
j = (int)y; //convert float to integer
Boolean variables can only take on the values represented by the reserved words true and false. Boolean variables also commonly receive values as a result of comparisons and other logical operations:
int k; boolean gtnum; gtnum = (k >6); //true if k is greater than 6
Unlike C or Visual Basic 3, you cannot assign numeric values to a boolean variable and you cannot convert between boolean and any other type.
Any number you type into your program is automatically of type int if it has no fractional part or of type double if it does. If you want to indicate that it is a different type, you can use various suffix and prefix characters to indicate what you had in mind.
float loan = 1.23f; //float long pig = 45L; //long long color = 0x12345; //hexadecimal int register = 03744; //octal: leading zero
Java also has three reserved word constants: true, false, and null, where null means an object variable which does not yet refer to any object. We'll learn more about objects in the next chapters.
You can represent individual characters by enclosing them in single quotes:
char c = 'q';
Java follows the C convention that the "whitespace characters" can be represented by preceding special characters with a backslash. Since the backslash itself is thus a special character, it can be represented by using a double backslash.
'\n' |
newline (line feed) |
'\r' | carriage return |
'\t' | tab character |
'\b' | backspace |
'\f' | form feed |
'\0' | null character |
'\"' | double quote |
'\'' | single quote |
'\\' | backslash |
Variable names in Java can be of any length and can be of any combination of upper and lower case letters and numbers, but like VB, the first character must be a letter. Further, since Java uses Unicode representations throughout, you can intermingle characters from other language fonts if you wish, but this is usually more confusing than it is useful.
P = 3.1416;
Note that since case is significant in Java, the following variable names all refer to different variables:
temperature Temperature TEMPERATURE
You must declare all Java variables that you use in a program before you use them.
int j; float temperature; boolean quit;
This is analogous to the usual practice in VB of declaring
Option Explicit
which then requires that you declare every variable in advance:
Dim j As Integer Dim temperature As Single Dim quit As Boolean 'in VB4 only
Java also allows you to declare variables just as you need them rather than requiring that they be declared at the top of a procedure:
int k = 5; float x = k + 3 * y;
This is very common in the object-oriented programming style, where we might declare a variable inside a loop which has no existence or scope outside that local spot in the program.
Java, like C, allows you to initialize a series of variables to the same value in a single statement:
i = j = k = 0;
This can be overused and confusing so do not overuse this feature. The compiler will generate the same code for:
i = 0; j = 0; k = 0;
whether the statements are on the same or successive
lines.
Now let's look at a very simple Java program for
adding two numbers together. This program is a stand-alone program
or application. We will also see later that Java applets
have a similar style in many ways, but do not require a main
function.
import java.awt.*; import java.io.*; class add2 { public static void main(String arg[]) { double a, b, c; //declare variables a = 1.75; //assign values b = 3.46; c = a + b; //add together //print out sum System.out.println("sum = " + c); } }
This is a complete program as it stands, and if you
compile it with the javac compiler and run it with the
java interpreter, it will print out the result:
sum = 5.21
Let's see what observations we can make about this
simple program:
public static void main(String arg[])
double a = 1.75; double b = 3.46; double c = a + b;
This simple program is called "add2.java" in the \chapter3 directory on your example disk. You can compile and execute it by copying it to any convenient directory and typing
javac add2.java
and you can execute it by typing
java add2
The fundamental operators in Java are much the same as they are in Visual Basic and most other modern languages.
Java | VB | |
+ | + | addition |
- | - | subtraction, unary minus |
* | * | multiplication |
/ | / | division |
% | Mod | modulo (remainder after integer division) |
The bitwise and logical operators are derived from C rather than
from VB.
Java | VB | |
& | And | bitwise And |
| | Or | bitwise Or |
^ | Xor | bitwise exclusive Or |
~ | Not | one's complement |
>> n | right shift n places | |
<< n | left shift n places |
Like C/C++ and completely unlike other languages
Java allows you to express incrementing and decrementing of integer
variables using the "++" and "--" operators.
You can apply these to the variable before or after you use it:
i = 5; j = 10; x = i++; //x = 5, then i = 6 y = --j; //y = 9 and j = 9 z = ++i; //z = 7 and i = 7
Java allows you to combine addition, subtraction, multiplication and division with the assignment of the result to a new variable.
x = x + 3; //can also be written as: x += 3; //add 3 to x; store result in x //also with the other basic operations: temp *= 1.80; //mult temp by 1.80 z -= 7; //subtract 7 from z y /= 1.3; //divide y by 1.3
This is used primarily to save typing: it is unlikely to generate any different code. Of course, these compound operators (as well as the ++ and - operators) cannot have spaces between them.
The familiar if-then-else of Visual Basic, Pascal and Fortran has its analog in Java. Note that in Java, however, we do not use the "then" keyword.
if ( y > 0 ) z = x / y;
Parentheses around the condition are required in Java. This format can be somewhat deceptive: as written only the single statement following the if is operated on by the if-statement. If you want to have several statements as part of the condition, you must enclose them in braces:
if ( y > 0 ) { z = x / y; System.out.println("z = " + z); }
By contrast, if you write
if ( y > 0 ) z = x / y; System.out.println("z = " + z);
the Java program will always print out "z=" and some number, because the if clause only operates on the single statement that follows. As you can see, indenting does not affect the program: it does what you say, not what you mean.
If you want to carry out either one set of statements or another depending on a single condition, you should use the else clause along with the if statement.
if ( y > 0 ) z = x / y; else z = 0;
and if the else clause contains multiple statements, they must be enclosed in braces as above.
There are two or more accepted indentation styles
for braces in Java programs: that shown above will be familiar
to VB and Pascal programmers. The other style, popular among C
programmers places the brace at the end of the if statement
and the ending brace directly under the if:
if ( y > 0 ) { z = x / y; System.out.println("z=" + z); }
You will see both styles widely used.
Above, we used the ">" operator to mean "greater than." Most of these operators are the same as in VB and other languages. Note particularly that is equal to requires two equals signs and that "not equal" is different than VB:
VB | Java | Meaning |
> | > | greater than |
< | < | less than |
= | == | is equal to |
<> | != | is not equal to |
>= | >= | greater than or equal to |
<= | <= | less than or equal to |
When you need to combine two are more conditions in a single if or other logical statement, you use the symbols for the logical and, or, and not operators. These are totally different than from any other languages except C/C++ and are confusingly like the bitwise operators shown above:
Java | VB |
&& | logical And |
|| | logical Or |
~ | logical Not |
So, while in VB we would write
If ( 0 < x) And (x <= 24) Then Msgbox "Time is up"
In Java we would write
if ( (0 < x) && ( x <= 24) ) System.out.println ("Time is up");
Since the "is equal to" operator is "=="
and the assignment operator is "=" they can easily be
misused. If you write
if (x = 0) System.out.println("x is zero");
instead of
if (x == 0) System.out.println("x is zero");
you will get the odd-seeming compilation error, "Cannot convert double to boolean," because the result of the fragment
(x = 0)
is the double precision number 0, rather than a boolean true or false. Of course, the result of the fragment
(x == 0)
is indeed a boolean quantity and the compiler does not print any error message.
The switch statement is somewhat analogous to the VB Select Case statement: you provide a list of possible values for a variable and code to execute if each is true.
Select Case j 'in VB Case 12: Msgbox "Noon" Case 13: Msgbox "1 PM" Case Else Msgbox "Some other time " Edn Select
However, in Java, the variable you compare in a switch statement must be either an integer or a character type and must be enclosed in parentheses:
switch ( j ) { case 12: System.out.println("Noon"); break; case 13: System.out.println("1 PM"); " break; default: System.out.println("some other time..."); }
Note particularly the break statement following each case in the switch statement. This is very important in Java as it says "go to the end of the switch statement." If you leave out the break statement, the code in the next case statement is executed as well.
As you have already seen, comments in Java start with a double forward slash and continue to the end of the current line. Java also recognizes C-style comments which begin with "/*" and continue through any number of lines until the "*/" symbols are found.
//Java single-line comment /*other Java comment style*/ /* also can go on for any number of lines*/
You can't nest Java comments, once a comment begins in one style it continues until that style concludes.
Your initial reaction as you are learning a new language may be to ignore comments, but they are just as important at the outset as they are later. A program never gets commented at all unless you do it as you write it, and if you want to ever use that code again, you will find it very helpful to have some comments to help you in deciphering what you meant for it to do. Many programming instructors refuse to accept programs which are not thoroughly commented for this reason.
Java has unfortunately inherited one of C/C++'s most opaque constructions, the ternary operator. The statement
if ( a > b ) z = a; else z = b;
can be written extremely compactly as
z = (a > b) ? a : b;
The reason for the original introduction of this statement into the C language was, like the post-increment operators, to give hints to the compiler to allow it to produce more efficient code. Today, modern compilers produce identical code for both forms given above, and the necessity for this turgidity is long gone. Some C programmers coming to Java find this an "elegant" abbreviation, but we don't agree and will not be using it in this book.
Java has only 3 looping statements: while, do-while, and for. The while is quite analogous to VB's. In VB, we write
i= 0 while ( i < 100 ) x = x + i i = i + 1 wend
while in Java we write
i = 0; while ( i < 100) { x = x + i++; }
The loop is executed as long as the condition in parentheses is true. It is possible that such a loop may never be executed at all, and, of course, if you are not careful, that a while loop will never be completed.
The Java do-while statement is quite analogous, except that in this case the loop must always be executed at least once, since the test is at the bottom of the loop:
i = 0; do ( x += i++; } while (i < 100);
This is entirely analogous to the do-loop statement in VB:
i = 0 Do x = x + i i = i + 1 Loop While i < 100
The for loop is the most structured: it has
three parts, an initializer, a condition and an operation that
takes place each time through the loop, each separated by semicolons.
for (i = 0; i< 100; i++) { x += i; }
Let's take this statement apart:
for (i = 0; //initialize i to 0 i < 100 ; //continue as long as i < 100 i++) //increment i after every pass
In the loop above, i starts the first pass through the loop set to zero. A test is made to make sure that i is less than 100 and then the loop is executed. After the execution of the loop the program returns to the top, increments i and again tests to see if it is less than 100. If it is, the loop is again executed.
Note that this for loop carries out exactly the same operations as the while loop illustrated above. It may never be executed and it is possible to write for loops that never exit.
One very common place to declare variables on the spot is when you need an iterator variable for a for loop. You simply declare that variable right in the for statement as follows:
for (int i = 0; i < 100; i++)
Such a loop variable exists or has scope only within the loop. It vanishes once the loop is complete. This is important because any attempt to reference such a variable once the loop is complete will lead to a compiler error message. The following code is incorrect:
for (int i =0; i< 5; i++) x[i] = i; //the following statement is in error //because i is now out of scope System.out.println("i=" + i);
You can initialize more than one variable in the initializer section of the Java for statement, and you can carry out more than one operation in the operation section of the statement. You separate these statements with commas:
for (x=0, y= 0, i =0; i < 100; i++, y +=2) { x = i + y; }
It has no effect on the loop's efficiency, and it is far clearer to write
x = 0; y = 0; for ( i = 0; i < 100; i++) { x = i + y; y += 2; }
It is possible to write entire programs inside an over-stuffed for statement using these comma operators, but this is only a way of obfuscating the intent of your program.
If you have been exposed to C, or if you are an experienced C programmer, you might like to understand the main differences between Java and C. Otherwise you can skip this section.
In this brief chapter, we have seen the fundamental
syntax elements of the Java language. Now that we understand the
tools, we need to see how to use them. In the chapters that follow,
we will take
up objects and show how to use them and how powerful
they can be.
[Top of page] | [Previous chapter] |
[Next chapter] |
[Java expertise]
Java and
all Java-based trademarks and logos are trademarks or registered
trademarks of Sun Microsystems, Inc. in the U.S. and other countries.