From Webster's Dictionary:

syn·tax
Pronunciation: 'sin-"taks
Function: noun
Etymology: French or Late Latin; French syntaxe, from Late Latin syntaxis, from Greek, from syntassein to arrange together, from syn- + tassein to arrange
Date: 1574
1 a: the way in which linguistic elements (as words) are put together to form constituents (as phrases or clauses) b: dealing with the formal properties of languages or calculi

And who said Rholl has no grasp of the English language? Well, the language is Java and the concept of syntax applies here too! This section deals with the ways the classes, interfaces, methods, and variables are arranged together.

HTML and Javascript both had their syntaxes. In HTML the <head> tag had to go before the <body> tag. In Javascript, when you called a function, you had to go function NameCapitalized(parameters) {statements}. Obviously, based on the Java you have seen thus far, Java's syntax is much more like Javascript's than HTML. I toyed with the idea of creating a fairly exhaustive reference page like I did for Javascript, but decided not too. Part of the reason is that I got "exhausted" creating the Javascript page, but mostly I wanted to keep things as simple as possible for this introduction to Java(thankyou Rholl, thankyou). So I settled on the following basic rules of syntax. Of course there are more and you are free to explore on your own.

  1. Syntax I: Comments
  2. Syntax II: Naming
  3. Syntax III: Variables
  4. Syntax IV: Expressions
  5. Syntax V: Arrays
  6. Syntax VI: Statements and Blocks
  7. Syntax VII: Program Flow
    1. If. . .Else Statements
    2. Looping
    3. Comments

      Comments are the most underused syntax element in programming. A comment enables you to add notes to your code to make sure that when someone else(or you in a few years) reads your code and can't figure out what is going on, there is some guide to clear things up.

      There are three ways to comment Java code. The first of these is just like you learned in Javascript:

      /* a 'block' comment. Everything between these marks is not readable by the JVM! */

      /** We will not use these, but this is a 'doc' comment. It is official in it's language and can be read by javadoc tools. Not something we want to play with at home!!**/

      // This is a 'line' comment and the JVM will ignore whatever follows these marks on one line.

      The block and 'doc' comments are both surrounded by beginning and end markers. They should be used when a paragraph or two needs to be said about a block of code in general. The line comment does not have an end marker; it marks everything to the end of the line as a comment. It is most useful to comment the program on a line by line basis.

      The compiler ignores comments; they are there purely to help the programming. Feel free to write as much as you think is necessary, going overboard in explaining if necessary. That said, make sure that the comments you leave are pertinent. Many beginning programmers make the mistake of trying to comment every line, which is almost worse that no commenting at all. Why? First, the programmer tends to tire of all the commenting quickly and gives up on commenting entirely in the long run. Second, the important comments tend to get lost in the mass of verbiage. A good general rule on commenting is to look at a piece of code and ask yourself, "Is what this code does obvious?" If not, comment it.


      Naming

      • identifiers are formed from letters A-Z, a-z, digits 0-9 and underscore _
      • case sensitive, so Count, count and COUNT are three different identifiers.
      • free format, so spaces and new lines make no difference (except to readability by humans(and teachers)!)
      • statements always end with a semi-colon ;

      • class names - start with Capital letter
        A class must be written in an applet with the same name, and with the extention .java
      • variable names - start with lower case letter
      • method names - start with lower case letter
      • all names - start any second or more words with a Capital letter
      • reserved words are (almost)all lower case, and may not be used as identifiers
      Reserved Words
      abstract
      default
      implements
      protected
      throws
      boolean
      do
      import
      public
      transient
      break
      double
      instanceof
      return
      try
      byte
      else
      int
      short
      variable
      case
      extends
      interface
      static
      void
      catch
      final
      long
      super
      volatile
      char
      finally
      native
      switch
      while
      class
      float
      new
      synchronized

      const
      for
      package
      this

      continue
      if
      private
      throw


      Variables

      Much like real life, there is a need in programming to remember things and to associate a name with those things. For instance, you refer to how old someone is by his or her age. Programming languages do the same thing. Statements in the language say things like the following line, which sets the variable cardNumber to a value of 15:

                cardNumber = 15;

      In this example, cardNumber is a variable because its value can be changed. You could set cardNumber to 30 at a later time. This is known as variable assignment: '=' assigns whatever is to the right of it to the variable to the left of it. The semicolon (;)is Java's way of indicating the end of the current statement.

      In some languages, such as BASIC, variables can be created on the fly, and a statement like the preceding one could appear in the middle of a program. In Java, much like C or C++, all variables must be declared at the beginning of a program. When you declare a variable, you must specify both its name and its type. We did not do that in the above example. For instance, a card number would be represented as an integer, which in Java is signified by int:

      int cardNumber;
      cardNumber = 15;
      We can, and usually do, shorten the above 2 statements to one:
      int cardNumber = 15;

      The eight basic (or primitive) types available in Java fall into four categories: integer, floating-point number, character, and boolean. Note: Class names can also be a type for variables.

      Variable type 1. Integer

      Representing numbers is one of the most basic aspects of programming, and numbers can be represented as integers in most cases. An integer is a positive or negative whole number (but no fractional numbers). For example, 18 is an integer, but 18.3 is not. The following table lists the four types of integers available in Java:

      Keyword
      
      
      Type
      
      
      Range
      
      

      byte

      8-bit integer

      -128 to 127

      short

      16-bit integer

      -32768 to 32767

      int

      32-bit integer

      -2147483648 to 2147483647

      long

      64-bit integer

      -9223372036854775808 to 9223372036854775807

      The different integer types enable you to specify a larger or smaller range for the number that is stored in a variable. The int type should be sufficient for most purposes unless the value of the number that needs to be stored is huge (on the order of several billion) or if many smaller numbers need to be stored (in which case byte might make sense). So 9 times out of 10 when you want to create a variable that will be a whole number use type int.

      Variable type 2. Floating-Point

      Although most of the time integers are sufficient, sometimes it's necessary to store numbers with a decimal point, like 3.14132. These numbers are known as floating-point numbers. The following table lists the two types of floating-point numbers in Java.

      Keyword
      
      
      Type
      
      
      Range
      
      

      float

      32-bit float

      -2.24E-149 to 2.24E104

      double

      64-bit float

      -2.53E-1045 to 2.53E1000

      The following example shows how a floating-point number might be used:

                float averageAge;
      
                averageAge = 71.6;

      The difference between the two is that the double type has more precision and can thus hold more decimal places. Most of the time it makes sense to stick with the float type. The range for this type is quite large and when it gets large, use the exponent symbol E. It is the power of 10 to multiply the first part of the number by. For example, 100 would be 1.0E2, 220 would be 2.2E2, and 10,000 would be 1.0E4. In this class, you probably won't be dealing with large floats or doubles but you may use a small float like the above 71.6. Remember most likely you would combine the above 2 statements into float averageAge = 71.6;. I am leaving as 2 statements to remind you that the compiler reads them in order, so think of the syntax of the 2 statments to read like this: 1. You are creating a variable of type float and assigning it the name of averageAge. 2. The already named variable, averageAge, is assigned an initial value of 71.6. I say initial, because on a later statement, you can assign it a new value or even make it part of a method in which the value changes over time(like adding older or younger members to the group, etc.).

      Variable type 3. Character

      A character is basically anything that can be typed on a keyboard: a letter(like a, b, or c), a single-digit number( 1, 2 ,3), or non-alphanumeric character(#, $, %). So, the number 3 could be of type int or of type char. Note: The compiler will kick out an error if you assign a value that is not of the correct type.
      For example,
      int example1 = b; is incorrect and will not compile.

      Keyword
      
      
      Type
      
      
      Range
      
      

      char

      16-bit integer

      Any Unicode character

      The following is an example of how the character type could be used:

                char studentGrade;
      
                studentGrade = 'A';

      Java differs slightly from other languages by including support for Unicode. Unicode is a standard that allows characters in languages other than English to be supported. Although support for this standard is not important to you in this class, it means that your applets can be used internationally without a complete rewrite. Think of Unicode as the new ASCII(for those of you who have not taken networking, here is a quick explanation of ASCII), but with the ability to handle foreign characters.

      Variable type 4. Boolean

      In programming, comparisons between two things happen constantly. Decisions for what the program should do next are based upon on whether the result of a question was true or false. A variable containing a true or false value is known as a boolean. A boolean could be represented with an integer by using a 0 for false and a 1 for true(C programs usually use this method), but that method makes programs much harder to read. Java does the true/false thing.

      Keyword
      
      
      Type
      
      
      Range
      
      

      boolean

      boolean

      true or false

      The following is an example of the boolean type in use:

                boolean smart;
      
                smart = false;

      Booleans can only hold two values: true or false. They are not only useful for remembering what the value of a comparison was, but also to keep track of the current state of your program. For instance, you may have a Slideshow applet that cycles through images automatically if the Cycle button is pressed. You could then have a boolean called cycle that is changed to true or false when the button is pressed.

      Variable type 5. Class type variables

      Any class in Java can construct a new variable. For example, you can create a new Color object by creating a new variable of type Color.

      Color fred=new Color(22,144,200);


      Expressions

      An expression is the most fundamental operation in Java. Expressions are how work on and comparisons with basic data types are done. They are operations that result in a value. The following are some examples of expressions:

      6 + (10 / 5)      /* Returns the value of dividing 10 by five then adding six to the result.*/

      (37 / 10) * (31 + 3)        /* Returns the value of dividing 37 by 10 and then multiplying it by the result of 31 plus 3.*/

      (value == 8)         /* Returns true if value is equal to 8.*/

      (2 < 4) && (value != 4)       /* Returns true if 2 is less than four and the variable value does not equal 4.*/

      Note that expressions are not listed with semicolons after them because by themselves they are meaningless; their result must be used for something (like a variable assignment). Ex. To make the expression 10/4 a complete statement, you might assign it the variable name of x like this: int x = 10/4;

      Expressions are built out of operators and operands. The three main classes of operators are arithmetic, relational, and logical. An operand is the data that the operator does its work upon. For instance, in the expression 2 + 4, the plus sign (+) is the operator, and the numbers 2 and 4 are the operands.

      Operator 1. Arithmetic Operators

      Java uses infix notation with arithmetic operators, which means that the operators appear between the numbers (or variables). This notation should be quite familiar to you—it's the way math is usually written down, as shown in the following examples:

      int result = 2 + 2 * 10;              // result = 22
      
      int x = 10 / 4;                       // x = 2
      
      int y = 10 * 10;                      // y = 100

      If you want to make sure certain operations are done first, use parentheses. For example, if you wanted to multiply 10 by the result of adding 2 plus 2 but were unsure of the rules of precedence (which operations occur before others), you could write

       (2 + 2) * 10;

      instead of

      2 + 2 * 10

      The parentheses would guarantee you that 2 would be added to 2 before it was multiplied by 10. If you are unsure of what operation takes precedence in an expression, go ahead and group parentheses around the operation you want to happen first.

      Table 1 lists the common arithmetic operators in Java. The four major operations are obvious, but remainder, decrement, and increment need a bit more explanation.

        Table 1. Arithmetic operators.
      Operator
      
      
      Action
      
      

      +

      Addition

      -

      Subtraction

      *

      Multiplication

      /

      Division

      %

      Remainder

      --

      Decrement

      ++

      Increment

      Note on Remainders:
      When two numbers are divided by one another, there is often a remainder. When you use floating-point numbers, this remainder is included in the numbers that follow the decimal point. However, when you do integer division, this remainder is lost. For example in,

      int result = 7 / 3;

      result is equal to 2, but the information that 1 was left over is lost. The Remainder operator (%) allows the remainder to be computed. Thus in,

      int result = 7 % 3;

      is equal to 1 because that is what is left over when 7 is divided by 3.

      A special Arithmetic Operator, Decrements and Increments:
      Addition and subtraction are operations that are done constantly in programming. In fact, 1 is added to or subtracted from a variable so often that this expression has its own operators: increment and decrement. The operator ++ adds (increments) 1 to its operand and -- subtracts (decrements) 1 from its operand. Therefore, the code

      age++;

      is equivalent to

           age = age + 1;

      Increment and decrement are special operators. Normally an operator couldn't appear by itself because it needs to be part of an expression. Either way you write it, each time the compiler goes over that code, it adds(++) or subtracts(--) one to the variable. But you will see increments and decrements alot! They are very useful in loops because loops cause the code to be run over and over again, in this case constantly adding or subtracting one.

      Operator 1. Relational and Logical Operators

      A relational operator is basically a way to compare two things to find out how they relate to one another. For example, you can check to see whether two things are equal to one other or whether one is greater than the another. Table 2 lists the available relational operators.

      For example, to check to see whether age is equal to 29, you would use the == operator:

      int is_twentynine = 29;
      int rhollAge = 47;
      boolean is_twentynine == rhollAge;

      If this expression is true, then the boolean value true is assigned to is_twentynine, otherwise false. As you can see, this boolean returns a false value which makes rholl very unhappy. Note that this is very different than the assignment operator, which is a single equal sign. The assignment operator = sets the value of the variable to the left to the value of the expression on the right, whereas the equal relational operator == checks to see whether the value on the left is equivalent to the value on the right, and if it is, returns true.

        Table 2. Relational operators.
      Operator
      
      
      Action
      
      

      >

      Greater than

      <

      Less than

      >=

      Greater than or equal

      <=

      Less than or equal

      ==

      Equal

      !=

      Not equal

      Quite often it is convenient to be able to do multiple relational tests at the same time. Logical operators (listed in Table 3) make this process possible.

        Table 3. Logical operators.
      Operator
      
      
      Action
      
      

      &&

      And

      ||

      Or

      !

      Negation

      The And (&&) operator returns true only if both of its operands are true. Thus,

           (2 == 2) && (3 < 4)

      evaluates to true, because 2 is equal to 2 and 3 is in fact less than 4. On the other hand,

           (2 == 2) && (3 == 4)

      evaluates to false because 3 is not equal to four. In this case, one of the operands is false so the whole expression is false.

      The Or operator ( || ) is similar except that it evaluates to true if either of its operands are true. Therefore,

           (2 == 2) || (3 == 4)

      evaluates to true because (2 == 2) is true. Note: To create the straight up line(|), the key is in the upper right corner of the main keypad on the same key the has the backslash(\).

      The Negation (!) operator is a bit strange. It takes its operand, which must be a boolean, and gives the opposite boolean value. Therefore, what was true is now false, and what was false is now true. For example,

           !(2 == 2)

      is false because (2 == 2) evaluated to true, and the opposite of true is false.

      The Negation operator is powerful, but it should also be used with care because it can be very confusing to figure out what expressions that contain it mean. You should use this operator only when the meaning of the expression is clear and the mind of the programmer is clear. Needless to say, Rholl is frightened to use the negation operator.


      Arrays

      When declaring variables, it makes sense to have distinct names for them, up to a point. However, suppose you are writing a gradebook program, and you need to keep scores for 50 people in the class. You could have a variable for each: student1, student2, student3, and so on. This amount of variables would get quite unwieldy.

      Arrays are the solution. They allow you to group what would be a large number of different variables with the same type under one name. Arrays enable you to keep things simple when you have a large number of variables that can be grouped together. Note: All variables in an array must be of the same type(int, string, etc.). An array is declared in the following manner:

           int students[];
      
           students = new int[50];

      First, you specify the type of variable that will be contained in the array, which in this case is an integer. Then you name the array (in this case students) and follow it with [], which tells the compiler that this code is an array. Note: You will sometimes see the above written as:

           int[] students;
      
           students = new int[50];

      They are identical statements.

      At this point, you have declared that students will be an array, but you haven't declared how many items will be in it. The next line does that operation:

           students = new int[50];

      This statement creates an array of 50 integers. Then this array of integers is assigned to the variable students. So the variable students is an array of integers.

      When you first declare the array (int students[]; or int[] students;), all you are doing is saying, "This variable will at some point contain an array". That is why the number is not listed in the first declaration of students, but later when the actual array is created. Remember the keyword new. That is the word you use to create an instance of something. In this example you are creating an instance of an existing variable. You use the word new to also create an instance of an existing object of any type in Java.

      The number in the square brackets []that come after new is an index, which is the fundamental thing that separates arrays from other data types. The index of an array is an integer in the range from 0 to the size of the array minus one. This is because although there are 50 objects in the array students, Java starts counting at 0. For instance, the students array would contain the following variables:

      students[0]
      
           students[1]
      
           students[2]
      
               etc...
      
           students[49]

      Each indexed reference to students[] is called an array element and can be treated in exactly the same way as any other variable of a basic data type. The index does not necessarily have to be a constant number; it can also be a variable, as in the following:

      students[currentvalue]

      Perhaps you can see why putting a variable, like currentvalue in an array would be powerful. If you set up a method that set the currentvalue from 0-49, you could use the power of that method to create a program that randomly selected students, or took a student's number and found his/her name, or ...

      If your array is a shorter array, you can declare the array and initialize it at the same time like this:

      String people[] = {"Jeff", "Fred", "Tasha", "George", "Maria"};

      The elements of the array must all be of the same type(in this case of class String) as the type of the variable name.


      Statements and Blocks

      In Java, each conceptual step of the program is known as a statement. For example, both a variable declaration and a variable assignment like the following are statements:

      int age;
      age = 100;

      A statement is followed by a semicolon to let the compiler know that the statement has ended.

      A block is an arbitrary number of statements that are grouped together. The beginning and ending of the block are marked by opening and closing braces, { and } respectively. The following code shows the preceding statements contained within a block:

      {
      
           int age;
      
           age = 100;
      
      }

      Blocks are used a great deal in Java. They are also an integral part of defining object classes when you get to the Java packages and their corresponding classes. Most importantly for syntax, they are also used a great deal in controlling the flow of a program, which is discussed in the next section.


      Program Flow

      Now you have the basics for organizing the syntax of Java statements. Java statements are executed in a linear order, one after another. Flow control statements, as explained in the following sections, let you modify that order. So things like the concept of looping that allow you to loop repeatedly through a section of code come under the category of Program Flow.

      Flow Control 1. If .... Else Statements

      One of the most basic things a program needs to do is to make decisions. Test statements check the result of a boolean relational expression (discussed earlier in this chapter) and decide in which manner the program will continue based upon the result of this expression.

      By far, the most important test statement is if. An if statement has the following form:

           if (Expression) ThingsToDoIfTrue
      
           else ThingsToDoIfFalse

      If the expression is true, the block (or statements) contained in ThingsToDoIfTrue is executed. If the expression is false, the block (or statements) contained in ThingsToDoIfFalse contained after the else is executed. If you just need to do something if the expression is true, the else can be left off.

      Suppose you wanted to add 1 to a variable named counter only if the boolean variable add_one is set to true; otherwise, you wanted to subtract 1 from the variable. The following example does this:

      boolean add_one;
      
      int counter;
      
      add_one = true;
      
      counter = 1;
      
      if (add_one == true)
      
           counter = counter + 1;
      
      else
      
           counter = counter - 1;
      Note: This might be a good place to use the increment and decrement operators discussed earlier operators section above.
      counter--;
      counter++;

      In this example, counter ends up being equal to 2. Why? The expression in the if statement is evaluated first. The program checks to see whether add_one is equal to the boolean value true. In this case, the add_one variable is true, so the program evaluates the second part of the if statement, which adds 1 to counter. If the add_one variable were not true, the statement(s) following the else would have been executed.


      Flow Control 2. Looping

      Java enables you to repeat something over and over again through a construct known as iteration statements. An iteration statement executes a block of code based on whether an expression is true.

      This process is known as looping. A loop occurs in a program when a single block of code is executed more than once. A loop can be set to repeat a definite number of times(a for loop) or a variable number of times(a while or do. . .while loop).

      for loops:
      A for loop repeats a program block a finite number of times based upon a counter. The following sample for loop repeats 10 times:

      for (int i=0; i<10; i = i + 1) {
      
           // Things you want to do
      
      }

      The for loop has three main components:

      1. Initialization sets up the variable that will be checked against in the loop to see whether the loop is executed again. In the preceding example, the initialization component is int i=0.

      2. The test expression determines whether the loop is executed again. In the preceding example, the test expression is i<10, so the loop will continue if i is less than 10.

      3. The increment section lets you change the value of the counter variable. This section usually consists of adding or subtracting 1 from its value, but for flexibility you can give the variable any value that you want. In the preceding example, the increment section is i = i + 1. Note: i=i+1 could also be written as i++.

      A semi-colon is required at the end of components 1 and 2, to tell the Java compiler that this is where the component ends.

      For loops make the most sense when you know ahead of time how many times the loop will need to be executed. For example, if you had a variable result that you wanted to multiply by 3 for 20 times, you could use the following:

      for (int i=0; i<20; i = i + 1) {
      
           result = result * 3;
      
      }
      while loops:
      A while loop is a much more general loop than a for loop. A while loop decides whether to evaluate the loop again based upon whether its expression is true or false. The while loop evaluates the expression again if the result is true and doesn't evaluate the expression again if its result is false. The following example only executes once because value is changed to false once the loop is entered:

      boolean value;
      
      value = true;
      
      while (value == true) {
      
           // Do some work
      
           value = false;
      
      }

      Note that a while loop isn't necessarily executed even once, as the following example demonstrates:

      boolean value;
      
      value = false;
      
      while (value == true) {
      
           // Do some work
      
           value = false;
      
      }

      In this case, the while expression is evaluated and is found to be false right from the beginning, so the code inside the loop is never executed.

      do. . . while loops:
      A do. . .while loop is much like a while loop except that the expression to be tested is contained at the end of the loop rather than at the beginning:

      boolean value;
      
      value = true;
      
      do {
      
           // Do some work
      
           value = false;
      
      } while (value == true)

      Note that in this case the program block is always executed at least once. In general, you should decide between a while and a do. . .while loop based upon whether the test to see whether the loop needs to continue fits more naturally at the beginning or the end of the loop.


      Index Grading Schedule Syntax JavaDocs Video Projects Links