Anda di halaman 1dari 29

Java Operators Simple Assignment Operator Assignment operator is the most common operator almost used with all

programming languages. It is represented by "=" symbol in Java which is used to assign a value to a variable lying to the left side of the assignment operator. But, If the value already exists in that variable then it will be overwritten by the assignment operator (=). This operator can also be used to assign the references to the objects. Syntax of using the assignment operator is: <variable> = <expression>; For example: int counter = 1; String name = "Nisha"; boolean rs = true; Shape s1 = new Shape(); // creates new object Shape s2 = s1; //assigning the reference of s1 to s2 counter = 5; // previous value is overwritten In all cases a value of right side is being assigned to its type of variable lying to the left side. You can also assign a value to the more than one variable simultaneously. For example, see these expressions shown as: x = y = z = 2; x =(y + z); Where the assignment operator is evaluated from right to left. In the first expression, value 2 is assigned to the variables "z", then "z" to "y", then "y" to "x" together. While in second expression, the evaluated value of the addition operation is assigned to the variable "x" initially then the value of variable "x" is returned. Apart from "=" operator, different kind of assignment operators available in Java that are know as compound assignment operators and can be used with all arithmetic or, bitwise and bit shift operators. Syntax of using the compound assignment operator is:
operand operation= operand

In this type of expression, firstly an arithmetic operation is performed then the evaluated value is assigned to a left most variable. For example an expression as x += y; is

equivalent to the expression as x = x + y; which adds the value of operands "x" and "y" then stores back to the variable "x". In this case, both variables must be of the same type. The table shows all compound assignment operators which you can use to make your code more readable and efficient. Operator Example
+= -= *= /= %= &= |= ^= <<= >>= >>>=

x x x x x x x x x x x y;

Equivalent Expression += y; x = (x + y); -= y; x = (x - y); *= y; x = (x * y); /= y; x = (x / y); %= y; x = (x % y); &= y; x = (x & y); != y; x = (x ! y); ^= y; x = (x ^ y); <<= y; x = (x << y); >>= y; x = (x >> y); >>>= x = (x >>> y);

Lets have an example implementing some compound assignment operators:


class CompAssignDemo{ public static void main(String[] args) { int x=5; int y=10; x += y; System.out.println("The addition is:"+ x); x -= y; System.out.println("The subtraction is:"+ x); x *= y; System.out.println("The multiplication is:"+ x); x /= y; System.out.println("The division is"+ x); x %= y; System.out.println("The remainder is:"+x); x &= y; System.out.println("The result of AND operation :"+ x); x |= y; System.out.println("The result of Bitwise inclusive OR operation :"+

x);

x); } }

x <<= y; System.out.println("The result of Signed left shift operation :"+

Arithmetic Operators Arithmetic Operators are used to perform some mathematical operations like addition, subtraction, multiplication, division, and modulo (or remainder). These are generally performed on an expression or operands. The symbols of arithmetic operators are given in a table: Symbol + * / % Name of the Operator Additive Operator Subtraction Operator Multiplication Operator Division Operator Remainder Operator Example n = n + 1; n = n - 1; n = n * 1; n = n / 1; n = n % 1;

The "+" operator can also be used to concatenate (to join) the two strings together. For example: String str1 = "Concatenation of the first"; String str2 = "and second String"; String result = str1 + str2; The variable "result" now contains a string "Concatenation of the first and second String". Lets have one more example implementing all arithmetic operators:

class ArithmeticDemo{ public static void main(String[] args) { int x = 4;

int y = 6; int z = 10; int rs = 0; rs = x + y; System.out.println("The addition of (x+y):"+ rs); rs = y - x; System.out.println("The subtraction of (y-x):"+ rs); rs = x * y; System.out.println("The multiplication of (x*y):"+ rs); rs = y / x; System.out.println("The division of (y/x):"+ rs); rs = z % y; System.out.println("The remainder of (z%x):"+ rs); rs = x + (y * (z/x)); System.out.println("The result is now :"+ rs); } }

Output of the Program: C:\nisha>javac ArithmeticDemo.java C:\nisha>java ArithmeticDemo The addition of (x + y): 10 The subtraction of (y - x): 2 The multiplication of (x * y): 24 The division of (y / x): 1 The remainder of (z % x): 4 The result is now : 16 Unary Operators: The unary operators requires only one operand to perform different kind of operations such as increasing/decreasing a value, negating an expression, or inverting a boolean value. These operators can not be used with final variables. There are different types of unary operators mentioned in the table given below: Symbol Name of the Operation Example

+ ++ -!

Operator Unary plus operator Unary minus operator Increment operator Decrement operator Logical compliment operator

indicates positive value (however, numbers int number = +1; are positive without this) number = negates an expression number; number = ++ increments a value by 1 number; number = -decrements a value by 1 number; inverts a boolean value

I. Unary Plus (+) Operator Unary plus operator (+) indicates positive value. This (+) operator is used to perform a type conversion operation on an operand. The type of the operand must be an arithmetic data type i.e. if a value of the integer operand is negative then that value can be produced as a positively applying unary plus (+) operator. For example, lets see the expressions shown as: int x = 0; int y = (25); x = (+y); In this expression, a negative value is assigned to the variable "y". After applying unary plus (+) operator on the operand "y", the value becomes 25 which indicates it as a positive value. However a number is positive without using unary plus (+) operator, if we have initially assigned it positively into the operand in the program. II. Unary minus (-) Operator Unary minus operator (-) indicates negative value and differ from the unary plus operator. This (-) operator is also used to perform a type conversion operation on an operand. If a value of the integer operand is positive then that value can be produced as a negatively applying unary minus (-) operator. For example, lets see the expressions shown as: int x = 0; int y = 25; x = (-y);

In this expression, a positive value is assigned tothe variable "y". After applying minus plus (-) operator on the operand "y", the value becomes "-25" which indicates it as a negative value. This behavior represents the number in two's complement format. III. Increment (++) and Decrement Operators The increment/decrement operators can be a prefix or a postfix .In a prefix expression (+ + x or -- x), an operator is applied before an operand while in a postfix expression (x ++ or x --) an operator is applied after an operand. In both conditions 1 is added to the value of the variable and the result is stored back to the variable. However both operators have the same effect as "x = x + 1;" Although there is a major difference between a prefix and a postfix expressions. In a prefix expression, a value is incremented first then this new value is restored back to the variable. On the other hand, In postfix expression the current value is assigned to a variable then it is incremented by 1 and restored back to the original variable. Lets make the things more clear with few examples ( i ) example using prefix unary operator:
public class Prefix{ public static void main(String[] args){ int x = 0; int y = 0; y = ++x; System.out.println("The value of x :" + x); System.out.println("The value of y:" + y); } }

Output of the Program: C:\nisha>javac Prefix.java C:\nisha>java Prefix The value of x :1 The value of y:1 The output of this program shows that always 1 is stored in both variables i.e. the value of "x" is incremented first then it is assigned to the variable "y". ( ii ) example using postfix unary operator:

public class Postfix{

public static void main(String[] args){ int x = 0; int y = 0; y = x++; System.out.println("The value of x :"+ x ); System.out.println("The value of y:" + y ); } }

Output of the Program: C:\nisha>java Postfix The value of x :1 The value of y:0 The output of the program indicates the value of variable "x" is stored first to the variable "y" then it is incremented by 1. IV. Logical Compliment (!) Operator The logical compliment (!) operator is also known as Boolean Negation Operator. It is used to invert the value of a boolean type operand i.e. the type of the operand must be boolean while using this operator,. If the value of the boolean operand is false, the ! operator returns true. But, if the value of the operand is true, the ! operator returns false. For example, lets see the statements shown as:
boolean result = (2>1); result = !result System.out.println("2 is geater than 1: " + result);

In these statements, the first expression returns true to the variable "result" but at the end of the program, the output is shown as false because the compliment (!) operator inverts the value of the variable "result". Lets have one more example using unary operators in different flavors:
class UnaryOperator { public static void main(String[] args){ int number = 1; int number1 = 0; System.out.println("result is now:" + number); number = -number; System.out.println("result is now:" + number);

++number; System.out.println("result is now:" + number); number1=number++; System.out.println("result is now:" + number); System.out.println("result of number1 is:" + number1); boolean result = (2>1); System.out.println("2 is geater than 1: " + result); System.out.println("2 is geater than 1: " + !result);

} }

Output of the Program: C:\nisha>javac UnaryOperator.java C:\nisha>java UnaryOperator result is now:1 result is now:-1 result is now:0 result is now:1 result of number1 is:0 2 is geater than 1: true 2 is geater than 1: false Equality and Relational Operators: Whenever we need to compare the results of two expressions or operands in a program then the equality and relational operators are used to know whether an operand is equal, not equal, greater than, less than to another operand. There are different types of equality and relational operators mentioned in a table given below: Symbol == != > < Name of the Operator Equal to Not equal to Greater than Less than Example Operation a==b a!=b a>b a<b a is equal to b a is not equal to b a is greater than b a is less than b

>= <=

a is greater a > = b than or equal to b a is less than or Less than or equal to a > = b equal to b Greater than or equal to

The Equality operator "= =" differs from an assignment operator "=" i.e. the equality operator is used to determine whether one operand is equal to another operand or not while the assignment operator is used to assign a value to a variable. All these operators are often used in the control structures such as if, do, while with the conditional operators to make decisional expressions. Lets have an example implementing these operators:

class EquityOperator { public static void main(String[] args){ int x = 5; int y = 10; if(x == y) System.out.println("value of x is equal to the value of y"); if(x != y)

System.out.println("value of x is not equal to the value of y"); if(x > y) System.out.println("value of x is greater then the value of y"); if(x < y) System.out.println("value of x is less then the value of y"); if(x >= y) System.out.println("value of x is greater then or equal to the value of y"); if(x <= y) System.out.println("value of x is less then or equal to the value of y"); } } Output of the Program: C:\nisha>javac EquityOperator.java C:\nisha>java EquityOperator value of x is not equal to the value of y value of x is less then the value of y value of x is less then or

equal to the value of y Conditional / Logical Operators Conditional operators return a true or a false value based on the state of the variables i.e. the operations using conditional operators are performed between the two boolean expressions. Symbol Name of the Operator & AND && Conditional-AND | OR || Conditional-OR ! NOT Ternary (shorthand for if?: then-else statement) I. AND (&) and Conditional-AND (&&) operators: The AND (&) operator is similar to the Conditional-AND operator (&&). Both of its operands are of boolean type, even these operands may be boolean expressions. Other Relational operators can also be used with these operators. Lets use a Truth Table to know the status of an output Op1 or Exp1 True False True False Op2 or Exp2 True False False True Result True False False False

If we analyze the table we find that result is always true only in case of first condition where both operands(or expressions) are true. On the other hand result is always false in other conditions. Note that this table works alike for & and && operators. In case of "&" operator, if both operands or expressions are true, the result is always true, otherwise it is false if either left-hand or right-hand operand is false. In case of "&&" operator, the result is also true, if both operands or expressions are true.

But this operator evaluates only the left-hand operand. It doesn't evaluate the right-hand operand if the left-hand operand is false then it will not jump to the right-hand operand to evaluate it, and will come out from that statement and read the next statement. That's why this mechanism is known as short-circuiting. Consider the following statements where the second expression returns false after evaluating only the left-hand operand. true && true = true; // both operands are evaluated false && true = false; // only leftoperand is evaluated But the "&" operator always evaluates both of its operands whether the first operand is true or false. Consider the following statements where the second expression returns false after evaluating the right-hand operand. true & true = true; // both operands are true true & false = false; // both operands are evaluated II. OR (|)and Conditional-OR (||)operators : Likewise, the OR operator(|) is similar to the Conditional-OR operator (||) and returns true, if one or another of its operand is true. Lets use a Truth Table to know the status of an output that works alike for "|" and "| |" operators. Op1 or Exp1 True False True False Op2 or Exp2 True False False True Result True False True True

If we analyze the table then we find that, result is always false only if both operands or expression are false. On the other hand, result is always true in rest of the other conditions. Still these exists a major difference in their mode of use: The "|" operator always evaluates both of its operands and returns true if one or other of its operand is true. Otherwise false if both the conditions are false. Consider the following statements where the second expression returns false after evaluating the righthand operand.

true | false = true; // left operand is true but both are evaluated false | false = false; //both operands are evaluated In case of "||" the result is also true, if one of the both operands is true. Otherwise it evaluates to false if both operands are false. But this operator conditionally evaluates the right-hand operand only if the left-hand operands is false. Like the Conditional-AND operator, this mechanism is also known as short-circuiting. Consider the following statements where the first expression returns true after evaluating the right-hand operand. false || true = true; // both operands are evaluated true || false = true; // only leftoperand is evaluated III. NOT ("!") operator : The NOT ("!") operator performs the boolean NOT operation on a single operand or an expression. It checks the boolean status of a current operand or expression and reverses the value of a boolean expression i.e. if the current value of an operand or expression is true then it reverses as false; but if the value of an operand or expression is false then it reverses as true. Consider the following example:

class BoolNotDemo { public static void main(String[] args){ int x = 2; int y = 1; boolean bl; bl = !(x > y); // bl is false System.out.println("x is not greater than y:"+bl); bl = !(y > x); // bl is true System.out.println("y is not greater than x:"+bl); }

Output of the Program: C:\nisha>javac BoolNotDemo.java C:\nisha>java BoolNotDemo x is not greater than y :

false y is not greater than x : true Download this program IV. ternary ("?:") operator Java supports another conditional operator that is known as the ternary operator "?:" and basically is used for an if-then-else as shorthand as boolean expression ? operand1 : operand2; The "?:" operator evaluates an expression which may also be an operand and returns operand1 if the expression is true; otherwise returns operand2, if the expression is false. We can understand this thing with the help of a diagram shown as:

If we analyze this diagram then we find that, operand1 is returned, if the expression is true; otherwise operand2 is returned in case of false expression. Lets have an example implementing some Logical operators:

class ConditionalOperator { public static void main(String[] args){ int x = 5; int y = 10, result=0; boolean bl = true; if((x == 5) && (x < y)) System.out.println("value of x is "+x); if((x == y) || (y > 1)) System.out.println("value of y is greater than the value of x"); result = bl ? x : y; System.out.println("The returned value is "+result); } }

Output of the Program: C:\nisha>javac ConditionalOperator.java C:\nisha>java ConditionalOperator value of x is 5 value of y is greater than the value of x The returned value is 5

Bitwise And Bit Shift Operators: In Java the bitwise and bit shift operators are used to manipulate the contents of variables at a bit level according to binary format. These operators perform bitwise and bit shift operations on integral type variables. There are different types of bitwise and bit shift operators available in the Java language summarized in the table. Symbol ~ & | ^ << >> >>> Name of the Operator Unary bitwise complement Bitwise AND Bitwise inclusive OR Bitwise exclusive OR Signed left shift Signed right sift Unsigned right shift Example
~op2 op1 & op2 op1 | op2 op1 ^ op2 op1 << op2 op1 >> op2 op1 >>> op2

Lets understand these operators in brief : I. Unary Bitwise Complement ("~") : The unary bitwise complement ("~") operator takes a single bit and inverts the level of that bit pattern and can be applied to any of the integral types. In this case, the value of a bit which is 0 become 1 and vice versa. For example the value 7 to a variable "x" is

represented in binary as 0111. But after applying "~" operator, the operation will be performed on each bit pattern which will return 1000 to the variable and the value 8 in the decimal format. Lets use the table to understand bitwise complement operation. Operand 0 1 1 0 Result 1 0 0 1

II. Bitwise AND (&): The Bitwise AND (&) operator performs the bitwise AND operation on each parallel pair of bits of two operands. The result is 1, if corresponding bits are 1 in both operands. Otherwise, the result is 0. Lets understand the AND operations using truth table: (AND) A 0 1 0 1 B 0 0 1 1 Result 0 0 0 1

III. Bitwise inclusive OR ( | ): The Bitwise inclusive OR ( | ) operator performs the bitwise inclusive OR operation on each parallel pair of bits of two operands. In each pair, the result is 1, if either first or second bit is 1 (or both are 1). Otherwise the result is 0. Lets see the table of using inclusive operations. Lets understand the inclusive OR operations using truth table: (OR) A 0 1 0 1 B 0 0 1 1 Result 0 1 1 1

IV. Bitwise exclusive OR (^):

The Bitwise exclusive OR (^) performs the exclusive or (XOR) operation i.e. The result in each position is 1 if the two bits are different, and 0 if they are the same. Lets understand the exclusive OR operations using truth table: A 0 1 0 1 B 0 0 1 1 Result 0 1 1 0

Bit Shifts Operators: The computer processor has the registers including a fixed number of available bits for storing numerals. So it is possible to "shift out" some bits of the register at one end, and "shift in" from the other end. The number of bits are shifted within the range mode of 32. The bit shifts operators are used to perform bitwise operations on the binary representation of an integer instead of its numerical value. In this operation, the bit shifts operators don't operate the pairs of corresponding bits rather the digits are moved, or shifted in a computer register either to the left or right according to the distance specified by a number. Sign Bit: A sign bit is found in the left most position of the number and is know as most significant bit (MSB) which indicates the status of a number i.e. the number is positive or negative. If the value of the sign bit is 0 then the number is positive; otherwise the number is negative, if the value of the sign bit is 1. Now lets understand these operators in brief. I. Signed Left Shift ("<<") : The signed left shift ("<<") operator shifts a bit (or bits) to the left by the distance specified in the right operand. In this case, the leftmost digit is shifted at the end of the register, and a new 0 is shifted into the rightmost position. No matter, the number is positive or negative; In both of case the leading bit position is always filled with a zero.

This diagram shows that, all bits of the upper position were shifted to the left by the distance of 1; and the Zero was shifted to the right most position. Thus the result is returned as 11100. Another expression "2<<2"; shifts all bits of the number 2 to the left placing a zero to the right for each blank place. Thus the value 0010 becomes 1000 or 8 in decimal. II. Signed Right Shift (">>") : The signed right shift (">>") operator shifts a bit (or bits) to the right by the distance specified in the right operand and fills the left most bit by the sign bit. In this case the rightmost bit (or bits) is shifted out, and a new 0 is filled with the sign bit into the highorder bits to the left position if the left operand is positive; otherwise 1, if the left operand is negative. This technique is known as sign extension.

This diagram shows that, all bits of the upper position were shifted to the right distance specified by 1; Since the sign bit of this number indicates it as a positive number so the 0 is shifted to the right most position. Thus the result is returned as 00011 or 3 in decimal. Another expression "2>>2"; shifts all bits of the number 2 to the right placing a zero to the left for each blank place. Thus the value 0010 becomes 0000 or 0 in decimal. When signed left or signed right shifting operation is performed then the sign bit is ignored i.e. all the bits except the sign bit can be moved but the sign bit stays the same. Thus a signed left or signed right shift (<< and >>) operator never causes a number to change its sign. A positive number will always stay positive and a negative number will always stay negative. But the result for a negative number is different. For example, if we take a negative number as -50 then this value is represented in binary as 11001110 then the expression "-50>>2"; will return the result as 11110011 or -13 in decimal. III. Unsigned Right Shift (">>>") The unsigned right shift (">>>") operator behave like the signed right shift operator. i.e. it shifts a bit (or bits) to the right. But unlike ">>" operator, this operator always shifts zeros into the leftmost position by the distance specified in the right operand. So the result of applying the >>>operator is always positive.

For example, the expression "14>>>2"; shifts all bits of the number 14 to the right placing a zero to the left for each blank place Thus the value 1110 becomes 0011 or 3 in decimal. An unsigned shift operation of a negative number generally returns the result in a positive number, because any unsigned right shift operation replaces the leading sign bit with a zero which indicates a positive number. Lets have an example where two variables "x" and "y" contain the value 11 and 12 respectively. Thus the binary value for each variable are as : x=1011 y=1100

public class BitwiseOperators { public BitwiseOperators( ) { int a = 11; //1 0 1 1 int b = 12; //1 1 0 0 System.out.println("a & b : "+(a & b)); System.out.println("a | b : "+(a | b)); System.out.println("a ^ b : "+(a ^ b)); System.out.println("~a : "+(~a)); System.out.println("a << b : "+(a << b)); System.out.println("a >> b : "+(a >> b)); System.out.println("a >>> b : "+(a >>> b)); } public static void main(String args[]){ new BitwiseOperators(); }

Output of the Program: C:\nisha>java BitwiseOperators a&b:8 a | b : 15 a^b:7 ~a : -12

a << b : 45056 a >> b : 0 a >>> b : 0 Type Comparison Operators: Java provides a run-time operator instanceof to compare a class and an instance of that class. This operator " instanceof" compares an object to a specified class type. The instanceof operator is defined to know about an object's relationship with a class. It evaluates to true, if the object or array is an instance of the specified type; otherwise it returns false. The instanceof operator can be used with the arrays and objects. It can't be used with primitive data types and values. Its signature is written as: object instanceof type Lets have an example :

class X { int i, j; } class Y { int i, j; } class Z extends X { int k; } public class InstanceOfDemo { public static void main(String args[]) { X x = new X(); Y y = new Y(); Z z = new Z(); if(x instanceof X) System.out.println("x is an instance of X"); X obj; obj = z; // X reference to z if(obj instanceof Z) System.out.println("obj is an instance of Z"); } }

.Output of the Program: C:\nisha>javac

InstanceOfDemo.java C:\nisha>java InstanceOfDemo x is an instance of X obj is an instance of Z

Operator Precedence: In Java, Operator Precedence is an evaluation order in which the operators within an expression are evaluated on the priority bases. Operators with a higher precedence are applied before operators with a lower precedence. For instance, the expression "4 + 5 * 6 / 3" will be treated as "4 + (5 * (6 / 3))" and 14 is obtained as a result. When two operators share an operand then operator with the higher precedence gets evaluated first. However, if the operators have the equal precedence in the same expression then that expression will be evaluated from left to right except the
assignment operators. For example a = b = c = 15

is treated as a = (b = (c = 15)).

The table below shows the list of operators that follow the precedence. Operators array index & parentheses access object postfix unary multiplicative additive bit shift relational Precedence [] ( ) . expr++ expr-++expr --expr +expr -expr ~ ! * / % + << >> >>> < > <= >= instanceof == != &

equality bitwise AND bitwise exclusive ^ OR bitwise inclusive | OR

logical AND logical OR ternary assignment

&& || ?: = += -= *= /= %= &= ^= |= <<= >>= >> >=

Lets see an example that evaluates an arithmetic expression according to the precedence order.

class PrecedenceDemo{ public static void main(String[] args){ int a = 6; int b = 5; int c = 10; float rs = 0; rs = a + (++b)* ((c / a)* b); System.out.println("The result is:" + rs); } }

The expression "a+(++b)*((c/a)*b)" is evaluated from right to left. Its evaluation order depends upon the precedence order of the operators. It is shown below:
a + (+ +b)*((c/a)*b) a+ (+ (c/a) +b)*((c/a)*b) a + (++b)*((c/a)* (c/a)*b b) a + (++b)*((c/a)* (++b)*((c/a)*b) b) a+(++b)*((c/a)*b) a+(++b)*((c/a)*b) (++b)

Output of the Program: C:\nisha>javac PrecedenceDemo.java C:\nisha>java PrecedenceDemo The result is: 42.0

The Modulus Operator

The modulus operator works on integers (and integer expressions) and yields the remainder when the first operand is divided by the second. In Java, the modulus operator is a percent sign, %. The syntax is exactly the same as for other operators: int quotient = 7 / 3; int remainder = 7 % 3; The first operator, integer division, yields 2. The second operator yields 1. Thus, 7 divided by 3 is 2 with 1 left over. The modulus operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by another: if x % y is zero, then x is divisible by y. Also, you can use the modulus operator to extract the rightmost digit or digits from a number. For example, x % 10 yields the rightmost digit of x (in base 10). Similarly x % 100 yields the last two digits. The % operator returns the remainder of two numbers. For instance 10 % 3 is 1 because 10 divided by 3 leaves a remainder of 1. You can use % just as you might use any other more common operator like + or -.
class Remainder { public static void main (String args[]) { int i = 10; int j = 3; System.out.println("i is " + i); System.out.println("j is " + j); int k = i % j; System.out.println("i%j is " + k); } }

Here's the output:


% javac Remainder.java % java Remainder i is 10 j is 3 i%j is 1

Perhaps surprisingly the remainder operator can be used with floating point values as well. It's surprising because you don't normally think of real number division as producing remainders. However there are rare times when it's useful to ask exactly how many times does 1.5 go into 5.5 and what's left over? The answer is that 1.5 goes into 5.5 three times with one left over, and it's that one which is the result of 5.5 % 1.5 in Java.

Operator Precedence in Java Java has well-defined rules for specifying the order in which the operators in an expression are evaluated when the expression has several operators. For example, multiplication and division have a higher precedence than addition and subtraction. Precedence rules can be overridden by explicit parentheses.

Precedence Order.
When two operators share an operand the operator with the higher precedence goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher precedence than addition.

Associativity.
When two operators with the same precendence the expression is evaluated according to its associativity. For example x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three variables with the value 17, since the = operator has right-to-left associativty (and an assignment statement evaluates to the value on the right hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has leftto-right associativity.

Precedence and associativity of Java operators.


The table below shows all Java operators from highest to lowest precedence, along with their associativity. Most programmers do not memorize them all, and even those that do still use parentheses for clarity.

Operator
[] . () ++ -++ -+ ! ~ () new

Description access array element access object member invoke a method post-increment post-decrement pre-increment pre-decrement unary plus unary minus logical NOT bitwise NOT cast object creation

Level Associativity

left to right

right to left

right to left

* / % + + << >> >>> < <= > >= instanceof == != & ^ | && || ?: = *= &= <<= += -= /= %= ^= |= >>= >>>=

multiplicative additive string concatenation shift relational type comparison equality bitwise AND bitwise XOR bitwise OR conditional AND conditional OR conditional assignment

4 5 6 7 8 9 10 11 12 13 14 15

left to right left to right left to right left to right left to right left to right left to right left to right left to right left to right right to left right to left

Order of evaluation.
In Java, the left operand is always evaluated before the right operand. Also applies to function arguments. Short circuiting. When using the conditional AND and OR operators (&& and ||), Java does not evaluate the second operand unless it is necessary to resolve the result. Allows statements like if (s != null && s.length() < 10) to work reliably. Programmers rarely use the non short-circuiting versions (& and |) with boolean expressions.

Precedence order gone awry.


Sometimes the precedence order defined in a language do not conform with mathematical norms. For example, in Microsoft Excel, -a^b is interpreted as (-a)^b instead of (a^b). So -1^2 is equal to 1 instead of -1, which is the values most mathematicians would expect. Microsoft acknowledges this quirk as a "design choice". One wonders whether the programmer was relying on the C precedence order in which unary operators have higher precedence than binary operators. This rule agrees with mathematical conventions for all C operators, but fails with the addition of the

exponentiation operator. Once the order was established in Microsoft Excel 2.0, it could not easily be changed without breaking backward compatability.

Mixing Data types


Mixed Type Operations We've assumed that the operands of a binary operator have the same type, and the result of evaluation an expression is the type of the operands. Thus, 3 + 4 evaluates to an int, while 3.0 + 4.0 evaluates to a double. What happens when you have one operand that's an int and the other is a double? In other words, what does 3 + 4.3 evaluate to? In Java, integer addition and double addition use different hardware. Even though they may seem the same to you, they are actually quite different to the computer. The computer wants to either add two int values or two double values. Java's solution (as in many other languages) is type promotion. Type Promotion When one operand is an int and the other is a double, Java creates a new temporary value that is the double version of the int operand. For example, suppose that we are adding dd + ii where ii is an int variable. Suppose the value of ii is 3. Java creates a temporary value 3.0 that is the corresponding double value. It then adds this temporary value to the other double operand. Notice that ii still remains an int after this addition. The temporary double is used to perform the addition, and then it is thrown away. Java has rules for doing type promotion that are somewhat more involved. Here's the basic rules: 1. 2. 3. 4. 5. 6. double float long int char or short byte

double is considered the "widest" value. byte is the narrowest. When you have two operands with types from this chart, pick the one with the lowest number (i.e., the widest). Thus, if one operand is short and another is long, then a temporary long value is made from short value and added to the long.

You might wonder, what are all these types? float is like double, but it has a much smaller range of values. However, it also uses less memory. In particular, float uses 4 bytes while double uses 8 bytes. Java seems to have a strong preference for double. short is a 2 byte int. int is 4 bytes. long is 8 bytes. However, we mostly use int in Java. byte is a 1 byte int. The more bytes a type has, the larger the range of valid values. The char data type in Java n Java, the data type used to store characters is char. However, C/C++ programmers beware:
char in Java is not the same as char in C or C++. In C/C++, char is an integer type that is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of characters known as ASCII still ranges from 0 to 127 as always, and the extended 8-bit character set, ISOLatin-1, ranges from 0 to 255. Since Java is designed to allow applets to be written for worldwide use, it makes sense that it would use Unicode to represent characters. Of course, the use of Unicode is somewhat inefficient for languages such as English, German, Spanish, or French, whose characters can easily be contained within 8 bits. But such is the price that must be paid for global portability. Note More information

about Unicode can be found at http://www.unicode.org.

Here is a program that demonstrates char variables: // Demonstrate char data type. class CharDemo { public static void main(String args[]) { char ch1, ch2; ch1 = 88; // code for X ch2 = 'Y'; System.out.print("ch1 and ch2: "); System.out.println(ch1 + " " + ch2); } } This program displays the following output: ch1 and ch2: X Y Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that corresponds to the letter X. As mentioned, the ASCII character set occupies the first 127 values in the Unicode character set. For this reason, all the "old tricks" that you have used with characters in the past will work in Java, too. Even though chars are not integers, in many cases you can operate on them as if they were integers. This allows you to add two characters together, or to increment the value of a character variable. For example, consider the following program:

// char variables behave like integers. class CharDemo2 { public static void main(String args[]) { char ch1; ch1 = 'X'; System.out.println("ch1 contains " + ch1); ch1++; // increment ch1

- 41 System.out.println("ch1 is now " + ch1); } } The output generated by this program is shown here: ch1 contains X ch1 is now Y

In the program, ch1 is first given the value X. Next, ch1 is incremented. This results in ch1 containing Y, the next character in the ASCII (and Unicode) sequence.

Booleans in java Java has a simple type, called Boolean, for logical values. It can have only one of two possible values, true of false. This is the type returned by all relational operators, such as a<b. Boolean is also the type required by the conditional expressions that govern the control statements such as if and for.

Here is a program that demonstrates the Boolean type:

// Demonstrate Boolean values. class BoolTest { public static void main (String args[]) { boolean b;

b = false; System.out.println(b is + b);

if ( b ) System.out.println(This is not executed. );

System.out.println(10 > 9 is + (10 > 9) ); } }

The output generated by this program is shown here:

b is false b is true This is executed. 10 > 9 is true

There are three interesting things to notice about this program. First, as you can see, when a boolean value is output by println(), true or false is displayed. Second, the value of a boolean variable is sufficient, by itself, to control the if statement. There is no need to write an if statement like this.

If (b == true)

Third, the outcome of a relational operator, such as <, is a boolean value. This is why the expression 10>9 displays the value true. Further, the extra set of parentheses around 10>9 is necessary because the + operator has a higher precedence than the >.

Relational Operator Precedence

Whenever a new operator is introduced you have to ask yourself where it fits in the precedence tree. If you look back at the example in the last section, you'll notice that it was implicitly assumed that the arithmetic was done before the comparison. Otherwise, for instance
boolean test8 = 6*4 < 3*8; // False. 24 is not less than 24

4 < 3 returns false which would then be multiplied by six and eight which would generate a compile time error because you can't multiply booleans. Relational operators are evaluated after arithmetic operators and before the assignment operator. == and != have slightly lower precedences than <, >, <= and >=. Here's the revised order: 1. 2. 3. 4. 5. *, /, % Do all multiplications, divisions and remainders from left to right. +, - Next do additions and subtractions from left to right. <, >, >=, <= Then any comparisons for relative size. ==, != Then do any comparisons for equality and inequality = Finally assign the right-hand side to the left-hand side

For example,
boolean b1 = 7 > 3 == true; boolean b2 = true == 7 > 3; b = 7 > 3;

Anda mungkin juga menyukai