OPERATORS IN JAVA
Operators
Now that you've learned how to declare and initialize variables, you probably want to know how to do something with them. Learning the operators of the Java programming language is a good place to start. Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.Assignment, Arithmetic, and Unary Operators
Operator Precedence Operators Precedence postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
In general-purpose programming, certain operators tend to appear more frequently than others; for example, the assignment operator "=
" is far more common than the unsigned right shift operator ">>>
". With that in mind, the following discussion focuses first on the operators that you're most likely to use on a regular basis, and ends focusing on those that are less common. Each discussion is accompanied by sample code that you can compile and run. Studying its output will help reinforce what you've just learned.
The Simple Assignment OperatorOne of the most common operators that you'll encounter is the simple assignment operator "Equality, Relational, and Conditional Operators=
". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left:
This operator can also be used on objects to assign object references, as discussed in Creating Objects.int cadence = 0; int speed = 0; int gear = 1;
The Arithmetic Operators
The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only symbol that might look new to you is "%
", which divides one operand by another and returns the remainder as its result.
The following program,+ additive operator (also used for String concatenation) - subtraction operator * multiplication operator / division operator % remainder operatorArithmeticDemo
, tests the arithmetic operators.
You can also combine the arithmetic operators with the simple assignment operator to create compound assignments. For example,class ArithmeticDemo { public static void main (String[] args){ int result = 1 + 2; // result is now 3 System.out.println(result); result = result - 1; // result is now 2 System.out.println(result); result = result * 2; // result is now 4 System.out.println(result); result = result / 2; // result is now 2 System.out.println(result); result = result + 8; // result is now 10 result = result % 7; // result is now 3 System.out.println(result); } }
x+=1;
andx=x+1;
both increment the value ofx
by 1.The+
operator can also be used for concatenating (joining) two strings together, as shown in the followingConcatDemo
program:
By the end of this program, the variableclass ConcatDemo { public static void main(String[] args){ String firstString = "This is"; String secondString = " a concatenated string."; String thirdString = firstString+secondString; System.out.println(thirdString); } }
thirdString
contains "This is a concatenated string.", which gets printed to standard output.The Unary Operators
The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.
The following program,+ Unary plus operator; indicates positive value (numbers are positive without this, however) - Unary minus operator; negates an expression ++ Increment operator; increments a value by 1 -- Decrement operator; decrements a value by 1 ! Logical complement operator; inverts the value of a booleanUnaryDemo
, tests the unary operators:
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The codeclass UnaryDemo { public static void main(String[] args){ int result = +1; // result is now 1 System.out.println(result); result--; // result is now 0 System.out.println(result); result++; // result is now 1 System.out.println(result); result = -result; // result is now -1 System.out.println(result); boolean success = false; System.out.println(success); // false System.out.println(!success); // true } }
result++;
and++result;
will both end inresult
being incremented by one. The only difference is that the prefix version (++result
) evaluates to the incremented value, whereas the postfix version (result++
) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.The following program,PrePostDemo
, illustrates the prefix/postfix unary increment operator:
class PrePostDemo { public static void main(String[] args){ int i = 3; i++; System.out.println(i); // "4" ++i; System.out.println(i); // "5" System.out.println(++i); // "6" System.out.println(i++); // "6" System.out.println(i); // "7" } }
The Equality and Relational OperatorsThe equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use "Bitwise and Bit Shift Operators==
", not "=
", when testing if two primitive values are equal.
The following program,== equal to != not equal to > greater than >= greater than or equal to < less than <= less than or equal to
ComparisonDemo
, tests the comparison operators:
Output:class ComparisonDemo { public static void main(String[] args){ int value1 = 1; int value2 = 2; if(value1 == value2) System.out.println("value1 == value2"); if(value1 != value2) System.out.println("value1 != value2"); if(value1 > value2) System.out.println("value1 > value2"); if(value1 < value2) System.out.println("value1 < value2"); if(value1 <= value2) System.out.println("value1 <= value2"); } }
The Conditional Operatorsvalue1 != value2 value1 < value2 value1 <= value2
The&&
and||
operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.
The following program,&& Conditional-AND || Conditional-OR
ConditionalDemo1
, tests these operators:
Another conditional operator isclass ConditionalDemo1 { public static void main(String[] args){ int value1 = 1; int value2 = 2; if((value1 == 1) && (value2 == 2)) System.out.println("value1 is 1 AND value2 is 2"); if((value1 == 1) || (value2 == 1)) System.out.println("value1 is 1 OR value2 is 1"); } }
?:
, which can be thought of as shorthand for anif-then-else
statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "IfsomeCondition
istrue
, assign the value ofvalue1
toresult
. Otherwise, assign the value ofvalue2
toresult
."
The following program,ConditionalDemo2
, tests the?:
operator:
Becauseclass ConditionalDemo2 { public static void main(String[] args){ int value1 = 1; int value2 = 2; int result; boolean someCondition = true; result = someCondition ? value1 : value2; System.out.println(result); } }
someCondition
is true, this program prints "1" to the screen. Use the?:
operator instead of anif-then-else
statement if it makes your code more readable; for example, when the expressions are compact and without side-effects (such as assignments).
The Type Comparison Operator instanceof
Theinstanceof
operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
The following program,InstanceofDemo
, defines a parent class (namedParent
), a simple interface (namedMyInterface
), and a child class (namedChild
) that inherits from the parent and implements the interface.
Output:class InstanceofDemo { public static void main(String[] args) { Parent obj1 = new Parent(); Parent obj2 = new Child(); System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent)); System.out.println("obj1 instanceof Child: " + (obj1 instanceof Child)); System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface)); System.out.println("obj2 instanceof Parent: " + (obj2 instanceof Parent)); System.out.println("obj2 instanceof Child: " + (obj2 instanceof Child)); System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface)); } } class Parent{} class Child extends Parent implements MyInterface{} interface MyInterface{}
When using theobj1 instanceof Parent: true obj1 instanceof Child: false obj1 instanceof MyInterface: false obj2 instanceof Parent: true obj2 instanceof Child: true obj2 instanceof MyInterface: true
instanceof
operator, keep in mind thatnull
is not an instance of anything.
The Java programming language also provides operators that perform bitwise and bit shift operations on integral types. The operators discussed in this section are less commonly used. Therefore, their coverage is brief; the intent is to simply make you aware that these operators exist.The unary bitwise complement operator "~
" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, abyte
contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".
The signed left shift operator "<<
" shifts a bit pattern to the left, and the signed right shift operator ">>
" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>
" shifts a zero into the leftmost position, while the leftmost position after">>"
depends on sign extension.
The bitwise&
operator performs a bitwise AND operation.
The bitwise^
operator performs a bitwise exclusive OR operation.
The bitwise|
operator performs a bitwise inclusive OR operation.
The following program,BitDemo
, uses the bitwise AND operator to print the number "2" to standard output.
class BitDemo { public static void main(String[] args) { int bitmask = 0x000F; int val = 0x2222; System.out.println(val & bitmask); // prints "2" } }
0 comments:
Post a Comment