Sunday, February 3, 2019

Java tutorial: Operator precedence, expression,statements, blocks,comments, tokens

References/Links: http://pasted.co/ab27024a

Chapters
Java Precedence Table

Hello everybody! This is brainy ghosts and today we're gonna discuss java operator precedence, expression, statements, blocks and tokens. Let's start with java operator precedence, Take a look at this table.

Precedence Table
This is the precedence table from java documentation I recommend you to open the table on your browser, table link is in the References/Links link.
The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence.

When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

Note: postfix and unary have the same precedence because the postfix(expr++ and expr--) is just the other version of unary(++expr and --expr).

Java Precedence

Create a source file in our workspace folder then name the source file "Precedence", open it on your text editor then write the basic code structure.
Code:
public class Precedence
{

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

}
Alright! Let's start with this expression.
Code:
public class Precedence
{

   public static void main(String[]args)
   {
     int i = 1;
     int j = 3;     

     int intVar = 
     ++i + j++ * 2 - 1 / j << 2;

     System.out.println(intVar);
   }

}
In this example, the result is 32. How's that happened? Here's a step-by-step procedure on how we end up with the result of "32".

Initial value
i = 1; j = 3;

Initial expression
++i + j++ * 2 - 1 / j << 2

Procedure:

#1

i = 2; j = 4

2 + 3 * 2 - 1 / 4 << 2

#2

2 + 6 - 0 << 2

#3

8 << 2

Answer: 32
So, in procedure #1 we first evaluated ++i and j++. In this procedure, the first operand is 2 after we evaluated ++i, then the second operand is 3 after we evaluated j++, why 3? because j++ is a postfix increment. Then, j after the "/" operator is now 4 because j++ increment already took effect.

In procedure #2, we did the multiplication and division, in the division part the result is 0 because 1/4 = 0.25 and since our data type is int then the fractional part is discarded.

In procedure #3, we did the addition and subtraction and the remaining operator is the left shift operator. We evaluated the left shift and the result is 32.

In this procedures, we see the operation precedence in java. So, In summary, we evaluated the postfix and unary in the first procedure, then in the second procedure, we evaluated the multiplicative operators according to the precedence table, then in the third procedure, we evaluated the additive operators and lastly, we evaluated the shifts and ended up with 32.

A more complex example of java precedence

Let's try a more complex expression.
Code:
public class Precedence
{

   public static void main(String[]args)
   {
     int i = 1;
     int j = 3;     

     int intVar = 
     ++i * j++ & 5 + i++ + j++ ^ 5 + ++i / ++j | 5 << 2;

     System.out.println(intVar);
   }

}
In this example, the result is 23.Let's evaluate this expression step-by-step.
Initial value
i = 1; j = 3;

Initial expression
++i * j++ & 5 + i++ + j++ ^ 5 + ++i / ++j | 5 << 2

Procedure:

#1

i = 4; j = 6;

2 * 3 & 5 + 2 + 4 ^ 5 + 4 / 6 | 5 << 2

#2

6 & 5 + 2 + 4 ^ 5 + 0 | 5 << 2

#3

6 & 11 ^ 5 | 5 << 2

#4

6 & 11 ^ 5 | 20

#5

2 ^ 5 | 20

#6

7 | 20

Answer: 23
So, In procedure #1, we need to evaluate postfix and unary. the first operand is 2 after we evaluated ++i and the second is 3 after we evaluated j++, now i = 2 and j = 4. Then, fourth operand is 2 after we evaluated i++ and the fifth operand is 4 after we evaluated ++j, now i = 3 and j = 4. Then, seventh operand is 4 after we evaluated ++i and eighth operand is 6 after we evaluated ++j, now i = 4 and j = 6. This procedure is pretty confusing at first.

In procedure #2, we evaluated the multiplicative operators.

in procedure #3 we evaluated the additive operators.

In procedure #4 we evaluated the shift operators.

In procedure #5 we evaluated the bitwise AND, we skipped the relational and equality operators in the table because we didn't use any of those operators.

In procedure #6, we evaluated the bitwise exclusive OR operator and remaining operator is the inclusive OR operator. We evaluated the remaining operator and the result is 23.

Using parentheses() to group expressions

We can use parentheses to group expressions.Parentheses are the highest priority in java precedence. Expressions that in the parentheses will be evaluated first. We can say that the precedence in java is similar to PEMDAS(Parentheses,Exponent,Multiplication,Division,Addition and Subtraction) that we learned in math class. Let's try to group expressions.
Code:
public class Precedence
{

   public static void main(String[]args)
   {
     int i = 1;
     int j = 3;     

     int intVar = 
     (++i * j++ & 5) + (i++ + j++ ^ 5) + (++i / ++j | 5) << 2;

     System.out.println(intVar);
   }

}
This example is similar to the example above, we just put parentheses. When we compile this the result is 48. Let's evaluate this expression step-by-step.

Initial value
i = 1; j = 3;

Initial expression
(++i * j++ & 5) + (i++ + j++ ^ 5) + (++i / ++j | 5) << 2

Procedure:

#1

i = 2; j = 4;

(2 * 3 & 5) + (i++ + j++ ^ 5) + (++i / ++j | 5) << 2
(6 & 5) + (i++ + j++ ^ 5) + (++i / ++j | 5) << 2
4 + (i++ + j++ ^ 5) + (++i / ++j | 5) << 2

#2

i = 3; j = 5;

4 + (2 + 4 ^ 5) + (++i / ++j | 5) << 2
4 + (6 ^ 5) + (++i / ++j | 5) << 2
4 + 3 + (++i / ++j | 5) << 2

#3

i = 4; j = 6;

4 + 3 + (4 / 6 | 5) << 2
4 + 3 + (0 | 5) << 2
4 + 3 + 5 << 2

#4

12 << 2

Answer: 48
Compound Assignment Operator Precedence

What about compound assignment? Well, the technique to deal with compound assignment is to compute the right side operand first.
Code:
public class Precedence
{

   public static void main(String[]args)
   {
     int i = 1;
     int j = 3;    
     int intVar = 5;
    
     intVar += (++i * j++ & 5) + (i++ + j++ ^ 5) + (++i / ++j | 5) << 2;

     System.out.println(intVar);
   }

}

In this example, the result is 53. So, first, we computed the right expression and the result is 48 then we could expand the compound assignment like this: intVar = intVar + 48;

Expression

Expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. You've already seen examples of expressions, Expressions are like this:


Expression #1: ++i * j++ & 5 + i++ + j++ ^ 5 + ++i / ++j | 5 << 2
Expression #2: int i = 1
Expression #3: "str is equal to str2? " + str.equals(str2)

an expression can be grouped into smaller expressions

(++i * j++ & 5) + (i++ + j++ ^ 5) + (++i / ++j | 5) << 2

By using parentheses, our single expression is now grouped into smaller expressions. Notice that I didn't include ";", that's because if I did then these codes are gonna be statements.

Some expressions need to be a statement in order to function, some be seen in control flow and method parentheses.

Statement

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. A statement ends with ";". There are different kinds of statements : expression statements, declaration statements and control flow statements. These are expression statements.

Statement #1: int intVar = (++i * j++ & 5) + (i++ + j++ ^ 5) + (++i / ++j | 5) << 2;
Statement #2: int i = 1;
Statement #3: int i;
Statement #4: i++;

Statement #1,#2 and #3 can also be called a declaration statement.

Next is declaration statements,declaration statement declares a variable. These are declaration statements.

Statement #1: int intVar = 5;
Statement #2: int i;

Last is the control flow statements, these statements control the order in which statements get executed, they can be either a block or a statement. These are control flow statement/block

Statement #1: if(true) System.out.println("true");
Block #1
if(false)
{
   System.out.print("My ");
   System.out.println();
   System.out.println("Block");

}
Block

Block is a group of zero or more statements between balanced braces,some examples of block that we already saw are classes and methods like the main method. These are blocks.


Block #1
if(false)
{
   System.out.print("My ");
   System.out.println();
   System.out.println("Block");

}
Block #2
public static void main(String[]args)
{
   System.out.print("My ");
   System.out.println();
   System.out.println("Block");
}
Block #3
public class Precedence
{
   int i;
   double j;

   public static void main(String[]args)
   {
 
   }
}
In Block #3, we see that a block can be nested to another block. Although, Some blocks can only be nested to a particular block e.g. a method block can't be nested to another method block and can't be nested in control flow block.

A block can also be in a statement, we can call this a block statement.

Block Statement #1
int[] intArr = new int[]{2,4,6};

Block Statement #2
Runnable run = () -> 
{
  int j = 2;
  for(int i = 1; i < 6;i++)
    {
       j *= i;
       System.out.println(j);
    }
              
};
Java Comments

Comments are used to provide a piece of information about some specific parts of our code, It can also be used to document our code. Comments are not executed by the compiler.

Comment has three forms: the single line(//), multi-line(/* */) and documentation(/** */) comment.

Single line(//) comments are used to comment a single line of code.
e.g. System.out.println("String"); //prints String

Multi-line(/* */) comments are comments that use multiple lines. e.g.
/*
Adds a and b, c and d
Then multiply the result
Then prints the result on the console
*/
System.out.println("Result: " + (a + b) * (c + d));
Documentation(/** */) comments are used in javadoc tool. e.g.
public class Comments
{
  static int a = 1,b = 2,c = 3,d = 4;

  /**
  Adds a and b, c and d.
  Then multiply the result
  and prints the result on the console
  */
  public static void computeAndDisplay()
  {
   System.out.println("Result: " + (a + b) * (c + d));
  }

  public static void main(String[]args)
  {
    Comments.computeAndDisplay();
  }  

}
It looks like multi-line and documentation document are the same, but no, let's create a documentation of this code using the javadoc command. javadoc command generates a myriad of files, so, It is better to isolate our code in one folder.

Create documentation using javadoc command: javadoc Comments.java

After you successfully documented our code, you see a myriad of files, open the index.html or index-all.html then click on our method which is the computeAndDisplay() method. As you can see, our comment is in the documentation of computeAndDisplay().

Now, try changing the documentation comment to a multi-line comment and document the code again, you will see that our comment is not included in the documentation anymore.

Java Tokens

Java tokens are the littlest component in a program that is significant to the compiler. Tokens explicitly define the composition of the language. These are the java tokens.

Identifier: are used to name things like variables, methods, classes, etc.
Keywords: also called reserved keywords are words that are reserved for specific use in java, java has a total of 50 keywords.
Literals: are constant values that are used when assigning an initial value to a variable at a time of code writing.
Separators: are symbols that denote division and order of codes. These are the separators in java:
    • Parentheses():are used in precedence of expression, enclosed cast type and enclosed method paremeter/argument.
    • Braces{}: are used as enclosure to blocks like class and method block, It can also be used to enclose array values.
    • Brackets[]: are used in arrays.
    • Semicolon(;): is used to end and separate statements. It is also used in for statement.
    • Comma(,): is used to separate multiple variable declarations and can be used in for statement.
    • Colon(:): is used in lambda(method/constructor reference), foreach statement, ternary operator, switch statement and assertion.
    • Period(.): is used to separate package names and to get a class/object member like variables, methods, etc.
Operators: are used to operate on some essential task like computing, comparing, bit manipulation, etc.
Comments: are used to comment a portion of a code. It can also be used in java documentation. Comments are not executed by the compiler.

No comments:

Post a Comment