Menus

Jul 22, 2016

Java Operators and Control Statements

Course Contents:

  1. Arithmetic operators
  2. Bitwise operator
  3. Boolean logical operator
  4. Relational operator
  5. Assignment operator
  6. The ?: Operator
  7. Operator precedence
  8. Java selection statements
  9. Iteration statements
  10. Jump statements

Operator

An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. Java operators can be classified into a number of related categories as below:

1. Arithmetic operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following are the arithmetic operators:
+, -, *, /, %, ++, +=, -=, *=, /=, %=, --.

The operands of the arithmetic operators must be of a numeric type.















2. Relational operators
a. <, >, <=, >=, = =, !=
b. = = is the equality operator not (=)
c. != is not equal to

WAP that demonstrate the concept of relational operators

class RelationalOperators
{
 public static void main(String args[])
{
 int a=10,b=12,c=10;
System.out.println("a=" + a);
System.out.println("b=" + b);
System.out.println("c=" + a);
System.out.println("a<b is " + (a<b));
System.out.println("a>b is " + (a>b));
System.out.println("a==c is " + (a==c));
System.out.println("a<=c is " + (a<=c));
System.out.println("a>=b is " + (a>=b));
System.out.println("b!=c is " + (b!=c));
System.out.println("b==a+c is " + (b==a+c));

 }
}

 Output:
a=10
b=12
c=10
a<b is true
a>b is false
a==c is true
a<=c false
a>=b is false
b!=c is ture
b==a+c is false

3. Logical operators
a. Logical AND (&&), Logical OR (||)
b. Logical NOT (!)
c. The logical operations return a 1 (true) or 0 (false)
d. For any conditional test, any non zero value is true and a zero is false
e. A common error is using the assignment operator = when the logical operator = = is required, e.g (x = 2) instead of (x = = 2); both are valid expressions, so the compiler will not indicate an error.

4. Assignment operators
a. =, +=, -=, *=, /=

5. Increment and decrement operators

There are two operators ++ and – known as increment and decrement operators respectively.
 increase by 1 x++, ++x ++
- - decrese by 1 x--, --x
Postfix: like x++ or x-- -> first assign then evaluate.
Prefix: Like ++x or –x -> first evaluate then assign
Precision is equal

WAP that demonstrate the increment operator
Class Increment  {
 Public static void main(String args[])
 {
 int a =1;
 int b =2;
 int c ;
 int d;
 c = ++b;
 d =a++;
 c++;
 System.out.println(“a=” +a);
 System.out.println(“b=” +b);
 System.out.println(“c=” +c);
 System.out.println(“d=” +d);
}
}

Output
a = 2
b = 3
c = 4
d = 1

6. Conditional operator (?:)
Types of operators (on the basis of number of operands) Depending on the number of operand used by an operator all the operators can be categories into three categories.

1. Unary operator: if an operator required only one operand then it is called unar y operator.
For example: negation ( - ), increment (++), decrement (--) etc.

2. Binary operator: if an operator required two operands to perform its action then it is known as binary operator. For example: arithmetic, relational, logical etc.

3. Ternary operator: if an operator required three operands to perform its action then it is known as ternary operator. Eg: conditional operator.
The ternary operator pair “?:” is used in java to construct the conditional expressions of the form exp1 ? exp2 : exp3; where exp1, exp2 and exp3 are expressions.

The working principle of ternary operator is as follows:
  1. First the exp1 is evaluated first. If it is true, then the exp2 is evaluated and becomes the value of the expression.

2. If exp1 is false, exp3 is evaluated and its value becomes the value of expression. i.e only one of the expressions (either exp2 or exp3) is evaluated.  



 eg. a = 10;
 b = 15;
 x = (a>b) ? a : b;
this is same as:
 if (a>b)
 x = a;
 else
 x = b;



7. Bitwise operators
Java support several bitwise operators which can be used to the integer types, long, int, short, char and byte. These operators act upon the individual bits of their operands. The bitwise operators in java are given below.

Operator
Description
~
Bitwise unary NOT
&
Bitwise AND
|
Bitwise OR
^
Bitwise Exclusive OR
>> 
Shift right
>>> 
Shift right zero fill
<< 
Shift left
&=
Bitwise AND assignment
|=
Bitwise OR assignment
^=
Bitwise exclusive OR assignment
>>=
Shift right assignment
>>>=
Shift right zero assignment
<<=
Shift left assignment

Operator precedence
Each and every operator in java as a precedence associated with it. This precedence is used to determine how an expression having more than one operator is evaluated.

There are distinct levels of precedence and every operator belongs to one of these levels. The operator at the higher level of precedence are evaluated first and the operators of the same precedence are evaluated either form left to right or from right to left, depending on the level.

This is known as the associativity property of an operator.

Operator Associativity Rank
(), [] Left to right 1
 ++,--, ~,! Right to left 2
*, /, % Left to right 3
+, - Left to right 4
>>, >>>, << ,, 5
>, >=, <, <= ,, 6
==, ! = ,, 7
& ,, 8
^ ,, 9
| ,, 10
&& ,, 11
|| ,, 12
?: Right to left 13
= ,, 14

Table: precedence of java operators
Control Statements
The control statements are used to control the flow of execution of the program. This execution order depends on the supplied data values and the conditional logic. Java contains the following types of control statements:

1- Selection Statements
2- Repetition Statements
3- Branching Statements

Java Selection Statement

Java supports selection statements. These statements are used to control the flow of program execution based upon the condition known at runtime. Java selection statements are also known as control or branching or decision making statements. Java supports following selection statements:
1. If statement
2. Switch statement

1. The if statement:
The if statement is a powerful decision making statement and it is used to control the flow of execution of statements. It is the two-way statement and is used in conjunction with a test condition. The general form of if statement is:

Syntax:
 if(conditional_expression){
 <statements>;
 ...;
 ...;
}
 Here, if is a keyword and the condition following the keyword if is always enclosed within the pair of parenthesis. The value of test condition may be true (non zero) or false (zero). The if statement allow the computer to test the condition first and depending on whether the value of the condition is true or false, it transfer the control to a particular statement. The if statement has two paths: one for the true condition and other for false condition. The if statements may be of different forms depending upon the complexity of conditions to be tested. Which are:

1. Simple if statement
2. if-else statement
3. Nested if-else statement
4. else-if ladder statement

Switch Case Statement
The switch case statement, also called a case statement is a multi-way branch with several choices. It is easier to implement than a series of if/else statements.

The switch statement begins with a keyword switch followed by an expression that evaluates to a no long integral value.

Following the controlling expression is a code block that contains zero or more labeled cases.

Each label must equate to an integer constant and each must be unique. When the switch statement executes, it compares the value of the controlling expression to the values of each case label.

The program will select the value of the case label that equals the value of the controlling expression and branch down that path to the end of the code block. If none of the case label values match, then none of the codes within the switch statement code block will be executed.

Java includes a default label to use in cases where there are no matches. We can have a nested switch within a case block of an outer switch.
Its general form is as follows:

switch (<non-long integral expression>) {
case label : <statement >
1 1
case label : <statement >
2 2
case label : <statement >
n n
default: <statement>
} // end switch

When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the middle of the switch statement code block, you must insert a break statement, which causes the program to continue executing after the current code block.

class SwitchDemo {
 public static void main(String[] args) {
 int month = 8;
 switch (month) {
 case 1: System.out.println("January"); break;
 case 2: System.out.println("February"); break;
 case 3: System.out.println("March"); break;
 case 4: System.out.println("April"); break;
 case 5: System.out.println("May"); break;
 case 6: System.out.println("June"); break;
 case 7: System.out.println("July"); break;
 case 8: System.out.println("August"); break;
 case 9: System.out.println("September"); break;
 case 10: System.out.println("October"); break;
 case 11: System.out.println("November"); break;
 case 12: System.out.println("December"); break;
 default: System.out.println("Invalid month.");break;
 }
 }
}

Output:
August


Repetition Statements

while loop statements:
This is a looping or repeating statement. It executes a block of code or a statement till the given condition is true. The expression must be evaluated to a boolean value. It continues testing the condition and executes the block of code. When the expression results to false control comes out of loop.

Syntax:
 while(expression){
 <statement>;
 ...;
 ...;
 }

Example: Java program that prints numbers from 1 to 10 using while repetition statement.
int i = 1;

//print 1 to 10

while (i <= 10){

 System.out.println("Num" + i);

 i++;
 }


do-while loop statements:

This is another looping statement that tests the given condition past so you can say that the do-while looping statement is a past-test loop statement. First the do block statements are executed then the condition
given in while statement is checked. So in this case, even the condition is false in the first attempt, do block of code is executed at least once.

Syntax:
 do{
 <statement>;
 ...;
 ...;
 }while (expression);

Print numbers from 1 to 10 using do-while statement.
int i = 1;
do{
 System.out.println("Num: " + i);
 i++;
}while(i <= 10);

for loop statements:
This is also a loop statement that provides a compact way to iterate over a range of values. From a user point of view, this is reliable because it executes the statements within this block repeatedly till the specified conditions is true .

Syntax:
 for (initialization; condition; increment or decrement){
 <statement>;
 ...;
 ...;
 }

initialization: The loop is started with the value specified.

condition: It evaluates to either 'true' or 'false'. If it is false then the loop is terminated.

increment or decrement: After each iteration, value increments or decrements.

Print values 1 to10 on the screen.
for (int num = 1; num <=
10; num++){


System.out.println("Num: " + num);
}
Branching Statements

Break statements:

The break statement is a branching statement that contains two forms: labeled and unlabeled. The break statement is used for breaking the execution of a loop (while, do-while and for). It also terminates the switch statements.

Syntax:
 break; // breaks the innermost loop or switch statement.
 break label; // breaks the outermost loop in a series of nested loops.

Example: Java program that demonstrate the concept of break statement.
In the above program when if statement evaluates to true it prints "data is found" and comes out of the loop and executes the statements just following the loop.

Continue statements:
This is a branching statement that are used in the looping statements (while, do-while and for) to skip the current iteration of the loop and resume the next iteration.  
Syntax:
 continue;



Example:


Return statements
It is a special branching statement that transfer the control to the caller of the method. This statement is used to return a value to the caller method and terminates execution of method. This has two forms: one that returns a value and the other that cannot return. The returned value type must match the return type of method.

Syntax:
 return;
 return values;

return; // This returns nothing. So this can be used when method is declared with void return type.

return expression; //It returns the value evaluated from the expression.


Example: Java program that demonstrate the concept of return statement.
 class ReturnDemo
{
 public static void main(String args[])
{
 System.out.println("Welcome to" + Helloworld());
}
 static String Welcome()
{
 return "Nepalnews.com";
}
}

Here, Welcome() function is called within println() function which returns a String value "Welcome to Nepalnews.com". This is printed to the screen. 

1 comment:

Contact Form

Name

Email *

Message *