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 |
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.
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 |
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 |
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)
Few programs can be presented based on these operators.
Explanation: The program is self-explanatory.
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.
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.
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.
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 |
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.
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.
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.
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 |
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 |
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).
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 |
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.
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 |
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:
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.
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 |
y = ++ x;
is equivalent to x = x + 1; y = x;
the value of x
is incremented first then it is assigned to y
.
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 |
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 |
For example, consider the following program:
Explanation: For explanation, see the following table, if both the input and output are 1.
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 |
Explanation: For explanation, see the following table. If any of the input is 1 then the output will be 1.
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 |
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:
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.
Explanation: Representing b1 in binary 8 bits and doing bitwise 1's complement:
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:
Taking 1's complement of the above value:
Now adding 1 to it, the result is:
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:
Explanation: The binary representation of 42 in 8 bits.
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:
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.
Explanation: Look at the binary representation of 42 in 8 bit format as given below.
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:
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.
Explanation: Internally, -1 is represented as all ones. In 32 bit format, it can be shown as follows:
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:
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.
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
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;
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.
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.
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.
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
18.219.81.43