3 Introduction to Operators and Expression in Java

3.1 INTRODUCTION

For performing different kinds of operations, various types of operators are required. An operator denotes an operation to be performed on some data that generates some value. For example, a plus operator (+) on 3 and 4 generates 7 (3 + 4 = 7). Here, 3 and 4 are called operands.

Java is rich in built-in operators. The four main classes of operators are arithmetic, relational, logical and bitwise.

Apart from these, there are many other operators. A list of operators provided by Java is given in Table 3.1.

Operator Symbolic Representation
Arithmetic +, -, /, *, %
Logical &&, ||, !
Relational >, <,<=,>=, = =, ! =
Assignment =
Increment ++
Decrement --
Comma ,
Conditional ? :
Bitwise &, |, ^, !, >>, <<., >>>
Instanceof

Table 3.1 Operators in Java

3.1.1 Binary Operators

Operators which require two operands to operate on, are known as binary operators. For example, as shown in Table 3.1, the arithmetic, relational, logical (except '!' (NOT) operator) , comma, assignment, bitwise (except ~ operator), etc., are binary operators.

For example: 2 + 4, 34 > 45, x = 23, 2 and 5

3.1.2 Unary Operators

Operators which require only one operand to operate on are known as unary operators. For example, as shown in Table 3.1, increment/decrement! (NOT), ~ (1's complement operator), sizeof, etc., are unary operators. C also provides unary plus and unary minus, i.e., +20 and -34. Here, + and - are known as unary plus operator and unary minus operator, respectively. The unary plus operator does not change the meaning of the operands, i.e., writing +x has no effect on the value of x whereas, unary minus changes the sign of the operand, i.e., if x = 10, then -x changes the value of x from 10 to -10.

For example: +4, 3, ++x, x.

NOTE: ? operator is known as ternary operator as it requires three operands to operate on: One before '?' second after '?' and third after ':'

3.1.3 Expressions

An operator together with operands constitutes an expression or a valid combination of constants, variables and operators forms an expression which is usually recognized by the type of operator used within it. Depending on whether it is integer, floating point or relational expression, etc., one may have different types of operators in an expression—called a mixed mode expression. See Table 3.2 for examples.

Expression Type of Expression
2 + 3 * 4/6 - 7 Integer Arithmetic
2.3 * 4.7/6.0 Real Arithmetic
a > b! = c Relational
X && 10 || y Logical
2 > 3 + x && y Mixed

Table 3.2 Types of expressions

3.2 ARITHMETIC OPERATORS

As given in Table 3.2, there are mainly five arithmetic operators in Java: +, -, *, / and %, which are used for addition, subtraction, multiplication, division and remainder, respectively. Table 3.3 presents arithmetic operators.

Operator Meaning / Used for
+ Addition
- Subtraction
/ Division
* Multiplication
% Remainder

Table 3.3 Arithmetic operators

The operators have their inherent meanings in mathematics. The main point to note when a division is performed with an integer operand is that the result will be an integer. If any of the operand is a floating point the answer will also be in floating point. The percentage symbol '%' is used for modulus of a number. a/b produces quotient and a%b, where % is called remainder operator, produces remainder when a is divided by b . The remainder operator % can be used with integer as well as with floating points. The mathematical formula behind remainder operator is:

a%b 5 a - (a/b) * b (where a/b is integer division)

For example, a = 5 13 and b 5 = 5
                    13 % 5 = 5 13 – (13/5) * 5
                           = 13 – (2) * 5
                           = 13 – 10
                           = 3
As another example with floating point data consider a = 5 5.3f and  b = 2.4f
                                               5.3%2.4  = 5.3 – (5.3/2.4) * 2.4
                                                        = 5 5.3 – (2)* 2.4
                                                        = 5.3 – 4.8
                                                        = 0.5

Few programs can be presented based on these operators.

/*PROG 3.1 DEMO OF ARITHMETIC OPERATORS */
class JPS1
{
          public static void main(String args[])
          {
          float num1=13.5f, num2=7.0f;
          float a,b,c,d,e;
          a=num1+num2;
          b=num1-num2;
          c=num1*num2;
          d=num1/num2;
          e=num1%num2;
          System.out.println("Sum of num1 & num2 :="+a);
          System.out.println("Sub of num1 & num2 :="+b);
          System.out.println("Mul of num1 & num2 :="+c);
          System.out.println("Div of num1 & num2 :="+d);
          System.out.println("Mod of num1 & num2 :="+e);
          }
}
OUTPUT:

Sum of num1 & num2 :=20.5
Sub of num1 & num2 :=6.5
Mul of num1 & num2 :=94.5
Div of num1 & num2 :=1.9285715
Mod of num1 & num2 :=6.5

Explanation: The program is self-explanatory.

/*PROG 3.2 SUM OF TWO NUMBERS, INPUT FROM USER */
import java.io.*;
import java.util.*;
class JPS2
{
          public static void main(String args[])
          {
                 int x, y, z;
                 Scanner sc = new Scanner(System.in);
                 System.out.print("
 Enter first number :=");
                 x = sc.nextInt();
                 System.out.print("
 Enter second
                                      number:=");
                 y = sc.nextInt();
                 z = x + y;
                 System.out.println("
 x:= " + x + "	y:= " + y);
                 System.out.println("
       Sum:= " + z);
          }
}
OUTPUT:

Enter first number:=15
Enter second number:=20
x:= 15 y:= 20
Sum:= 35

Explanation: Two numbers are taken from input. Both the numbers are taken one by one. For taking input, scanner class has been used. This method of taking input has been shown earlier.

/* PROG 3.3 DEMO OF MOD OPERATOR, FINDING QUOTIENT AND REMAINDER */
import java.io.*;
import java.util.*;
class JPS3
{
          public static void main(String args[])
          {
                 int num1, num2, rem, quo;
                 Scanner sc = new Scanner(System.in);
                 System.out.println("
Enter two integer
                                     numbers");
                 num1 = sc.nextInt();
                 num2 = sc.nextInt();
                 quo = num1 / num2;
                 rem = num1 % num2;
                 System.out.println("
num1:=" + num1 + "	num2:="
                                                      + num2);
                 System.out.println("
Quotient:=" + quo);
                 System.out.println("
Remainder:=" + rem);
          }
}
OUTPUT:

Enter two integer numbers
13 5
num1:=13         num2:=5
Quotient: =2
Remainder: =3

Explanation: The program is simple to understand. We take two integer numbers as inputs and find division and modulus of two numbers. The numbers and result are then shown.

/* PROG 3.4 BEHAVIOUR OF MOD OPERATOR */
import java.io.*;
import java.util.*;
class JPS4
{
         public static void main(String args[])
         {
            System.out.println("
 BEHAVIOUR OF MOD OPERATOR
");
            System.out.println("17%5    :=" + (17 % 5));
            System.out.println("-17%5   :=" + (-17 % 5));
            System.out.println("17%5    :=" + (17 % 5));
            System.out.println("-17%-5  :=" + (17 % -5));
        }
}
OUTPUT:

BEHAVIOUR OF MOD OPERATOR
17%5   :=2
-17%5  :=-2
17%5   :=2
-17%-5 :=2

Explanation: Using % operator if the numerator is negative, the answer will also be negative. This can be verified by the formula given in the program for - 17 and 5.

- 17 % 5 = -17 -(-17/5)*5
         = -17 -(-3)* 5
         = -17 + 15
         = -2

3.3 RELATION AND TERNARY OPERATOR

The two symbols '?' and ':' together are called ternary or conditional operator. Before '?', condition is specified with the help of relational operators which may be any of the operators as given in the Table 3.4. If the condition specified before '?' is true any expression or statement after '?' is executed, and if the condition is false the statement or expression after ':' is evaluated. The general syntax is:

All relational operators yield Boolean values, i.e., true or false.

Operator Meaning/Used for
> Greater than
< Less than
> = Greater than equal to
< = Less than equal to
= = Equal to
! = Not equal to

Table 3.4 Relational operators

An example of the use of ternary operator is given below.

String str;
str= 5>0?"Welcome":Bye Bye......";

As the condition 5>0 is true, "Welcome" will be assigned to str.

/* PROG 3.5 DEMO OF CONDITIONAL OPERATOR */
import java.io.*;
import java.util.*;
class JPS5
{
          public static void main(String args[])
          {
                 int num1 = 5, num2 = 7;
                 boolean res;
                 String str;
                 res = (num1 == num2);
                 str = res ? "Both are equal
" : "Both are not equal";
                 System.out.println(str);
          }
}
OUTPUT:

Both are not equal

Explanation: The expression a= =b gives false in res. If it were true, true would be in res. Before '?' value is false due to false in res and so is the output.

/* PROG 3.6 FINDING MAXIMUM OF TWO NUMBERS */
import java.io.*;
import java.util.*;
class JPS6
{
          public static void main(String args[])
          {
                 String snum;
                 int a,b,c,max1, max;
                 Scanner sc= new Scanner(System.in);
                 System.out.print("

Enter first number :=");
                 a=sc.nextInt();
                 System.out.print("Enter second number:=");
                 b=sc.nextInt();
                 System.out.print("Enter third number :=");
                 c=sc.nextInt();
                 max1=a>b?a:b;
                 max=max1>c?max1:c;
                 System.out.println("a="+a);
                 System.out.println("b="+b);
                 System.out.println("c="+c);
                 System.out.println("Maximun="+max);
          }
}
OUTPUT:

Enter first number:=15
Enter second number:=45
Enter third number :=10
      a=15
      b=45
      c=10
Maximun=45

Explanation: Initially, maximum of two numbers is found out and stored in the max1. Then, maximum of max1 and c is found out, which gives maximum of three numbers. The maximum can also be found out by nesting of ternary operators as shown below.

In this example, assume two names for the expressions A1 and A2. In the nested condition when a > b is true, A1 will execute and A2 is skipped. This means that a > b so next it can be checked whether a > c and this is what A1 represents. If a > c then the maximum is a, else maximum is c, which is assigned to max.

If a > b fails, it means b > a , then A1 is skipped and A2 is executed. Falsity of a>b means b ≤ a so next it can be checked whether b > c and this is what A2 represents. In A2, if b > c then maximum is b, else maximum is c, which is assigned to max.

/*PROG 3.7 DEMO OF RELATIONAL OPERATOR */
class JPS7
{
          public static void main(String args[])
          {
                int a = 5, b = 6;
                boolean p, q, r, s, t, u;
                p = a > b;
                q = a < b;
                r = (4 != 3);
                s = (8 >= 15);
                t = (130 <= 130);
                u = (0 == 0);
                System.out.println("

value of p :=" + p);
                System.out.println("value of q :=" + q);
                System.out.println("value of r :=" + r);
                System.out.println("value of s :=" + s);
                System.out.println("value of t :=" + t);
                System.out.println("value of u :=" + u);
          }
}
OUTPUT:

value of p :=false
value of q :=true
value of r :=true
value of s :=false
value of t :=true
value of u :=true

Explanation: All relational operators return either a true or a false value. The true and false value can only be stored in the Boolean variables and not in any other types of variables. In the program, depending on the expression true or false value is assigned to variables p, q, r, s, t and u.

3.4 LOGICAL OPERATOR

Logical operators are used to check logical relation between two expressions. Depending on the truth or falsehood of the expression they are assigned true or false value. The expressions may be variables, constants, functions, etc. These operators always work with the true and false value. Table 3.5 presents logical operators.

Symbol Meaning
&& AND
|| OR
! NOT

Table 3.5 Logical operators

The '&&' and ' ||' are binary operators. For '&&' to return true value, both of its operands must yield true value. For '||' to yield true value, at least one of the operands should yield true value. The NOT (!) operator is unary operator. It negates its operand, that is, if the operand is true it converts it into false and vice versa.

In case of logical operators '&&' and '||', if the left operand yields false value, the right operand is not evaluated by a compiler in a logical expression using '&&'. If the left operand yields true value, the right operand is not evaluated by the compiler in a logical expression with the operator '||'. The operators '&&' and ' ||' have left to right associativity, hence the left operand is evaluated first and based on the output, the right operand may or may not be evaluated. For example, consider the following expression:

int x =10;
boolean b = (10>=15) &&(x++! =4);
System.out.println ("x="+x);

The left operand of '&&' (10 > = 15) is false so the right operand (x+ + ! = 4) is not evaluated. If it were '||' (OR) in the above expression in place of '&&' , the second operand would have been checked and x = 11 would be the output.

Due to the aforesaid feature of '&&' and '||' operators, they are sometimes known as short circuit operators as they short-circuit the next operand to be checked.

Operand 1 Operand 2 Returned Value
False False False
False True False
True False False
True True True

Table 3.6 Truth table of logical AND

3.4.1 Logical AND (&&)

The operator works with two operands which may be any expression, variable, constant or function. It checks if both of its operands returns true value or not. If they return true value, and if either of its operands is false, a false value is returned (See Table 3.6).

/*PROG 3.8 DEMO OF LOGICAL AND (&&) OPERATOR */
class JPS8
{
          public static void main(String args[])
          {
                int num1 = 5, num2 = 7;
                boolean a, b;
                a = (num1 > num2) && (num2 > 5);
                b = (num1 > 2) && (num2 > 3);
                System.out.println("
VALUE OF a :=" + a);
                System.out.println("VALUE OF b :=" + b);
          }
}
OUTPUT:

VALUE OF a :=false
VALUE OF b :=true

Explanation: Logical AND returns true when both the conditions and its operand are true and also when the first operand returns a false value and the second operand is not evaluated. In the program, if the expression a = (num1 > num2)&&(num2 > 5); returns false, num1 > num2 is false and the second condition is not checked. Thus, 'a' stores false as its value. In the expression b = (num1 > 2) && (num2 > 3); the first condition num1 > 2 is true, so the second condition is checked, which also turns out true. Thus, 'b' stores true as its value.

Operand 1 Operand 2 Returned Value
False False False
False True True
True False True
True True True

Table 3.7 Truth table of OR

3.4.2 Logical OR

The operator works with two operands which may be any expression, variable, constant or function. It checks whether any of its operands returns true value or not. If any one of them is true, it returns true value and if both of its operands are false, false value is returned. Table 3.7 presents the truth table of logical OR.

/* PROG 3.9 DEMO OF LOGICAL OR OPERATOR */
class JPS9
{
          public static void main(String args[])
          {
                int a=5,b=6;
                boolean d,c,e,f;
                c=(a>b)||(b>15);
                d=(a>12)||(b>3);
                e=(a>2)||(b>13);
                f=(a>2)||(b>3);
                System.out.println("
Value of c:="+c);
                System.out.println("
Value of d:="+d);
                System.out.println("
Value of e:="+e);
                System.out.println("
Value of f:="+f);
          }
}
OUTPUT:

Value of c: =false
Value of d: =true
Value of e: =true
Value of f: =true

Explanation: In logical OR , if any of the conditions is true, the whole logical OR expression is considered true. If the first condition is true then the second condition is not evaluated at all. In the above program, of the four expressions, three are true and one is false.

3.4.3 Logical NOT (!)

The operator converts a true value into false and vice versa (Table 3.8). Again, the operand may be any expression, constant, variable or function.

Operand Returned Value
False True
True False

Table 3.8 Truth table of NOT

/*PROG 3.10 DEMO OF LOGICAL NOT OPERATOR */
class JPS10
{
          public static void main(String args[])
          {
                int num1 = 15, num2 = 17;
                boolean check1, check2;
                check1 = !(num1 > 10);
                check2 = !(num1 > 20);
                System.out.println("
 Value of check1:="
                                       + check1);
                System.out.println("
 Value of check2:="
                                       + check2);
          }
}
OUTPUT:

Value of check1:=false
Value of check2:=true

Explanation: The NOT operator '!' negates the value; that is, true value is converted into false and false into true.

3.5 ASSIGNMENT OPERATOR

The '=' is called assignment operator. Several instances of this operator have been presented in earlier programs. In addition, one use of this operator is the shortening of following types of expressions:

x = x + 1,    y = y *(x - 5),    a = a/10,    t = t%10;

In all the above expressions, the variable on both sides of '=' operator is the same. So the above expression can be changed to a shorter form as follows:

x = x 1 + 1            =>           x + = 1
y = y * (x - 5)       =>           y* = (x-5)
a = a/10               =>           x/ = 10
t = t%10               =>           t% =  10

This form op=, where operator may be any operator is called compound operator or shorthand assignment operator.

Java also supports chained assignment, i.e., assigning a value to one of the variables in the chain and then from this to the next one in the chain and so on. The rightmost value in the chain must be assigned the value as assignment operator works from right to left. For example:

         int x, y, z;
         x = y = z =15;

In this example, first 15 will be assigned to z, and then the value of z will be assigned to y and at the end, the value of y will be assigned to x. In terms of chain assignment, it can be thought that after assigning the value 15 to z, it returns a value which is given to next variable in the chain.

3.6 INCREMENT (++) AND DECREMENT (--) OPERATOR

The '++' is known as increment operator and the '-' is known as decrement operator. Both are unary operators. The '++' increments the value of its operand by 1 and '-' decrements the value of its operand by 1. For example: + + x becomes 11 (assume x = 10, prior to this operation + + x and -- x) and -x becomes 9. The following syntax is given, for example:

int x=10;
x++;         //makes x 11;
System.out.println("x ="+x);  //prints 11
x--;          //makes x 10;
System.out.println("x="+x);   //prints 10

If the operator '++' or '-' is written before the operand, like -x or ++x, it is known as pre-decrement/pre-increment. In case, it is written after the operand, like x- or x++, it is known as post-decrement/post-increment. The difference between the two forms of these operators is visible when single expression is assigned involving these operators to some variable. For example:

int x=10;
y = x++;
System.out.println("x ="+x);      //prints 11
System.out.println("y ="+y);      //prints 10

In this code, post-increment operator has been used with x, and y is assigned the value. Due to post-increment, first x will be assigned to y, and x will be incremented by 1, i.e., y = x++ is equivalent to the following two statements:

y = x;
x = x + 1;

Now consider the following code:

int x=10;
y = ++x;
System.out.println("x =" +x);      //prints 11
System.out.println("y =" +y);    //prints 11

In this code, pre-increment operator has been used with x and y is assigned the value. Due to pre-increment, first x will be incremented by 1 and the same incremented value will be assigned to y. y = + +x, which is equivalent to the following statement:

x = x + 1;
y = x;

See the program given below for more explanation.

/*PROG 3.11 DEMO OF ++ & -- OPERATOR */
class JPS11
{
          public static void main(String args[])
          {
                 int x,y;
                 x = 10;
                 y = ++x;
                 --x;
                 y--;
                 x = y++;
                 y = --x;
                 x = y++;
                 System.out.println("x="+x);
                 System.out.println("y="+y);
          }
}
OUTPUT:

x=9
y=10

Explanation: For explanation see Table 3.9.

Statement Value of x Value of y
Y = ++x 11 11
--x 10 11
y-- 10 10
X = y++ 10 11
Y = --x 09 09
X = y++ 09 10

Table 3.9 Basic implementation of Program 3.11

y = ++ x; is equivalent to x = x + 1; y = x; the value of x is incremented first then it is assigned to y.

/* PROG 3.12 IMPLEMENTATION OF METHODOLOGY OF ++ AND -- OPERATOR */
class JPS12
{
          public static void main(String args[])
          {
                 int x=10;
                 System.out.println("
BEHAVIOUR OF ++ AND
                                      -- OPERATOR");
                 System.out.println("
 "+(--x)+" "+(++x)+"
                                       "+(x)+" "+(x++)+" "+(x--));
          }
}
OUTPUT:

BEHAVIOUR OF ++ AND -- OPERATOR
9 10 10 10 11

Explanation: The evaluation takes place from left to right. This is shown in the following steps:

1.   In --x, first x is decremented and then printed, so the output is 9 and the same for the next expression.

2.   In ++x, first x is incremented and then printed, so the output is 10 and the same for the next expression.

3.   In x, value of x is printed, so the output is 10 and the same for the next expression.

4.   In x++, first x is printed and then incremented, so the output is 10 and 11 for the next expression.

5.   In x--, first x is printed and then decremented, so the output is 10.

3.7 BITWISE OPERATORS

Bitwise operators are called so because they operate on bits. They can be used for the manipulation of bits. Java provides a total of seven types of bitwise operators as shown in Table 3.10.

Operator Meaning/Used for
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ One's Complement
>> Right Shift
<< Left Shift
>>> Right Shift with zero fill

Table 3.10 Bitwise operators

For all the following programs, the byte data type is only considered. The byte data type is of 8 bits, so the range of possible numbers is from -128 to 127 and numbers are represented using 8 bits.

3.7.1 Bitwise AND (&)

Bitwise AND (&) takes two bits as operand and returns the value 1 if both are 1. If either of them is 0, the result is 0 (Table 3.11).

First Bit Second Bit Result
0 0 0
0 1 0
1 0 0
1 1 1

Table 3.11 Truth table of bitwise AND

For example, consider the following program:

/*PROG 3.13 DEMO OF BITWISE AND (&)OPERATOR */
class JPS13
{
          public static void main(String args[])
          {
                 byte b1 = 12, b2 = 7;
                 byte b3 = (byte)(b1 & b2);
                 System.out.println("
Behavior of Bitwise
                                       AND(&)operator");
                 System.out.println("
The value of b3:=" + b3);
          }
}
OUTPUT:

Behavior of Bitwise AND (&) operator
The value of b3:=4

Explanation: For explanation, see the following table, if both the input and output are 1.

images

3.7.2 Bitwise OR (|)

Bitwise OR (|) takes two bits as operand and returns the value 1 if at least one operand is 1. If both are 0, only then the result will be 0, else it is 1 (Table 3.12).

For example, consider the following program:

First Bit Second Bit Result
0 0 0
0 1 1
1 0 1
1 1 1

Table 3.12 Truth table of bitwise OR

/*PROG 3.14 DEMO OF BITWISE OR (|)OPERATOR*/
class JPS14
{
          public static void main(String args[])
          {
                byte b1 = 65, b2 = 42;
                byte b3 = (byte)(b1 | b2);
                System.out.println("

Behavior of Bitwise  OR");
                System.out.println("
Value of b3 :=" + b3);
          }
}
OUTPUT:

Behavior of Bitwise OR
Value of b3:=107

Explanation: For explanation, see the following table. If any of the input is 1 then the output will be 1.

images

3.7.3 Bitwise XOR (^)

Bitwise XOR (^) takes at least two bits (may be more than two). If the number of 1's are odd then the result is 1, else the result is 0 (Table 3.13).

For example, consider the following program:

First Bit Second Bit Result
0 0 0
0 1 1
1 0 1
1 1 0

Table 3.13 Truth table of bitwise XOR (^)

/*PROG 3.15 DEMO OF BITWISE XOR (∂)OPERATOR */
class JPS15
{
   public static void main(String args[])
   {
         byte b1 = 125, b2 = 107;
         byte b3 = (byte)(b1 ^ b2);
         System.out.println("

Behaviour of Bitwise
                                 XOR");
         System.out.println("
The value of b3:=" + b3);
   }
}
OUTPUT:

Behaviour of Bitwise XOR
The value of b3:=22

Explanation: For bitwise XOR (∂) operator, if the number of 1's are odd then the result is 1, else the result will be 0. For better explanation, see the following table:

images

3.7.4 1's Complement (~)

The symbol (~) denotes 1's complement. It is a unary operator and complements the bits in its operand, i.e., 1 is converted to 0 and 0 is converted to 1.

/*PROG 3.16 DEMO OF 1'S COMPLEMENT (~)*/
class JPS16
{
          public static void main(String args[])
          {
                byte b1 = 107;
                byte b2 = (byte)~b1;
                System.out.println("

Behaviour of 1's
                                     complement");
                System.out.println("
The value of b2 :=" + b2);
          }
}
OUTPUT:

Behaviour of 1's complement
The value of b2 :=-108

Explanation: Representing b1 in binary 8 bits and doing bitwise 1's complement:

images

On running the program, as given above, the answer will be 148, otherwise the answer will be -108. Both the answers are correct but as the left most bit (bit number 7) is 1 in b2, the number will be negative and the computer has given the answer in 2's complement form. In order to cross check whether the answer is correct or not, find out the binary value of 108, which is as follows:

images

Taking 1's complement of the above value:

images

Now adding 1 to it, the result is:

images

Now, the binary value of 148 and -108 is the same. So the answer is correct.

3.7.5 Left Shift Operator (<<)

Left shift operator is used to shift the bits of its operand towards left. It is written as x << num, which means shifting the bits of x towards left by num number of times. A new zero is entered in the least significant bit (LSB) position. For example, consider the following code:

/*PROG 3.17 DEMO OF LEFT SHIFT OPERATOR (<<)*/
class JPS17
{
          public static void main(String args[])
          {
                byte b1 = 42;
                byte b2 = (byte)(b1 << 1);
                System.out.println("

Demo of Left Shift
                                      Operator");
                System.out.println("
The value of b2:=" + b2);
          }
}
OUTPUT:

Demo of Left Shift Operator
The value of b2:=84

Explanation: The binary representation of 42 in 8 bits.

images

In the left, shifting bits are shifted towards left as: bit b0 moves to b1, b1 to b2 and so on . A zero is inserted at the b0 position. After shifting bits of b1 once, the resultant bits patterns will be as follows:

images

NOTE: Shifting the bits left once multiplies the number by 2, while shifting the bits left by n number of times multiplies the number by 2n.

3.7.6 Right Shift Operator (>>)

Right shift operator is used to shift the bits of its operand towards right. It is written as x>>num, which means shifting the bits of x towards right by num, number of times. A new zero (not necessarily, depends on sign bit) is entered in the most significant bit (MSB) position. See the program given below.

/*PROG 3.18 DEMO OF RIGHT SHIFT OPERATOR (>>)*/
class JPS18
  {
           public static void main(String args[])
           {
                  byte b1 = 42;
                  byte b2 = (byte)(b1 >> 1);
                  System.out.println("

Demo of Right Shift
                                        Operator");
                  System.out.println("The value of b2:=" + b2);
           }
  }
  OUTPUT:

  Demo of Right Shift Operator
  The value of b2:=21

Explanation: Look at the binary representation of 42 in 8 bit format as given below.

images

In the right, shifting bits are shifted towards right as: bit b7 moves to b6, b6 to b5 and so on . A zero is inserted at the b7 position. It is to be noted that b7 represents sign bit. For positive numbers, the sign bit is 0 and for negative numbers sign bit. In the right shifting the sign bit remains at its position and propagates too in the right direction. After shifting the bits of b1 once, the resultant bits pattern will be as follows:

images

NOTE: Shifting the bits right once divides the number by 2. Shifting the bits right by n number of times divides the number by 2n.

/*PROG 3.19 DEMO OF BITWISE OPERATOR ALL IN A SINGLE PROGRAM */
class JPS19
{
          public static void main(String args[])
          {
                 int x = 2,y = 3,and,or,xor,comp,lshift,rshift;
                 and = x & y;
                 or = x | y;
                 xor = x ^ y;
                 comp = ~x;
                 lshift = x << 2;
                 rshift = (x * 2) >> 1;
                 System.out.println("x:=" + x);
                 System.out.println("y:=" + y);
                 System.out.println("and:=" + and);
                 System.out.println("xor:=" + xor);
                 System.out.println("comp:=" + comp);
                 System.out.println("lshift:=" + lshift);
                 System.out.println("rshift:=" + rshift);
          }
}
OUTPUT:

x:=2
y:=3
and:=2
xor:=1
comp:=-3
lshift:=8
rshift:=2

Explanation: Read the theory given above for explanation.

3.7.7 Right Shift with Zero Fill (>>>)

The operator '>>' shifts number towards right and depending on sign bit fills 0 or 1. The '>>>' operator is the unsigned right shift operator. Regardless of sign of number it always fills zero at the left side. The effect of '>>>' operator can only be seen in terms of integer and long data types. In order to understand this concept, look at the program given below.

/* PROG 3.20 DEMO OF RIGHT SHIFT WITH ZERO FILL (>>>)OPERATOR */
class JPS20
{
       public static void main(String args[])
       {
          int x = -1;
          int y1 = x >>> 16;
          int y2 = x >> 16;
          System.out.print("

Applying >> on -1,16  times");
          System.out.println(" give " + y2);
          System.out.print("
Applying >>> on -1,16times");
          System.out.println(" give " + y1);
       }
}
OUTPUT:

Applying >> on -1, 16 times give -1
Applying >>> on -1, 16 times give 65535

Explanation: Internally, -1 is represented as all ones. In 32 bit format, it can be shown as follows:

images

Applying '>>' operator of the above binary string sixteen times, shifts the number sixteen times towards right and fills sixteen 1s as the number is -ve and as the left most bit represents the sign so the bit string remains the same. Hence, the output will be -1.

Applying '>>>' operator to -1 sixteen times has the same effect as '>>>' but instead of 1s, 0s are inserted towards the left. The binary string therefore becomes as follows:

images

There are sixteen 1s from the right and all other bits are 0s; so in decimal, the value of the binary string will be 216-1, i.e., 65535.

3.8 THE INSTANCEOF OPERATOR

The instanceOf operator is used to check which object is of which class. By knowing this, one can call the appropriate method of the class. For example, if one creates an object d of class demo (say) as demo d = new demo(); then the expression will be Boolean b = d instance of demo stores true in b. This operator will be used in a number of programs presented in subsequent chapters. In the present context a short program is given below.

/* PROG 3.21 DEMO OF INSTANCEOF OPERATOR */
class demo
{}
class JPS21
{
   public static void main(String args[])
   {
       Object top;
       Float objf = 0.0f;
       Integer obji = 15;
       Long objl = 25L;
       top = objf;
       if (top instanceof Float)
          System.out.println("
 of class Float");
       top = obji;
       if (top instanceof Integer)
          System.out.println("
 of class Integer");
       top = objl;
       if (top instanceof Long)
          System.out.println("
 of classs Long");
       top = new demo();
       if (top instanceof demo)
          System.out.println("
 of class demo");
   }
}
OUTPUT:

of class Float
of class Integer
of classs Long
of class demo

Explanation: The class object is the base class for all the classes in the Java class hierarchy, even for the user-defined classes. In the program, there is a reference obj of Object class type. Three objects of the class—Integer, Long and Float—are created and initialized as follows.

top = objf;
if (top instanceof Float)
System.out.println("
 of class Float");

Object objf of float class is assigned to a reference of Object class. This is perfectly appropriate as the base class can hold a reference of any derived class and Object is the base class for all classes in Java. The if condition checks whether the reference top referring to an object of Float class which is true so output produced is of class Float.

The same discussion applies to Integer and Long class. At the end, top contains reference of user-defined class demo and if condition is true which prints of class demo.

3.9 THE COMMA OPERATOR

The comma is not an operator in Java; it is simply used as a separator for the variable declarations. For example, the following expression used in C and C++ will not work in Java.

int x = (2, 5, 6);
System.out.println ("x ="+x);

This will generate compilation errors.

Also, in loops, the following code will generate compilation errors.

for(i=0, j=10;i<10,j>=10;i++,j- -)
{
}

In the condition part (i<10, j>=10) one cannot use comma as operator.

3.10 THE sizeof() OPERATOR

In C and C+ + , the sizeof() operator satisfies a specific need: it tells the number of bytes allocated for the data items. The most compelling need for sizeof() in C and C + + is portability. Different data types might be of different sizes on different machines, so the programmer must find out how big those types are when performing operations that are sensitive to size. For example, one computer might store integers in 32 bits, whereas another might store it as 16 bits. Programs could store larger values in integers on the first machine. Probably, portability is a major issue for C and C+ + programmers.

Java does not need a sizeof() operator for this purpose, because all the data types are of the same size on all machines. There is no need to think about portability on this level—it is designed into the language.

3.11 PRECEDENCE OF OPERATOR

Precedence tells in an expression which operations should be performed first depending on priority of operators. Associativity means when two or more operators have same priority then from which side (left or right) to operate (see Table 3.14); for example, in the expression a*b/c '*' and '/' have got same priority whether one performs a*b first or b/c first or in other way 'b' should be considered as part of sub-expression b/c or a*b. Associativity of '*' and '/' is from left to right, so the sub-expression a*b will be performed first and then the result of a*b will be divided by c. While executing some expressions first, regardless of the priority of the operators, one can console the expressions within parenthesis. For example:

float a=12f, b=3f, c=4f, d;
d = (a-d)/c;
System.out.println(d);          //prints 2.25
Operators Associativity Priority
(), [],. Right to left 1
+, -, ++,!, &, ~, sizeof Right to left 2
*, /, % Left to right 3
+,- Left to right 4
<<, >> Left to right 5
<,<=,>,> = Left to right 6
= =, ! = Left to right 7
& Left to right 8
^ Left to right 9
| Left to right 10
&& Left to right 11
|| Left to right 12
?: Right to left 13
= Right to left 14

Table 3.14 Operator precedence table

In order to evaluate the difference of a and b divided by c, it can be written (a - b)/c. As precedence of '/ ' is more than '-', if it is written as a - b/c, then initially b/c will be evaluated, which is not required. So, whenever an expression needs to be evaluated irrespective of the priority of the operator, it is written within parenthesis.

3.12 TYPE CONVERSION AND TYPECASTING

Sometimes, in an expression, it is required to convert the data type of a variable or a constant, for example, from float to int or int to float, etc. In this case, two types of conversions are used in practice.

1.   Implicit type of conversion: In this type of conversion, the compiler internally converts the type depending on the expression without letting the user to know. The following example can be presented:

  double num =34;
  double d = 45.56f;

In this example, value 34 is integer constant and an integer is assigned to double. As double data type has higher width than integer data type, 34 will be converted internally into double and will be assigned to num. Similarly, in the next case, floating point constant is assigned to double data type. Note that a reverse will not be true, i.e., one cannot assign a float to an integer, an integer to byte or a double to float, etc. Java is a strong type language. For example, in C+ + , assigning a float to an integer is allowed. The float value is internally converted to integer and the fraction part is lost. In Java, this will be an error. In Java, only the lower data type can be assigned to higher data type without casting. This is known as widening or promotion.

Look at the following code snippet as an example of implicit type conversion.

  int a =10;
  float b = 2.5f, c;
  c = a+b;

In the expression c = a + b , type of 'a' and 'b' is not the same. According to size, float is greater than int so variable 'a' is internally converted into float and then addition is performed so that the result obtained will also be in float.

2.   Explicit type conversion: In this type of conversion (also known as typecasting), the data type of the variable or constant is explicitly converted from one to another. For example:

  float x= 2.5f;
  int a=x;

If the above code is compiled in Java, it will produce a compilation error as one cannot assign a higher data type to a lower data type without typecasting. Assigning a higher data type to a lower data type can only be allowed when typecasting is done. For example:

  int x = 23.45f;           //error cannot assign float to
                              int;
  int x =(int)23.45f;       //valid 23 will be assigned to x;
  byte b = 260;             //error 260 is integer
  byte b =(byte)260;        //260%256 (range of byte data type)
                                    =4 is assigned to b;
  float f = 14.4878129878   //error
  float f =(float)14.4878129878; or float f= 14.4878129878f;

NOTE: Loss of precession will occur as f will contain 14.487813, as float allows only six digits of precision whereas double allows 14 digits of precision.

In addition, all expressions involving either byte or short or both are internally converted to integer before the operation is performed. For example:

  byte b1 = 20, b2 = 5;
  byte b3 = b1 * b2;

The above line will give error as b1*b2 is promoted to integer in the expression that becomes 100 and treated as integer. Assigning an integer to byte data type without typecasting will give compilation error, which has been seen in bitwise operators. The correct way will be as follows:

  byte b3 =(byte)(b1*b2);

3.13 MATHEMATICAL FUNCTIONS

For using mathematical functions in the program, Math class as defined in java.lang package can be used. The class defines a number of mathematical functions which can be used in a number of programming situations. The class Math contains methods for programming basic numeric functions. All methods are static and return double values.

Some of the methods return value other than double. It also provides a field PI which returns values of 22/7 or the ratio of the circumference of a circle to its diameter.

The most commonly used functions are listed in Table 3.15.

Function Signature Purpose
static double abs (double a) Returns the absolute value of a double value.
static double ceil (double a) Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument.
static double cos (double a) Returns the trigonometric cosine of an angle.
static double exp (double a) Returns Euler's number e raised to the power of a double value.
static double floor (double a) Returns the largest (closest to positive infinity) double value that is less than or equal to the argument.
static double hypot (double x, double y) Returns sqrt (x2 + y2) without intermediate overflow or underflow.
static double log (double a) Returns the natural logarithm (base e) of a double value.
static double max (double a, double b) Returns the greater of two double values.
static double min (double a, double b) Returns the smaller of two double values.
static double pow (double a, double b) Returns the value of the first argument raised to the power of the second argument.
static double random() Returns a double value with a positive sign greater than or equal to 0.0 and less than 1.0.
static long round (double a) Returns the closest long to the argument.
static double sin (double a) Returns the trigonometric sine of an angle.
static double sqrt (double a) Returns the correctly rounded positive square root of a double value.
static double tan (double a) Returns the trigonometric tangent of an angle.

Table 3.15 Some mathematical functions

Some of the functions are discussed below.

1.   Math.abs (argument)
The method returns the absolute value of the argument. The method is overloaded for int, long, float and double data type.

For example:

double d = Math.abs (223);        // returns 23

2.   Math.cbrt (double d)
The method finds cube root of argument d of double type.

For example:

double d1 = Math.cbrt(27.0);      //prints 3.0

3.   Math.ceil (double a)
The method returns the smallest double value that is greater than or equal to the argument and is equal to a mathematical integer.

For example:

double d =Math.ceil (2.3);       //returns 3.0

4.   Math.floor (double d)
This function returns the largest double value that is less than or equal to the argument and is equal to a mathematical integer.

For example:

double d = Math.floor (2.3);     //return 2.0

5.   int Math.round (double d)
The method returns the closest int to the argument.

For example:

int x = Math.round (2.3);        //returns 2
    int y = Math.round (2.6);    // returns 3

6.   Math.pow (double a, double b)
The method returns the value of the first argument raised to the power of the second argument.

For example:

double d = Math.pow(2, 3);      //returns 8

7.   Math.sqrt (double d)
The method returns square root of the argument passed.

For example:

double d= Math.sqrt (25);       //returns 5.0

3.14 SCOPE AND LIFETIME

When a variable is declared within a function or a block (A block can be created by enclosing statements within {}) that variable is accessible only to that block or function. Other blocks/functions cannot access that variable as they are local to that block/function, and where the variable can be accessed is called the scope of the variable. In other words, it is called the portion of program where the variable may be visible or available.

Nesting of scope can be done, i.e., one block can be created inside another block. All the variables of the outer block can be accessed in the inner block but reverse is not true. Here, the scope is discussed within block and method only. The other type of scope is created by the class which will be discussed in the study about classes.

/*PROG 3.22 DEMO OF BLCOK AND SCOPE VER 1 */
class JPS22
{
   public static void main(String args[])
   {
       int p = 20;
       System.out.println("
In main");
       System.out.println("p=" + p);
       {
          System.out.println("
In block");
          int y = 30;
          System.out.println("y=" + y);
          System.out.println("p=" + p);
       }
   }
}
OUTPUT:

In main
p=20
In block
y=30
p=20

Explanation: In the program, the 'p' is declared within main. Inside main, a block is created and in it there is an integer variable y initialized by 30 . In the block, one can access the variable p of the main but y cannot be accessed outside the block. Thus, the scope of p is the entire main method whereas the scope of y is the block only. If one tries to use y outside the block, he will get a compilation error.

One important point to note regarding variables in the blocks or methods is that whenever control reaches into the method, variables spring to life and as soon as control goes out of method, they expire, i.e., exist no longer. Also, one cannot use the variable before its declaration. All variables must be used only after they are declared and initialized within the methods or blocks.

The lifetime of a variable is the time from its birth to its death, i.e., the time elapsed the moment it sprang to life to the time it lost. In the above case, the scope and lifetime for variables within block and method is the same.

Finally, it should be noted about blocks and scope that if an outer block has a variable by some name than the inner block cannot have a variable by the same name. Look at the program given below.

/* PROG 3.23 DEMO OF BLOCK AND SCOPE VER 2 */
class JPS23
{
   public static void main(String args[])
   {
       int x = 20;
       {
          int x = 40;
       }
   }
}
OUTPUT:

C:JPSch3>javac JPS23.java
JPS23.java:8: x is already defined in main(java.lang.String[])
                                      int x = 40;
^
1 error

Explanation: The program generates compilation error as x has already been defined within the main. One cannot redefine it in the inner block.

3.15 PONDERABLE POINTS

1.   In Java, '>>>'operator is called right shift with zero fill. It is a right shift operator which fills 0 instead of the sign of the number.

2.   Java is a strong type language, i.e., one cannot assign a lower data type to a higher without typecasting.

3.   By default, a floating point number is considered as double. To make it float, one needs to suffix f/F to the number.

4.   A valid combination of constants, variables and operators continues an expression.

5.   When several operators appear in one expression, evaluation takes place according to certain predefined rules, which specify the order of evaluation and are called precedence rules.

6.   The expression 'x++' executes faster than 'x+1' as the former requires a single machine instruction, such as INR (increment) to carry out the increment operation whereas, 'x+1' requires more instructions to carry out this operation.

7.   If an operand in an expression or a statement is converted to a higher rank data type causing upward type conversion, it is known as integral promotion. For example, int data type is converted to float.

8.   If an expression or a statement is converted to a lower rank data type, it is known as downward type conversion. It may occur when the left-hand side of an assignment has a lower rank data type compared to the values in the right-hand side. For example, assigning a float value to an int type variable. This is not possible in Java without explicit typecasting.

9.   Typecasting is also known as type coercion.

10. For using mathematical functions in Java one can use Math class.

11. "The" are where the variable can be accessed is called the scope of the variable. In other words, we can say portion of the program where the variable may be visible or available.

12. Lifetime of a variable is time from its birth to its death, i.e., the time elapsed the moment it sprang to life to the time it lost.

REVIEW QUESTIONS

1.   What are the different types of operators available in Java?

2.   What is the difference between '>>' and '>>>' operator?

3.   Explain how Boolean operator works in Java. How it is different from int type?

4.   Explain the functionality of instanceof operator. How it is used?

5.   Explain with suitable example why Java is called a strong type language.

6.   Explain demotion and promotion in typecasting.

7.   Discuss few mathematical functions in Java.

8.   Write a program to compute division of 2 without using any arithmetical operator.

9.   Find the sum of the digits if the given number is 12345 and the total is 1 + 2 + 3 + 4 + 5 = 15 = 1 + 5 = 6 in single digit. Do not use any looping structure.

10. Write a program that performs the following: If the user gives input as 1, the output is 2; if the input is 2 then the output becomes 1.

11. Give the precedence and associativity of Java operators.

12. What are Java separators? Give an example.

13. Suppose you declare a float variable f and initialize the value as 1.275 float test = 1.275; which cannot be compiled. How do you avoid the error?

14. If a = -1 and b = -2, then the statement result = (a>b)? a: b; What is the value in the result?

15. What is the result of the following operation:

System.out.println(3|4);

16. What will be the result of the expressions:

(a) 13&9

(b) 25|9

(c) -21%5

17. What is the octal equivalent of 1234?

(a) 01234

(b) 0X1234

(c) 0x1234

(d) 1234

18. What will be the output of the following program when it is executed with command line argument?

java contest how are you
  class contest
  {
    public static void main
     (String args[])
    {
        System.out.println
         (args[1]);
    }
  }

19. What will happen if you compile/run this code in your program:

int j = 089;

20. What will happen when you compile and run the program:

public class JPS
{
   public   static  void  main
     (String args)
   {
        System.out.println
          ("Welcome in Java");
   }
}

Multiple Choice Questions

1.   The number of binary arithmetic operators in Java is:

(a) 5

(b) 4

(c) 7

(d) 6

2.   The operator % can be applied only to

(a) float values

(b) double values

(c) (a) and (b)

(d) integral values

3.   Which of the following is not a valid expression?

(a) +0x3456

(b) -0345

(c) 23-

(d) +a

4.   Which of the following executes quickly?

(a) p++

(b) ++p

(c) (a) and (b)

(d) p + 1

5.   Identify the valid expression(s).

(a) a = 0

(b) a = b= 0

(c) a % = (x % 10)

(d) all of the above

6.   Integer division results in

(a) rounding of the fractional part of the quotient

(b) floating value

(c) truncating the fractional part of the quotient

(d) syntax error

7.   Which of the following is not a valid expression?

(a) ++(a+b)

(b) y--

(c) --x --

(d) + + p + q

8.   If the value of a = 10 and b = -1, the value of x after executing the following expression is:

x = (a! = 10) && (b = 1)

(a) 0

(b) 1

(c) -1

(d) None

9.   Which of the following is a better approach to do the operation I = I * 16?

(a) Multiply I by 16 and keep it

(b) Shift left by 4 bits 14.

(c) Add I, 16 times

(d) None of the above

10. The second operator of the operator % must always be a

(a) negative value

(b) non zero

(c) zero

(d) positive value

11. Typecasting is also known as

(a) type coercion

(b) type conversion

(c) neither (a) nor (b)

(d) none of the above

12. In Java, >>> operator is called

(a) left shift

(b) right shift

(c) left shift with zero fill

(d) right shift with zero fill

13. By default, a floating point number is considered as double. To make it float, you need to

(a) suffix f/F to the number

(b) prefix f/F to the number

(c) prefix d/D to the number

(d) suffix d/D to the number

14. int a = 15;
float b = 3.5 f, c;
c = a + b;
The code snippet shows the example of

(a) explicit type conversion

(b) implicit type conversion

(c) both (a) and (b) are correct

(d) none of the above

15. To check which object is of which class, which of the following is used

(a) sizeof

(b) instanceof

(c) comma

(d) none of the above

KEY FOR MULTIPLE CHOICE QUESTIONS

1.   a

2.   d

3.   c

4.   c

5.   d

6.   c

7.   c

8.   a

9.   b

10. b

11. a

12. d

13. a

14. b

15. b

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.81.43