Saturday 3 August 2013

11: Language Fundamentals and Operators

Learning Objectives
After completing this session, you will be able to:
‰  Identify the different types of operators in Java
Operators
Different types of operators are:
‰  arithmetic operators
‰  relational operators
‰  logical operators
‰  conditional operators
‰  binary operator
These operators follow a certain kind of precedence so that the compiler will know which operator
to evaluate first, in case multiple operators are used in one statement.
Arithmetic Operators
Arithmetic Operators: Sample Program
1 public class ArithmeticDemo {
2 public static void main(String[] args){
3 //a few numbers
4 int i = 37;
5 int j = 42;
6 double x = 27.475;
7 double y = 7.22;
8 System.out.println("Variable values...");
9 System.out.println(" i = " + i);
10 System.out.println(" j = " + j);
11 System.out.println(" x = " + x);
12 System.out.println(" y = " + y);
13 System.out.println("Adding...");
14 System.out.println(" i + j = " + (i + j));
15 System.out.println(" x + y = " + (x + y));
16 //subtracting numbers
17 System.out.println("Subtracting...");
18 System.out.println(" i - j = " + (i – j));
19 System.out.println(" x - y = " + (x – y));
20
21 //multiplying numbers
22 System.out.println("Multiplying...");
23 System.out.println(" i * j = " + (i * j));
24 System.out.println(" x * y = " + (x * y));
25
26 //dividing numbers
27 System.out.println("Dividing...");
28 System.out.println(" i / j = " + (i / j));
29 System.out.println(" x / y = " + (x / y));
30 //computing the remainder resulting from dividing
31 // numbers
32 System.out.println("Computing the remainder...");
33 System.out.println(" i % j = " + (i % j));
34 System.out.println(" x % y = " + (x % y));
35
36 //mixing types
37 System.out.println("Mixing types...");
38 System.out.println(" j + y = " + (j + y));
39 System.out.println(" i * x = " + (i * x));
40 }
Arithmetic Operators: Sample Program Output
Variable values... Dividing...
i = 37 i / j = 0
j = 42 x / y = 3.8054
x = 27.475
y = 7.22  Computing the remainder...
i % j = 37
Adding...  x % y = 5.815
i + j = 79
x + y = 34.695  Mixing types...
j + y = 49.22
Subtracting...  i * x = 1016.58
i - j = -5
x - y = 20.255
Multiplying...
i * j = 1554
x * y = 198.37
Arithmetic Operators
Note:When an integer and a floating-point number are used as operands to a single arithmetic
operation, the result is a floating point. The integer is implicitly converted to a floating-point number
before the operation takes place.
Increment and Decrement Operators
unary increment operator (++) and unary decrementoperator (--) are the two increment and
decrement operators.
Increment and decrement operators increase and decrease a value stored in a number variable by
1.
For example
the expression, count=count + 1; //increment the value of count by 1 is equivalent to count++;.
Operator  Use   Description
++  op++  Increments op by 1; evaluates to the value of op before it was incremented
++  ++op  Increments op by 1; evaluates tothe value of op before it was incremented
--  op--  Decrements op by 1; evaluates to the value of op before it was decremented
--  --op  Decrements op by 1; evaluates to the value of op after it was decremented
The increment and decrement operators can be placed before or after an operand.
When used before an operand, it causes the variable to be incremented or decremented by 1, and
then the new value is used in the expression in which it appears.
For example:
int i = 10;
int j = 3;
int k = 0;
k = ++j + i; //will result to k = 4+10 = 14
When the increment and decrement operators are placed after the operand, the old value of the
variable will be used in the expression where it appears.
For example:
int i = 10;
int j = 3;
int k = 0;
k = j++ + i; //will result to k = 3+10 = 13
Increment and Decrement Operators: Coding Guidelines
Always keep expressions containing incrementand decrement operators simple and easy to
explain.
Relational Operators
Relational operators compare two values and determine the relationship between those values.
The output of evaluation is the boolean value of true or false.
Operator  Use   Description
++  op++  Increments op by 1; evaluates to the value of op before it was incremented
++  ++op  Increments op by 1; evaluates tothe value of op before it was incremented
--  op--  Decrements op by 1; evaluates to the value of op before it was decremented
--  --op  Decrements op by 1; evaluates to the value of op after it was decremented
Relational Operators: Sample Program
1 public class RelationalDemo{
2 public static void main(String[] args){
3 //a few numbers
4 int i = 37;
5 int j = 42;
6 int k = 42;
7 System.out.println("Variable values...");
8 System.out.println(" i = " +i);
9 System.out.println(" j = " +j);
10 System.out.println(" k = " +k);
11 //greater than
12 System.out.println("Greater than...");
13 System.out.println(" i > j = "+(i>j));//false
14 System.out.println(" j > i = "+(j>i));//true
15 System.out.println(" k > j = "+(k>j));//false
16 //greater than or equal to
17 System.out.println("Greater than or equal to");
18 System.out.println(" i >= j = "+(i>=j));//false
19 System.out.println(" j >= i = "+(j>=i));//true
20 System.out.println(" k >= j = "+(k>=j));//true
21 //less than
22 System.out.println("Less than...");
23 System.out.println(" i < j = "+(i<j));//true
24 System.out.println(" j < i = "+(j<i));//false
25 System.out.println(" k < j = "+(k<j));//false
26 //less than or equal to
27 System.out.println("Less than or equal to...");
28 System.out.println(" i <= j = "+(i<=j));//true
29 System.out.println(" j <= i = "+(j<=i));//false
30 System.out.println(" k <= j = "+(k<=j));//true
31 //equal to
32 System.out.println("Equal to...");
33 System.out.println(" i == j = " + (i==j));//false
34 System.out.println(" k == j = " + (k==j));//true
35 //not equal to
36 System.out.println("Not equal to...");
37 System.out.println(" i != j = " + (i!=j));//true
38 System.out.println(" k != j = " + (k!=j));//false
39 }
40 }
Relational Operators: Sample Program Output
Variable values:
‰  i = 37
‰  j = 42
‰  k = 42
Greater than:
‰  i > j = false
‰  j > i = true
‰  k > j = false
Greater than or equal to:
‰  i >= j = false
‰  j >= i = true
‰  k >= j = true
Less than:
‰  i < j = true
‰  j < i = false
‰  k < j = false
Less than or equal to:
‰  i <= j = true
‰  j <= i = false
‰  k <= j = true
Equal to:
‰  i == j = false
‰  k == j = true
Not equal to...
‰  i != j = true
‰  k != j = false
Logical Operators
Logical operators have one or two boolean operands that yield a boolean result.
There are six logical operators:
‰  && (logical AND)
‰  & (boolean logical AND)
‰  || (logical OR)
‰  | (boolean logical inclusive OR)
‰  ^ (boolean logical exclusive OR)
‰  ! (logical NOT)
The basic expression for a logical operation is, x1 op x2 where, x1, x2 can be boolean
expressions, variables or constants. op is either &&, &, ||, | or ^ operator.
The truth tables that will be shown next, summarize the result of each operation for all possible
combinations of x1 and x2.
Logical Operators: &&(logical) and &(boolean logical) AND
Here is the truth table for && and &:
x1  x2  Result
TRUE  TRUE  TRUE
TRUE  FALSE  FALSE
FALSE  TRUE  FALSE
FALSE  FALSE  FALSE
The basic difference between && and & operators is that && supports short-circuit evaluations (or
partial evaluations), while & does not.
Given an expression exp1 && exp2 where:
‰  && will evaluate the expression exp1, and immediately return a false value if exp1 is
false.
‰  If exp1 is false, then the operator never evaluates exp2 because the result of the
operator will be false regardless of the value of exp2.
‰  In contrast, the & operator always evaluates both exp1 and exp2 before returning an
answer.
1 public class TestAND {
2 public static void main( String[] args ){
3 int i = 0;
4 int j = 10;
5 boolean test= false;
6 //demonstrate &&
7 test = (i > 10) && (j++ > 9);
8 System.out.println(i);
9 System.out.println(j);
10 System.out.println(test);
11 //demonstrate &
12 test = (i > 10) & (j++ > 9);
13 System.out.println(i);
14 System.out.println(j);
15 System.out.println(test);
16 }
17 }
The output of the program is:
0
10
false
0
11
false
Note, that the j++ on the line containing the && operator is not evaluated because the first
expression (i>10) is already equal to false
Logical Operators: || (logical) and | (boolean logical) inclusive OR
Here is the truth table for || and |:
x1  x2  Result
TRUE  TRUE  TRUE
TRUE  FALSE  FALSE
FALSE  TRUE  FALSE
FALSE  FALSE  FALSE
The basic difference between || and I operators is that || supports short-circuit evaluations (or
partial evaluations), while | does not.
Given an expression exp1 || exp2 where:
‰  || will evaluate the expression exp1 and immediately return a true value if exp1 is true.
‰  If exp1 is true, then the operator never evaluates exp2 because the result of the
operator will be true regardless of the value of exp2.
‰  In contrast, the | operator always evaluates both exp1 and exp2 before returning an
answer.
1 public class TestOR {
2 public static void main( String[] args ){
3 int i = 0;
4 int j = 10;
5 boolean test= false;
6 //demonstrate ||
7 test = (i < 10) || (j++ > 9);
8 System.out.println(i);
9 System.out.println(j);
10 System.out.println(test);
11 //demonstrate |
12 test = (i < 10) | (j++ > 9);
13 System.out.println(i);
14 System.out.println(j);
15 System.out.println(test);
16 }
17 }
The output of the program is:
0
10
true
0
11
true
Note, that the j++ on the line containing the || operator is not evaluated because the first
expression (i<10) is already equal to true
Logical Operators: ^ (boolean logical exclusive OR)
Here is the truth table for ^:
x1  x2  Result
TRUE  TRUE  TRUE
TRUE  FALSE  FALSE
FALSE  TRUE  FALSE
FALSE  FALSE  FALSE
The result of an exclusive OR operation is TRUE, if and only if one operand is true and the other is
false.
Note that both operands must always be evaluated inorder to calculate the result of an exclusive
OR.
1 public class TestXOR {
2 public static void main( String[] args ){
3 boolean val1 = true;
4 boolean val2 = true;
5 System.out.println(val1 ^ val2);
6 val1 = false; val2 = true;
7 System.out.println(val1 ^ val2);
8 val1 = false; val2 = false;
9 System.out.println(val1 ^ val2);
10 val1 = true; val2 = false;
11 System.out.println(val1 ^ val2);
12 }
13 }
The output of the program is:
false
true
false
true
Logical Operators: ! ( logical NOT)
The logical NOT takes in one argument, wherein that argument can be an expression, variable, or
constant.
Here is the truth table for !.
x1   Result
TRUE  FALSE
FALSE  TRUE
1 public class TestNOT {
2 public static void main( String[] args ){
3 boolean val1 = true;
4 boolean val2 = false;
5 System.out.println(!val1);
6 System.out.println(!val2);
7 }
8 }
The output of the program is:
false
true
Logical Operators: Conditional Operator (?:)
The conditional operator ? is a ternary operator. This means that it takes in three arguments that
together form a conditional expression:
The structure of an expression using a conditionaloperator is exp1?exp2:exp3wherein exp1 is a
boolean expression whose result must either be true or false
Result:
‰  If exp1 is true, then exp2 is the value returned
‰  If it is false, then exp3 is returned
1 public class ConditionalOperator {
2 public static void main( String[] args ){
3 String status = "";
4 int grade = 80;
5 //get status of the student
6 status = (grade >= 60)?"Passed":"Fail";
7 //print status
8 System.out.println( status );
9 }
10 }
The output of this program will be:
Passed
Flowchart related to student’s grade












The instanceof Operator
‰  The instanceof operator is a binary operator that determines whether an object
reference (the left operand) is an instance of the class, interface, or array type
specified by the right operand.
‰  The instanceof operator cannot be used with primitive types (this results in a
compilation error).
‰  The instanceof operator returns a boolean value of true if the left operand references a
non-null object of class C (or array of type T), so that at least one of the following
conditions hold:
‰  The right operand is a class name C' and C is a subclass of C'.
‰  The right operand is an interface name I, and C implements I.
‰  The right operand is an array of type T‘ , the left operand is an array of type T, and T is
a subclass or subinterface of T' or equal to T'.
‰  The instanceof operator returns false if none ofthe preceding conditions are met or if
the left operand is null.
Operator Precedence










































In a complicated expression, 6%2*5+4/2+88-10 you can rewrite the expression and place some
parenthesis based on operator precedence, like ((6%2)*5)+(4/2)+88-10;.
Operator Precedence: Coding Guidelines

To avoid confusion in evaluating mathematical operations, keep your expressions simple and use
parentheses.
Try It Out
Problem Statement:
Write a program that illustrates the use of the instanceof operator.
Code:
import java.util.*;
class Instance {
public static void main(String args[]) {
String s = "abcd";
Vector v = new Vector();
v.add(s);
Object o = v.elementAt(0);
System.out.println(s instanceof String);
System.out.println(s instanceof Object);
System.out.println(o instanceof String);
System.out.println(o instanceof Object);
System.out.println(o instanceof Vector);
}
}
Refer File Name: Instance.javato obtain soft copy of the program code
How It Works:
‰  When you run the program, it produces the following results:
true
true
true
true
false
‰  The first two output lines reflect the fact that s is a String and therefore an Object
(because String is a subclass of Object)
‰  The third output line displays a value of true even though o is declared to be of type
Object because the object assigned to o is the String object that was added to Vector
v
‰  The fourth and fifth output lines result fromthe fact that a String object is an Object
object but not a Vector object.
Tips and Tricks
On what situations can you use the ‘==‘ operator?
Solution:
To compare two primitives, use the == operator.
Example:
int a = 3;
int b = 3;
if (a == b) { // true}
To see if two references are the same, (which means they refer to the same object on the heap)
use the == operator.
Example:
Foo a = new Foo();
Foo b = new Foo();
Foo c = a;
if (a == b) { // false }
if (a == c) { // true }
if (b == c) { // false }
To compare if two different objectsare equal, use the equals() method.
Summary
‰  The different types of operators are:
oArithmetic operators
oIncrement and decrement operators
oRelational operators
oConditional operators
oLogical operators
‰  To avoid confusion in evaluating mathematical operations, keep your expressions
simple and use parentheses.
Test Your Understanding
1.State true or false for the following:
a)The character pair ?: is called the relational operator.
b)In a mixed expression, the highest ranking operand is identified and the values of
all other operands in the expression are automatically converted to the type of the
highest ranking operand

No comments:

Post a Comment