ü Definition: Operators are special symbols that perform specific operations on one, two, or three variables called operands to get the desired result.
ü If an operator acts on a single variable, it is called unary operator and if it acts on two variables, it is called binary operator, and if it acts on three variables it is called ternary operator.
ü Java supports the following types of operators:
o Arithmetic operators
o Unary operators
o Assignment operator
o Relational operators
o Logical operators
o Boolean operators
o Bitwise operators
o Ternary operator or conditional operator
o Some special operators (dot, instanceof, new, cast operators).
Arithmetic Operators:
ü Arithmetic operators are used to perform fundamental arithmetic operations like addition, subtraction, and division etc. There are 5 arithmetic operators in Java. Since these operators act on two operands at a time, called binary operators.
ü The 5 operators are shown here: Consider a=13 and b=5.
Operator | Meaning | Example | Result |
+ | Addition | a+b | 18 |
- | Subtraction | a-b | 8 |
* | Multiplication | a*b | 65 |
/ | Division | a/b | 2.6 |
% | Modulus | a%b | 3 |
ü Addition operator (+) is also used to join two strings as,
String s1 = “Madhava”;
String s2 = “Bhavani”;
String s3 = s1+s2;
Now we get MadhavaBhavani in s3. In this case, + is called String concatenation
operator.
Unary Operators:
ü Unary operators act on only one operand. There are 4 kinds of unary operators: To better understand these operators see the following table:
Operator | Meaning | Purpose | Example | Result |
+ | Unary plus | Used to indicate positive value. | int x=6; System.out.println(x) | 6 |
- | Unary minus | Used to negate a given value. Negation means converting a negative value into positive and vice versa. | int x = 5; System.out.println(-x); System.out.println(-(-x)); | -5 5 |
++ | Increment | Used to increment the value of a variable by 1. | int x =1; ++x (pre increment) x++ (post increment) | x = 2 x = 3 |
-- | Decrement | Used to decrement the value of a variable by 1. | int x = 1; --x (pre decrement) x-- (post decrement) | x = 0 x = -1 |
ü Writing ++/-- before a variable is called pre incrementation/decrementation.
ü Writing ++/-- after a variable is called post incrementation/decrementation.
ü In pre incrementation/decrementation, incrementation/decrementation is done first and any operation is done next. In post incrementation/decrementation, all the other operations are done first. and incrementation/decrementation is done only at the end.
ü Let us take an example to understand it better:
int i=10;
sum = ++i; //First increments the value of i and then
//assigns the increment value to sum
sum = 11, i = 11
int i=10;
sum = i++; //First assign the value to the sum and then increments
sum = 10, i = 11
Assignment Operator:
ü This operator is used to store some values into a variable. It is used in 3 ways:
· It is used to store a value into a variable.
For ex: int x = 9;
· It is used to store the value of a variable into another variable.
For ex: int x = y; // here the value of y is stored into x.
· It is used to store the value of an expression into a variable.
For ex: int x = y+z-6; // here the expression y+z-6 is evaluated and its result is
// stored into x.
ü Note: We can not use more than one variable at the left hand side of the = operator.
For ex: x+y = 9; // invalid, since there is doubt for the compiler regarding
// where the value 10 is stored.
ü Some examples of assignment operator:
x = x+10 //Expand notation
x += 10 // Compact notation eliminates the repetition of the variable.
// += called addition assignment operator
value = value - discount;
value -= discount // -= called subtraction assignment operator.
Relational Operators:
ü These operators are used for the purpose of comparing. There are 6 types of relational operators in Java. To better understand these operators see the following table:
Operator | Meaning | Example |
< | less than | if(a<25 |
<= | less than or equal to | a<=b |
> | greater than | a>b |
>= | greater than or equal to | a>=5 |
== | equal to | if(x = = y) |
!= | not equal to | number!=100 |
Logical Operators:
ü Logical operators are used to construct compound conditions. A compound condition is a combination of several simple conditions. There are 3 types of logical operators.
ü See the following table, which demonstrate logical operators:
Operator | Meaning | Example |
&& | logical and | if(a = 1||b = 1) System.out.println( “Hi” ); |
|| | logical or | if(x>y&&y System.out.println( “Hi” ); |
! | logical not | if(!(str1.equals(str1)) System.out.println( “hi” ); |
Boolean Operators:
ü These operators act on boolean variables and produce boolean type result true or false.
ü There are 3 boolean operators shown here, consider a = true and b = false in the following table:
Operator | Meaning | Example | Result |
& | boolean and | a&b | false |
| | boolean or | a|b | true |
! | boolean not | !a | false |
Bitwise Operators:
ü Bitwise operators can be used to perform the operation at bit level ( 0 and 1). These operators act on only integer data types, i.e. byte, short, long, and int.
ü In case of these operators, the internal representation of numbers will be in the form of binary number system, which is different from the decimal number system used in our daily life.
ü Binary number system uses only 2 digits 0 and 1 to represent any number. On the other hand, decimal number system uses 10 digits from 0 to 9.
Operator | Operation |
& | Bitwise-AND |
| | Bitwise-OR |
^ | Exclusive-OR |
~ | One’s complement |
>> | Right shift |
<< | Left shift |
>>> | Unsigned right shift |
ü The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of each operation.
A | B | A&B | A|B | A^B | ~A |
0 | 0 | 0 | 0 | 0 | 1 |
1 | 0 | 0 | 1 | 1 | 0 |
0 | 1 | 0 | 1 | 1 | 1 |
1 | 1 | 1 | 1 | 0 | 0 |
Bitwise NOT:
ü Also called the bitwise complement, the unary NOT operator, ~, inverts all of the bits of its operand. For example, the number 42, which has the following bit pattern:
00101010
becomes
11010101
after the NOT operator is applied.
Bitwise AND:
ü The AND operator, &, produces a 1 bit if both operands are also 1. A zero is produced in all other cases. Here is an example:
00101010 42
& 00001111 15
--------------
00001010 10
Bitwise OR:
ü The OR operator, |, combines bits such that if either of the bits in the operands is a 1, then the resultant bit is a 1, as shown here:
00101010 42
| 00001111 15
--------------
00101111 47
THE JAVA LANGUAGE
The Bitwise XOR:
ü The XOR operator, ^, combines bits such that if exactly one operand is 1, then the result is 1. Otherwise, the result is zero.
ü The following example shows the effect of the ^. This example also demonstrates a useful attribute of the XOR operation. Notice how the bit pattern of 42 is inverted wherever the second operand has a 1 bit. Wherever the second operand has a 0 bit, the first operand is unchanged. You will find this property useful when performing some types of bit manipulations.
00101010 42
^ 00001111 15
-------------
00100101 37
Bitwise Left shift (<<):
ü The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times.
ü It has this general form:
value << num
Here, num specifies the number of positions to left-shift the value in value. That is,
the << moves all of the bits in the specified value to the left by the number of bit
positions specified by num.
ü For each left shift, the high-order bit is shifted out (and lost), and a zero is brought in on the right. This means that when a left shift is applied to an int operand, bits are lost once they are shifted past bit position 31. If the operand is a long, then bits are lost after bit position 63.
ü Java’s automatic type promotions produce unexpected results when you are shifting byte and short values. As we know, byte and short values are promoted to int when an expression is evaluated. Furthermore, the result of such an expression is also an int. This means that the outcome of a left shift on a byte or short value will be an int, and the bits shifted left will not be lost until they shift past bit position 31.
ü Furthermore, a negative byte or short value will be sign-extended when it is promoted to int. Thus, the high-order bits will be filled with 1’s. For these reasons, to perform a left shift on a byte or short implies that we must discard the high-order bytes of the int result.
ü Ex: int x = 10;
x = x<<2;
0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 |
x=10
0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
x<<2
fill 0’s
Now x = 40.
Bitwise right shift (>>):
ü The right shift operator, >>, shifts all of the bits in a value to the right a specified number of times.
ü Its general form is shown here
value >> num
Here, num specifies the number of positions to right-shift the value in value. That is,
the >> moves all of the bits in the specified value to the right the number of bit
positions specified by num.
ü Ex: int x = 10;
x = x>>2;
0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 |
x=10
0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
x>>2
fill 0’s
Now x = 2
Unsigned right shift (>>>):
ü This operator also shifts the bits in a value towards right a specified number of times. But it stores 0 in the sign bit.
ü Since it always fills 0 in the sign bit, that’s why it is called zero fill right shift operator.
ü Suppose, if we apply >>> on a positive number it gives same output as that of >>. But in case of negative numbers, the output will be positive, since the sign bit is replaced by a 0.
Program: Demonstrate various bitwise operators
class Bits
{
public static void main(String args[])
{
byte x,y;
x=42;
y=15;
System.out.println(“~x=” + (~x));
System.out.println(“x&y =” + (x&y));
System.out.println(“x|y =” + (x|y));
System.out.println(“x^y =” + (x^y));
System.out.println(“x<<2 =” + (x<<2));
System.out.println(“x>>2 =” + (x>>2));
System.out.println(“x>>> =” + (x>>>2));
}
}
Output: C:\Madhava>java Bits
~x=-43
x&y =10
x|y =47
x^y =37
x<<2 =168
x>>2 =10
x>>> =10
Ternary Operator or Conditional operator (?:)
ü Java includes a special ternary (three-way) operator that can replace certain types of if-then-else statements. This operator is the ?:, and it works in Java much like it does in C, C++, and C#.
ü The ?: has this general form:
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value. If
expression1 is true, then expression2 is evaluated; otherwise, expression3 is
evaluated.
Program: Demonstrate ?: operator
class Ternary
{
public static void main(String args[])
{
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of "+ i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("\nAbsolute value of " + i + " is " + k);
}
}
Output: Absolute value of 10 is 10
Absolute value of -10 is 10
Dot (.) Operator:
ü This operator can be used in 2 ways:
- We know that each class contains variables or methods. To refer to the variables or methods of a class, we can use dot operator:
Syntax:
classname.variablename
or
objectname.variablename in case of variables
classname.method name
or
objectname.methodname in case of methods
- We know a package contains classes. we can use dot (.) operator to refer to the class of a package.
Syntax:
packagename.classname
Ex:
java.io.FileReader // FileReader is a class in the package java.io.
instanceof Operator:
ü This operator is used to test if an object belongs to a class or not. Note that the word instance means object. This operator can also be used to check if an object belongs to an interface or not.
ü Syntax: boolean variable = object instanceof class;
boolean variable = object instanceof interface;
ü Ex: boolean x = emp instanceof Employee;
new Operator:
ü new operator is often used to create objects to classes. we know that objects are created on heap memory by JVM, at runtime (dynamically).
ü Syntax: classname obj = new classname( );
ü Ex: Madhava m = new Madhava( ); // m is an object of Madhava class
Cast Operator:
ü Cast operator is used to convert one datatype into another datatype. This operator can be used by writing datatype inside braces.
ü For example, double x = 20.34:
int y = x; // error - because datatypes of x and y are different.
To store x value into y we have to first convert the datatype of x (double) into
datatype of y (int) by writing inside braces as,
int y = (int)x;
Operator Precedence:
Operator | Associativity | Group | Priority |
( ) [] . | left to right | Top | 1 |
++ -- - + ~ ! | right to left | Unary | 2 |
* / % | left to right | Multiplicative | 3 |
+ - | left to right | Additive | 4 |
>> >>> << | right to left | Shift | 5 |
< <= > >= | left to right | Relational | 6 |
== != | left to right | Equality | 7 |
& ^ | | left to right | Boolean and Bitwise | 8 |
&& || | left to right | Logical | 9 |
?: | right to left | Conditional | 10 |
= *= /= %= += -= | left to right | Assignment | 11 |
Technical Interview Questions and Answers:
1. How are positive and negative numbers represented internally?
Ans: Positive numbers are represented in binary using 1’s complement notation and negative numbers are represented by using 2’s complement notation.
2. What is the difference between >> and >>>?
Ans: Both bitwise right shift operator (>>) and unsigned right shift operator (>>>) are used to shift the bits towards right. The difference is that >> will protect the sign bit whereas the >>> operator will not protect the sign bit. It always fills 0 in the sign bot.
3. Can a double value be cast to a byte?
Ans: Yes.
4. Can a byte object be cast to a double value?
Ans: No, an object can not be cast to a double value.
5. What is the difference between pre ++/-- and post ++/-- operators?
Ans: In pre incrementation/decrementation, incrementation/decrementation is done first and any operation is done next. In post incrementation/decrementation, all the other operations are done first. and incrementation/decrementation is done only at the end.
6. What is the value of x and y, if x = 5 and y =++ x?
Ans: x = 6 and y = 6.
7. What is the value of x and z, if x = 5 and z = x++?
Ans: x = 6 and z = 5.
8. What is an operator and what are the various types of operators?
Ans: See at first.
9. Character literals are stored as Unicode characters?
Ans: True.
10. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Ans: Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
11. What are order of precedence and Associativity, and how are they used?
Ans: Order of precedence determines the order in which operators are evaluated in expressions. Associativity determines whether an expression is evaluated left-to-right or right-to-left
12. What is the difference between the Boolean & operator and the && operator?
Ans: If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated, the && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
13. Which Java operator is right associative?
Ans: The = operator is right associative.
14. How does Java handle integer overflows and underflows?
Ans: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
15. Is &&= a valid Java operator?
Ans: No, it is not.
- J Madhava Rao