The next Java tutorial gets the basic language out of the way. It’s surprisingly difficult to recall all those primitive types and operator precedence, which is a good reason to use () with the latter so you don’t have to.

Exercises

  1. Language Basics – Variables
  2. Language Basics – Operators
  3. Language Basics – Expressions, Statements, and Blocks
  4. Language Basics – Control Flow Statements

 

Variables

  • Types : java is statically-typed so all variables must be declared before use.
    • Instance Variables ( Non-Static Fields) : values unique to each instance of a class
    • Class Variables (Static Fields) : 1 static class field instance per class. final makes it unmodifiable
    • Local Variables : store state temporarily in a method
    • Parameters
  • Naming Rules & Conventions
    • startWithALowercaseLetterAndCapitalizeSubsequentWords
    • CAPITALIZE_CONSTANTS_AND_USE_UNDERSCORE
  • Primitive Types :  defined by the language and named by a reserved keyword. Special data types built into the language. Not objects created from a class.
    • byte : 8-bit signed two’s complement integer : -128 – 127
    • short : 16-bit signed two’s complement integer : -32,768 – 32,767
    • int : 32-bit signed two’s complement integer : -231 – 231-1. Can be unsigned in Java8 using Integer.
    • long : 64-bit signed two’s complement integer : -263 – 263-1. Can be unsigned in Java8 using Integer.
    • float : single-precision 32-bit IEEE 754 floating point. Refer to Floating-Point Types, Formats, and ValuesUse BigDecimal for currency / precise values.
    • double : double-precision 64-bit IEEE 754 floating point.
    • boolean
    • char : single 16-bit Unicode character. '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
  • Character Strings : Special support for String in java.lang.String. Not strictly a primitive type. String objects are immutable. When you define a string literal, e.g. String s = "this is a string literal"; , a String object is created. The value of the object cannot be changed but the reference can be pointed at another String object.
  • Arrays : length of elements starting at index 0 is fixed at creation.
    int[] anArrayOfIntegers = new int[3];
    int[] anArray = {1, 2, 3};
    int[][] anArrayOfArrays = {
     {1,2,3},
     {1,2,3,4} // rows can be different lengths
    }
    int[][] anArrayOfArrays =new int[2][3];
    anArray.length
    System.arraycopy(copyFromObject, fromPosInt, copyToObject, toPosInt,
    elementsToCopyInt)
    • java.util.Arrays
      • copyOfRange(origArray, fromInt, toInt) : returns array of same type
      • binarySearch: search for index of specific value
      • equals: compare 2 arrays for equality
      • fill: fill array with specific value at each index
      • sort: sort in asc order sequentially
      • parallelSort:faster concurrent sorting of larger arrays on multiprocessor systems
  • Default Values : Variables should be initialized even though Fields are initialized with default values. Local variables are not initialized with a default.
  • Literals : the source code representation of a fixed value
    • Integer Literals : Of type long if ends with L, else int. Number systems:
      int decVal = 26; // decimal - Base 10 : 0-9
      int hexVal = 0x1a // hexadecimal - Base 16 : 0-9, A-F
      int binVal = 0b11010 // binary - Base 2 : 0-1
    • Floating-Point Literals : Of type float if ends with F, else double.
      double d1 = 123.4;
      double d2 = 1.234e2;
      float f1 = 123.4F;
    • Character and String Literals
      • May contain Unicode (UTF-16) characters, e.g. \u0108
      • charliterals use ‘single quotes’
      • Stringliterals use “double quotes”
      • Escape sequences
        • \b : backspace
        • \t : tab
        • \n : line feed : meant move to new line
        • \f : form feed : meant page break
        • \r : carriage return : meant move to beginning of line
        • \"
        • \'
        • \\
      • null : may be assigned to any variable, except primitive types
      • Class literals, e.g. String.class, meaning the object of type Class that represents the type itself.
    • Numeric Literals : You can put _ in the middle of digits, e.g.long creditCardNumber = 1234_5678_9012_3456L;

Operators

Operators Precedence
postfix expr++ expr-- (evaluates to the original result)
unary ++expr --expr +expr -expr ~ (bitwise complement operator : inverts a bit pattern) ! (logical complement)
multiplicative (arithmetic) * / %
additive (arithmetic) + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND && (Conditional-AND)
logical OR || (Conditional-OR)
ternary ? : (someCondition ? value1 : value2)
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
  • Binary operators evaluated from left to right
  • Assignment operators evaluated from right to left

Expressions, Statements, and Blocks

  • Operators may be used in building expressions, which compute values.
  • Expressions are the core components of statements.
    • A construct of variables, operators and method invocations that evaluate to a single value, e.g. result = 1 + 2
  • Expressions that require the same data type can be joined into compound  expressions, e.g. x + y / 100
  • Statements end with a semicolon ;
    • Expression Statements are expressions terminated with a ; e.g.
      // assignment statement
      aValue = 8933.234;
      // increment statement
      aValue++;
      // method invocation statement
      System.out.println("Hello World!");
      // object creation statement
      Bicycle myBike = new Bicycle();
    • Declaration Statements declaring a variable, e.g. double aValue = 8933.234;
    • Control Flow Statements
  • Statements may be grouped into blocks.
  • A Block is a group of zero or more statements between balanced braces {} and can be used anywhere a single statement is allowed.

Control Flow Statements

  • decision-making statements
    • if-then
    • if-then-else
    • switch 
      • byte, short, char, int primitive data types
      • Enum types
      • String
      • Character, Byte, Short, Integer classes wrapping primitive types
      • Offers more execution paths than if-then, if-then-else
      • switch (anInt) { // switch block
                    case 1:  aString= "1"; // no break so will fall through to the next line
                    case 2:  aString= "2";
                             break;
                    case 3: case 4: // multiple case labels that fall through
                    default: aString = "0";
                             break;
                }
        
  • looping statements
    • for
      • for (initializationtermination; increment) {}
      • for (anObject i : anArray) {}
    • while
    • do-while : statements always executed once
  • branching statements
    • break
      • unlabeled break statement terminates the innermost switch, for, while, do-while
      • labelled break statement terminates the outermost labelled statement
            int[][] arrayOfInts = { 
                    { 32, 87},
                    { 12 },
                };
            int i; int j = 0;
        
            search: // label
                for (i = 0; i < arrayOfInts.length; i++) {
                    for (j = 0; j < arrayOfInts[i].length; j++) {
                        if (arrayOfInts[i][j] == 12) {
                            break search; // break to outermost
                                          // for loop label
                        }
                    }
                }
    • continue
      • unlabeled continue statement skips to the end of the innermost for, while, do-while
      • labelled continue statement skips to the end of the outer loop marked with the label
        test:
          for (int i = 0; i <= max; i++) {
            int n = substring.length();
            int j = i;
            int k = 0;
            while (n-- != 0) {
              if (searchMe.charAt(j++) != substring.charAt(k++)) {
                continue test; // skip to end of loop labelled with test
              }
            }
            foundIt = true;
            break test;
          }
        
    • return

Exercises

1. Language Basics – Variables

Questions

  1. The term “instance variable” is another name for Non-Static Field.
  2. The term “class variable” is another name for Static Field.
  3. A local variable stores temporary state; it is declared inside a method.
  4. A variable declared within the opening and closing parenthesis of a method signature is called a parameter.
  5. What are the eight primitive data types supported by the Java programming language? byte, short, int, long,  float, double, char, boolean
  6. Character strings are represented by the class java.lang.String.
  7. An array is a container object that holds a fixed number of values of a single type.

Exercises

  1. Create a small program that defines some fields. Try creating some illegal field names and see what kind of error the compiler produces. Use the naming rules and conventions as a guide.
  2. In the program you created in Exercise 1, try leaving the fields uninitialized and print out their values. Try the same with a local variable and see what kind of compiler errors you can produce. Becoming familiar with common compiler errors will make it easier to recognise bugs in your code.

 

2. Language Basics – Operators

Questions

  1. Consider the following code snippet.
    arrayOfInts[j] > arrayOfInts[j+1]
    

    Which operators does the code contain? additive, relational greater than

  2. Consider the following code snippet.
    int i = 10;
    int n = i++%5;
    
    1. What are the values of i and n after the code is executed? i=11 n=0 : postfix has the highest precedence so i++ is executed first BUT postfix returns the original value so the remainder equation is 10%5 instead of 11%5. The postfix increment only happens when the program moves to the next line.
    2. What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))? i=11 n=1
  3. To invert the value of a boolean, which operator would you use? ! logical complement
  4. Which operator is used to compare two values, = or == ? ==
  5. Explain the following code sample: result = someCondition ? value1 : value2;

If someCondition assign value1 to result else assign value2

Exercises

  1. Change the following program to use compound assignments:
    class ArithmeticDemo {
    
         public static void main (String[] args){
              
              int result = 1 + 2; // result is now 3
              System.out.println(result);
    
              result = result - 1; // result is now 2
              result -= 1;
              System.out.println(result);
    
              result = result * 2; // result is now 4
              result *= 2;
              System.out.println(result);
    
              result = result / 2; // result is now 2
              result /= 2;
              System.out.println(result);
    
              result = result + 8; // result is now 10
              result += 8;
              result = result % 7; // result is now 3
              result %= 7;
              System.out.println(result);
         }
    }
    
    
  2. In the following program, explain why the value “6” is printed twice in a row:
    class PrePostDemo {
        public static void main(String[] args){
            int i = 3;
            i++;
            System.out.println(i);    // "4"
            ++i;                     
            System.out.println(i);    // "5"
            System.out.println(++i);  // "6"
            System.out.println(i++);  // "6"
            System.out.println(i);    // "7"
        }
    }

    The prefix ++ operator increments i to 6 before it is printed out. The postfix ++ operator increments i after it is printed out so it is still 6.

3. Language Basics – Expressions, Statements, and Blocks

Questions

  1. Operators may be used in building expressions, which compute values.
  2. Expressions are the core components of statements.
  3. Statements may be grouped into blocks.
  4. The following code snippet is an example of a compound expression.
     1 * 2 * 3
    
  5. Statements are roughly equivalent to sentences in natural languages, but instead of ending with a period, a statement ends with a semicolon ;.
  6. A block is a group of zero or more statements between balanced braces {} and can be used anywhere a single statement is allowed.

Exercises

Identify the following kinds of expression statements:

  • aValue = 8933.234; // assignment statement
  • aValue++; // increment statement
  • System.out.println("Hello World!"); // method invocation statement
  • Bicycle myBike = new Bicycle(); // object creation statement

4. Language Basics – Control Flow Statements

Questions

  1. The most basic control flow statement supported by the Java programming language is the if-then statement.
  2. The switch statement allows for any number of possible execution paths.
  3. The do-while statement is similar to the while statement, but evaluates its expression at the bottom of the loop.
  4. How do you write an infinite loop using the for statement? for ( ; ; ; ) {}
  5. How do you write an infinite loop using the while statement? while (true) {}

Exercises

  1. Consider the following code snippet.
    if (aNumber >= 0)
        if (aNumber == 0)
            System.out.println("first string");
    else System.out.println("second string");
    System.out.println("third string");
    
    1. What output do you think the code will produce if aNumber is 3?
        second string
        third string
      
    2. Write a test program containing the previous code snippet; make aNumber 3. What is the output of the program? Is it what you predicted? Explain why the output is what it is; in other words, what is the control flow for the code snippet?  The first if is true as 3 >= 0 and control passes to the 2nd if. The 2nd if and else are treated as an if-else statement. The final println is always executed and is outside any if statement. This example is trying to demonstrate a nested if. It makes more sense with aNumber = -1 as this proves the first if  is not isolated and actually controls the execution of the if-else block. With -1 the output is:
      third string
      
    3. Using only spaces and line breaks, reformat the code snippet to make the control flow easier to understand.
              if (aNumber >= 0)       
                if (aNumber == 0)
                  System.out.println("first string");        
                else 
                  System.out.println("second string");        
              
              System.out.println("third string");
      
    4. Use braces, { and }, to further clarify the code.
              if (aNumber >= 0) {
                if (aNumber == 0) { 
                  System.out.println("first string");        
                } else  {
                  System.out.println("second string");        
                }
              }
              System.out.println("third string");
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s