Java Syntax Review and Exercises


Comments

Let's take a look at a simple Java program without any real code:

public class SyntaxExample1 {

  public static void main (String[] argv) 
  {
  }
  
}

NOTE:

Next, let us add some comments:

// Comment1 

public class SyntaxExample2 {

  // Comment2 

  public static void main (String[] argv) 
  {
    // Comment3 
  }
  
}

NOTE:

Next, let's play around with the program to highlight a few syntax issues:

Exercise 0.1: The following program will not compile. Why? And what kind of error is identified by the compiler?

public class SyntaxExample2 {

  //  
    Comment1

  public static void main (String[] argv) 
  {
    // Comment // Comment 
  }
  
}
 

Exercise 0.2: Is whitespace allowed between array brackets?

public class SyntaxEx2 {

  public static void main (String [
     ] argv) 
  {
  }
  
}
 

Java programs are case-sensitive. The following program will not compile:

Public class SyntaxExample3 {

  public static void main (String[] argv) 
  {
  }
  
}
This is because the Java reserved word public is mis-spelt as Public.

Notice that the error produced above by the compiler is:

  SyntaxExample3.java:2: Class or interface declaration expected.
  Public class SyntaxExample3 {
  ^
  1 error
Thus, the compiler does not know you mis-typed.

Let us now deliberately mis-type a few different words in the program to see what compiler errors are produced (so we learn to recognize the problem).

Exercise 0.3: What is the error produced by compiling this program?

public Class SyntaxEx3 {

  public static void main (String[] argv) 
  {
  }
  
}
 

Exercise 0.4: What is the error produced by compiling this program?

public class sYnTaXEx4 {

  public static void main (String[] argv) 
  {
  }
  
}
 

HelloWorld

Consider the classic helloworld program in Java: (source file)

public class HelloWorld {
  public static void main (String[] argv)
  {
    System.out.println ("Hello World!");
  }
}
 

The main syntactic elements are:

  • Java reserved words such as: public, class, static, void.
  • Method (procedure or function) names: main, println.
  • Names of variables and objects, such as System, String, HelloWorld, argv and out.
  • Delimiters for the class, and the method main.
  • An end-of-statement symbol, the semicolon.
  • Parentheses for enclosing method parameters (arguments).
  • A string literal, Hello World!.
  • Array brackets []

Next, let us get accustomed to errors produced by the compiler when the syntax is incorrect.

Exercise 0.5: What errors are reported by the compiler with this program?

public class SyntaxEx6  // Left out the opening brace 
  public static void main (String[] argv)
  {
    System.out.println ("Hello World!");
  }
}
 

Exercise 0.7: What errors are reported by the compiler with this program?

public class SyntaxEx7 {
  public static void main (String[] argv)
  {
    System.out.println (Hello World!");   // Forgot the first double-quote " 
  }
}
 

Exercise 0.8: What errors are reported by the compiler with this program?

public class SyntaxEx8 {
  public static void main (String[] argv)
  {
    System.out.println ("Hello World!")   // No semicolon 
  }
}
 

Exercise 0.9: What errors are reported the compiler with this program?

public class SyntaxEx9 {
  public static void main (String[] argv)
  {
    System .out.println ("Hello World!");   
  }
}
 

Exercise 0.10: Try to compile and run this program.

public class SyntaxEx10 {
  public static void main () // Removed parameters in method definition 
  {
    System.out.println ("Hello World!");   
  }
}
 

Data types and Identifiers

Java has 8 "built-in" data types: byte, short, int, long, float, double, boolean, char.

Let us examine some code with only int's to get started: (source file)

public class SyntaxExample4 {

  public static void main (String[] argv) 
  {
    // Declare an integer variable called "i". 
    int i;

    // Assign it a value. Note the assignment operator "=" 
    i = 5;

    // Print out its value to the screen. 
    System.out.println (i);
  }

}
  

Next, let's play around with the syntax and observe what the compiler reports.

Exercise 0.11: Try to compile and run this program.

public class SyntaxEx11 {

  public static void main (String[] argv) 
  {
    // Forgot to declare "i" 

    // Assign it a value. Note the assignment operator "=" 
    i = 5;

    // Print out its value to the screen. 
    System.out.println (i);
  }
  
}
 

Exercise 0.12: Try to compile and run this program.

public class SyntaxEx12 {

  public static void main (String[] argv) 
  {
    // Declare an integer variable called "i". 
    int i;

    // Wrong assignment operator 
    i := 5;

    // Print out its value to the screen. 
    System.out.println (i);
  }
  
}
 
NOTE:

  • Good programming style requires that variable names be chosen for readability.

  • Variable names like i are usually only appropriate for loop (control) variables.

  • What kinds of variable names are allowed?
    The rules that apply to variable names also apply to method, parameter and object names, the so-called identifiers.

About identifiers:

  • An identifier must begin with a letter or underscore

  • An identifiers can contain any number of letters, digits, or underscores.

  • Case (upper or lower) is significant.

  • No Java reserved word can be used as an identifier.

  • Identifiers can actually be more complex when using Unicode characters, allowing currency symbols. But these are best avoided.

  • Examples of legal identifiers:
    i
    really_important_integer_for_counting_lines_in_a_text_file (bad style)
    num_lines_in_file (acceptable)
    numLinesInFile (recommended)

More about variable declaration syntax:

  • Variables can be assigned values in a declaration: (source file)
    public class SyntaxExample5 {
    
      public static void main (String[] argv) 
      {
        // Declare and initialize i 
        int i = 5;
    
        // Print out its value to the screen. 
        System.out.println (i);
      }
    
    }
      
  • Declarations can occur anywhere in a program body (source file)
    public class SyntaxExample6 {
    
      public static void main (String[] argv) 
      {
        System.out.println ("Value of i is: ");  
    
        // Declare and initialize i 
        int i = 5;
    
        System.out.println (i);
      }
    
    }
      
  • Multiple variables (of the same type) can be declared in a single statement: (source file)
    public class SyntaxExample7 {
    
      public static void main (String[] argv) 
      {
        // Declare multiple variables of the same type. 
        int i = 5, j = 6, k;
    
        k = 7;
    
        System.out.println (i);
        System.out.println (j);
        System.out.println (k);
      }
    
    }
      

    The preferred style is either:

    public class SyntaxExample7 {
    
      public static void main (String[] argv) 
      {
        // Declare multiple variables of the same type. 
        int i = 5;  // i is the variable that .... 
        int j = 6;  // j ... 
        int k = 7;  // k ... 
    
        System.out.println (i);
        System.out.println (j);
        System.out.println (k);
      }
    
    }
      
    or
    public class SyntaxExample7 {
    
      public static void main (String[] argv) 
      {
        // Declare multiple variables of the same type. 
        int 
          i = 5,  // i is the variable that .... 
          j = 6,  // j ... 
          k = 7;  // k ... 
    
        System.out.println (i);
        System.out.println (j);
        System.out.println (k);
      }
    
    }
      

Let us "clean up" the above program a little: (source file)

public class SyntaxExample8 {

  public static void main (String[] argv) 
  {
    int numGoals = 5;         // Number of goals scored 
    int numAssists = 6;       // Number of assists 
    int numShotsBlocked = 7;  // Number of shots blocked 

    System.out.println (" Goals scored=" + numGoals + " Assists=" + numAssists
                        + " Shots-blocked=" + numShotsBlocked);
  }

}
 

Note:

  • The + operator is used to concatenate strings with variables and other strings.

  • The data type that eventually goes into the println method is a string.

More Data Types

While there are seven additional data types, we will first focus on a few:

  • double
    • Use double to store floating point numbers, as in: (source file)
      public class SyntaxExample9 {
      
        public static void main (String[] argv) 
        {
          double 
            pi = 3.14159,      // The constant Pi 
            radius = 2.0E03,   // Circle radius 
            area = 0;          // Area, not yet computed. 
      
          area = pi * radius * radius;
      
          System.out.println ("Area of circle with radius " + radius + " is: " + area);
        }
      
      }
       
    • double constants are decimal values (3.14159), or in exponent notation (2.0E03).

  • char
    • A char variable holds a single character, e.g., (source file)
      public class SyntaxExample10 {
      
        public static void main (String[] argv) 
        {
          char 
           initial1 = 'J',
           initial2 = 'F',
           initial3 = 'K';
      
          System.out.println ("Initials: " + initial1 + initial2 + initial3);
        }
      
      }
       
    • "Backslash" combinations are used to represent special characters: (source file)
      public class SyntaxExample11 {
      
        public static void main (String[] argv) 
        {
          char initial1 = 'J';
          char initial2 = 'F';
          char initial3 = 'K';
          char newline = '\n';
          char tab = '\t';
      
          System.out.println (newline + "Initials: \'" + initial1 + tab +
                              initial2 + tab + initial3 + "\'");
        }
      
      }
       
    • Notice the quote character inside the string "Initials: \'".

  • boolean
    • boolean variables take the values true or false: (source file)
      public class SyntaxExample12 {
      
        public static void main (String[] argv) 
        {
          boolean tastesGreat = false;
          boolean lessFilling = true;
          boolean either;
          boolean both;
      
          either = tastesGreat || lessFilling;
          both = tastesGreat && lessFilling;
      
          System.out.println ("either=" + either + " both=" + both);
        }
      
      }
       

  • Strings
    • Strings are not really primitive data types.
    • Strings are objects, but are treated a little differently because of the concatenation operator.
    • We will understand more about the details once we understand objects.
    • Example: (source file)
      public class SyntaxExample13 {
      
        public static void main (String[] argv) 
        {
          String str1 = "Hello";
          String str2 = "World!";
      
          // Concatenation 
          String str3 = str1 + " " + str2;  
      
          System.out.println (str3);
        }
      
      }
       

Casting

Casting is the term used to convert a value of one data type to a value of another data type. For example: (source file)

public class SyntaxExample14 {

  public static void main (String[] argv) 
  {
    int i = 5, j = 6;
    double x = 2.718,  y = 3.141;

    // Implicit cast: 
    x = i;
    System.out.println ("x = " + x);   // Prints 5 
    
    // Explicit cast: 
    j = (int) y;
    System.out.println ("j = " + j);   // Prints 3 
  }

}
 

Exercise 0.13: What does the following program print out?

public class SyntaxEx13 {

  public static void main (String[] argv) 
  {
    System.out.println ( ( (double) (int) 3.141 ) );
  }
  
}
 

Expressions

Arithmetic expressions:

  • Many arithmetic expressions in Java are common to most programming languages:, e.g.,
       x = ( (a / b) * (c - d) ) + e;
      

  • It's considered good style to delineate arithmetic expressions with parentheses, where appropriate, to help with readability.

  • C/C++ programmers will be familiar with operators like post-increment and "assignment with operator", e.g.,
       i = 0; 
       i += 1;         // Same as i = i + 1; 
       A[++i] = 0;     // A[2] = 0 because i is first incremented and then used 
      

  • Other arithmetic operators include:
    / Integer division
    % Integer remainder

    Note: bitwise arithmetic operators include the shift operators:
    >> Right shift
    << Left shift
    >>> Unsigned right shift

Exercise 0.14: What does the following program print out?

public class SyntaxEx14 {

  public static void main (String[] argv) 
  {
    byte k = 13;

    for (int i=0; i<8; i++) {
      System.out.print (k % 2);
      k >>= 1;
    }
    System.out.println();
  }
  
}
 

Boolean expressions:

  • Boolean operators include:
    && AND
    || OR
    ! NOT
    & Bitwise AND
    | Bitwise OR
    ^ Bitwise XOR
  • Examples of boolean expressions used in if statements: (source file)
        if (i == 10) 
          System.out.println ("i is equal to 10");
        
        if ( !(i == 10) )
          System.out.println ("i is not equal to 10");
        
        if (i < 10) 
          System.out.println ("i is less than 10");
        
        if ( (i >= 5) && (i <= 10) )
          System.out.println ("i is between 5 and 10");
             
        if ( (i >= 5) && (i != 6) )
          System.out.println ("i larger than 6");
       

Statements

Finally, we will examine some basic Java statements. The following is not meant to be exhaustive, but rather, a quick introduction to the most commonly used statements:

  • Assignment:
    • Assignment statements use the assignment operator =, e.g.,
             x = 5;                 // Simple assignment. 
             y = getInputValue();   // Assign a function's return value. 
             z = (x + y) / y;       // Assign an expression value. 
           
    • Assignment can be combined with many operators, e.g.,
             x += 5;    // Add 5 to x 
           
    • Assignments can be grouped:
             x = y = z = 0;     // All are given the value 0. 
           

  • if-statement:
    • An if-statement is the keyword if followed by a boolean expression in parentheses, followed by a statement.
    • Example:
             if (x < 5) 
               System.out.println ("x is less than 5");
           

  • compound-statement:
    • Compound statements are groups of statements placed in a single block.
    • A block is delineated with braces.
    • Example:
             if (x < 5) {       // Start of block 
               y = 5;
               z += x;
             }                  // End of block 
           
    • Example:
             if (x < 5) {       // Start of outer block 
               y = 5;
               z += x;
               if (z > 10) {      // Start of inner block 
                 z = z - 1;
                 w = z * z;
               }                  // End of inner block 
             }                  // End of outer block 
           

  • if-else and if-else-if statements:
    • Example of if-else
             if (x < 5) {
               System.out.println ("x is less than 5");
             }
             else {
               System.out.println ("x is not less than 5");
             }
           
    • Example of if-else-if
             if (x < 5) {
               System.out.println ("x is less than 5");
             }
             else if (x > 5) {
               System.out.println ("x is greater than 5");
             }
             else if (x == 5) {
               System.out.println ("x is equal to 5");
             }
             else {
               // Logically impossible! 
             }
           

  • while loop:
    • Example:
           System.out.println ("Countdown: ");
           i = 10;
           while (i >= 1) {           // Start of while-body 
             System.out.println (i);
             i--;
           }                          // End of while-body 
           
    • Any boolean expression is syntactically valid for the while-test expression (i.e., in place of i >= 1).

  • for loop:
    • Example:
           System.out.println ("Countdown: ");
           for (int i=10; i>=1; i--) {           // Start of for-body 
             System.out.println (i);
           }                                     // End of while-body 
           
    • The loop-header first has a statement (int i = 10) then a boolean expression (i>=1), followed by another statement (i--), each separated by a semi-colon.
    • Note: for-loop variable(s) can be defined in the loop-header itself.
    • Each statement (first, and third parts) can consist of multiple comma-separated statements:
           System.out.println ("Weird countdown/up: ");
           for (int i=10, j=1; ( (i>=1) && (j<=10) ); i--, j++) { 
             System.out.println ("i=" + i + " j=" + j);
           }                                     
           
    • Sometimes, the flexibility offered by the for-loop can be taken too far, making some code examples difficult to read: (source file)
           System.out.println ("Really weird countdown/up: ");
           for (countInitializer (i,10), countInitializer (j,1); 
                checkCountGreaterEqual (i, 1) && checkCountLessEqual (j, 10);
                incrementCount (i, -1), incrementCount (j, 1)) {
             System.out.println ("i=" + i + " j=" + j);
           }                                     
          

Exercise 0.15: What is the error in the following if statement?

    if (i = 5)
      System.out.println ("i is equal to 5");
 

Exercise 0.16: What is the error in the following code?

   int i = 10;
   while (i >= 1)
     System.out.println (i);
     i--;
 

Methods

Other languages call them "procedures" or "functions". Java calls them methods:

  • A method refers to both a procedure (doesn't return a value) or a function (does return a value).

  • A method that does not return a value returns a void value.

  • Every method must have a return type (void, if it doesn't return a value).

  • A method declaration has a bunch of modifiers, followed by a return type, followed by the name, followed by parameter declarations.

  • Example of a simple (static) method declaration: (source file)
    public class SyntaxExample18 {
    
      public static void printHello ()
      {
        System.out.println ("Hello World!");
      }
      
    
      public static void main (String[] argv) 
      {
        printHello();
      }
    
    }
       
    Note:
    • The method printHello() has no parameters.
    • The return type is void.
    • (Less relevant at this time). The modifiers are public, static.

  • Example with parameters and return values: (source file)
    public class SyntaxExample19 {
    
      public static int squareIt (int inputInteger)
      {
        int squareValue = inputInteger * inputInteger;
        return squareValue;
      }
      
      public static void main (String[] argv) 
      {
        int i = 5;
        int j = squareIt (i);
        System.out.println ("The square of " + i + " is " + j);
      }
    
    }
      
    Note:
    • The method squareIt() takes one int parameter and returns an int.
    • The return-statement is the keyword return followed by an expression whose type is the same as the return type.

  • Let's consider some variations of the previous example to illustrate a few points:
    • The return-expression can be of any type that can be cast into the return type, e.g, (source file)
      public class SyntaxExample20 {
      
        public static int squareIt (int inputInteger)
        {
          double squareValue = inputInteger * inputInteger;
          return (int) squareValue;                          // Cast to return type 
        }
        
        public static void main (String[] argv) 
        {
          int i = 5;
          int j = squareIt (i);
          System.out.println ("The square of " + i + " is " + j);
        }
      
      }
        
    • We can "tighten" the code in two ways: (source file)
      public class SyntaxExample21 {
      
        public static int squareIt (int inputInteger)
        {    
          return (inputInteger * inputInteger);   
        }
        
        public static void main (String[] argv) 
        {
          int i = 5;
          System.out.println ("The square of " + i + " is " + squareIt(i) );
        }
      
      }
        

Exercise 0.17: What happens if you leave out the keyword static in the definition of squareIt() below?

public class SyntaxEx17 {

  public static int squareIt (int inputInteger)
  {    
    return (inputInteger * inputInteger);   
  }
  
  public static void main (String[] argv) 
  {
    int i = 5;
    System.out.println ("The square of " + i + " is " + squareIt(i) );
  }

}
 

Exercise 0.18: What is the compiler error in this program?

public class SyntaxEx18 {

  public static int squareIt (int inputInteger)
  {    
    if (inputInteger >= 0)
      return (inputInteger * inputInteger);   
  }
  
  public static void main (String[] argv) 
  {
    int i = 5;
    System.out.println ("The square of " + i + " is " + squareIt(i) );
  }

}
 

Exercise 0.19: Is it possible for a method to return a value, but that the value not be used?

public class SyntaxEx19 {

  public static int squareIt (int inputInteger)
  {    
    return (inputInteger * inputInteger);   
  }
  
  public static void main (String[] argv) 
  {
    int i = 5;
    squareIt (i);    // Return value not used. 
  }

}