SlideShare a Scribd company logo
Operators and
Assignments

Ben Abdallah Helmi Architect J2EE
Evaluation Order
1. int [] a = { 4, 4 };
2. int b = 1;
3. a[b] = b = 0;
the value 0 is first assigned to the variable called
b then the value 0 is assigned into the last
element of the array a .
.
Ben Abdallah Helmi Architect J2EE
Overview of the Java Operators

Ben Abdallah Helmi Architect J2EE
The Unary Operators
The increment and decrement operators: ++ and -The unary plus and minus operators: + and -

The bitwise inversion operator: ~
The boolean complement operator: !

The cast: ()
Ben Abdallah Helmi Architect J2EE
The Increment and Decrement Operators: ++ and --

Ben Abdallah Helmi Architect J2EE
The Unary Plus and Minus Operators: + and 1. x = -3;
2. y = +3;
3. z = -(y + 6);
the value of z is initialized to −9.

Ben Abdallah Helmi Architect J2EE
The Bitwise Inversion Operator: ~
For example, applying this operator to a byte
containing 00001111 would result in the value
11110000. The same simple logic applies, no
matter how many bits there are in the value
being operated on. This operator is often used
in conjunction with shift operators
(<<, >>, and >>>) to perform bit
manipulation, for example, when driving I/O
ports.
Ben Abdallah Helmi Architect J2EE
The Boolean Complement Operator: !
1. Vector v = new Vector();
2. v.add ("Hello");
3. String s = (String)v.get(0);

Ben Abdallah Helmi Architect J2EE
The Arithmetic Operators

Ben Abdallah Helmi Architect J2EE
The Multiplication and Division
Operators: * and /
1. int a = 12345, b = 234567, c, d;
2. long e, f;
3.
4. c = a * b / b; // this should equal a, that is, 12345
5. d = a / b * b; // this should also equal a
6. System.out.println("a is " + a +
7. "nb is " + b +
8. "nc is " + c +
9. "nd is " + d);
10.
11. e = (long)a * b / b;
12. f = (long)a / b * b;
13. System.out.println(
14. "ne is " + e +
15. "nf is " + f);
The output from this code is
a is 12345
b is 234567
c is -5965
d is 0
e is 12345
f is 0
Ben Abdallah Helmi Architect J2EE
The Modulo Operator: %

Ben Abdallah Helmi Architect J2EE
The Addition and Subtraction
Operators: + and -

To prepare for the Certification Exam questions, and to use the + operator effectively in your
own programs, you should understand the following points:
•

•

•
•

For a + expression with two operands of primitive numeric type, the result
o Is of a primitive numeric type.
o Is at least int, because of normal promotions.
o Is of a type at least as wide as the wider of the two operands.
o Has a value calculated by promoting the operands to the result type and then
performing the addition using that type. This might result in overflow or loss of
precision.
For a + expression with any operand that is not of primitive numeric type,
o At least one operand must be a String object or literal; otherwise, the expression is
illegal.
o Any remaining non-String operands are converted to String, and the result of the
expression is the concatenation of all operands.
To convert an operand of some object type to a String, the conversion is performed by
invoking the toString() method of that object.
To convert an operand of a primitive type to a String, the conversion is performed by a static
method in a container class, such as Integer.toString(). J2EE
Ben Abdallah Helmi Architect
Arithmetic Error Conditions
In exceptional conditions, the following rules apply:

•

Integer division by zero, including modulo (%) operation, results in an ArithmeticException.

•

No other arithmetic causes any exception. Instead, the operation proceeds to a result, even
though that result might be arithmetically incorrect.

•

Floating-point calculations represent out-of-range values using the IEEE 754 infinity, minus
infinity, and Not a Number (NaN) values. Named constants representing these are declared
in both the Float and Double classes.

•

Integer calculations, other than division by zero, that cause overflow or a similar error
simply leave the final, typically truncated bit pattern in the result. This bit pattern is derived
from the operation and the number representation and might even be of the wrong sign.
Because the operations and number representations do not depend upon the
platform, neither do the result values under error conditions.

These rules describe the effect of error conditions, but some additional significance is associated
with the NaN values. NaN values are used to indicate that a calculation has no result in
ordinary arithmetic, such as some calculations Architect J2EE infinity or the square root of a
Ben Abdallah Helmi involving
negative number.
Arithmetic Promotion of Operands

The diagram in Figure 2.2 shows the process by which a byte is shifted right. First the
byte is promoted to an int, which is done treating the byte as a signed quantity.
Next, the shift occurs, and 0 bits are indeed propagated into the top bits of the
result—but these bits are not part of the original byte. When the result is cast
down to a byte again, the high-order bits of that byte appear to have been created
by a signed shift right, rather than an unsigned one. This is why you should
generally not use the logical right-shift operator with operands smaller than an int:
It is unlikely to produce the result you expected.
Ben Abdallah Helmi Architect J2EE
The Ordinal Comparisons Operators:
<, <=, >, and >=
int p = 9;
int q = 65;
int r = -12;
float f = 9.0F;
char c = ‘A’;
the following tests all return true:
p<q
f<q
f <= c
c>r
c >= q

Notice that arithmetic promotions are applied when these operators are used.
This is entirely according to the normal rules discussed in Chapter 4. For
example, although it would be an error to attempt to assign, say, the float
value 9.0F to the char variable c, it is perfectly acceptable to compare the two.
To achieve the result, Java promotes the smaller type to the larger type; hence
the char value ‘A’ (represented by the Unicode value 65) is promoted to a float
65.0F. The comparison is then performed on the resulting float values.
Ben Abdallah Helmi Architect J2EE
The instanceof Operator
The instanceof operator tests the class of an object at runtime. The left argument can be any
object reference expression, usually a variable or an array element, whereas the right operand
must be a class, interface, or array type. You cannot use a java.lang.Class object reference
or a String representing the name of the class as the right operand. A compiler error results if
the left operand cannot be cast to the right operand.

If the left argument of the instanceof operator is a null value, the instanceof test simply returns
false; it does not cause an exception.
Ben Abdallah Helmi Architect J2EE
The Equality Comparison Operators:
== and !=
The operators == and != test for equality and
inequality, respectively, returning a boolean value. For primitive
types, the concept of equality is quite straightforward and is subject to
promotion rules so that, for example, a float value of 10.0 is considered
equal to a byte value of 10. For variables of object type, the “value” is
taken as the reference to the object—typically, the memory address.
You should not use these operators to compare the contents of
objects, such as strings, because they will return true if two references
refer to the same object, rather than if the two objects have equivalent
value. Object comparisons compare the data of two objects, whereas
reference comparisons compare the memory locations of two objects.

To achieve a content or semantic comparison, for example, so that two
different Double objects containing the value 1234 are considered
equal, you must use the equals() method rather than the == or !=
operator.
Ben Abdallah Helmi Architect J2EE
The Bitwise Operators
The bitwise operations calculate each bit of their
results by comparing the corresponding bits of
the two operands on the basis of these three
rules:
• For AND operations, 1 AND 1 produces 1. Any
other combination produces 0.
• For XOR operations, 1 XOR 0 produces 1, as does
0 XOR 1. (All these operations are commutative.)
Any other combination produces 0.
• For OR operations, 0 OR 0 produces 0. Any other
combination produces 1.
Ben Abdallah Helmi Architect J2EE
Boolean Operations
• For AND operations, true AND true produces
true. Any other combination produces false.
• For XOR operations, true XOR false produces
true, and false XOR true produces true.Other
combinations produce false.
• For OR operations, false OR false produces
false. Any other combination produces true.

Ben Abdallah Helmi Architect J2EE
The Short-Circuit Logical Operators

The main difference between the & and && and between the | and || operators is that the right operand might not be
evaluated in the latter cases. We will look at how this happens in the rest of this section. This behavior is based on two
mathematical rules that define conditions under which the result of a boolean AND or OR operation is entirely determine
by one operand without regard for the value of the other:
•
For an AND operation, if one operand is false, the result is false, without regard to the other
operand.
•
For an OR operation, if one operand is true, the result is true, without regard to the other
operand.
To put it another way, for any boolean value X,
•
false AND X = false
•
true OR X = true
1. if (s != null) {
2. if (s.length() > 20) {
3. System.out.println(s);
4. }
5. }
However, the same operation can be coded very succinctly like this:
1. if ((s != null) && (s.length() > 20)) {
2. System.out.println(s);
Ben Abdallah Helmi Architect J2EE
3. }
//first example:
1. int val = (int)(2 * Math.random());
2. boolean test = (val == 0) || (++val == 2);
3. System.out.println("test = " + test + "nval = " + val);
//second example:
1. int val = (int)(2 * Math.random());
2. boolean test = (val == 0) | (++val == 2);
3. System.out.println("test = " + test + "nval = " + val);
The first example will sometimes print
test = true
val = 0
and sometimes it will print
test = true
val = 2
The second example will sometimes print
test = true
val = 1
and sometimes it will print
test = true
val = 2
Ben Abdallah Helmi Architect J2EE
The Conditional Operator
The conditional operator—?:— (also known as a ternary operator, because it takes three operands) provides a way to code
simple conditions (if/else) into a single expression. The (boolean) expression to the left of the ? is evaluated. If true, the
result of the whole expression is the value of the expression to the left of the colon; otherwise, it is the value of the
expression to the right of the colon. The expressions on either side of the colon must be assignment-compatible with
the result type.
For example, if a, b, and c are int variables, and x is a boolean, then the statement a = x
? b : c; is directly equivalent to the textually longer version:
1. if (x) {
2. a = b;
3. }
4. else {
5. a = c;
6. }
Of course x, a, b, and c can all be complex expressions if you desire.
Here are the points you should review for handling conditional operators in an exam question, or to use them properly in a
program. In an expression of the form a = x ? b : c;
•
The types of the expressions b and c should be compatible and are made identical through
conversion.
•
The type of the expression x should be boolean.
•
The types of the expressions b and c should be assignment-compatible with the type of a.
•
The value assigned to a will be b if x is true or will be c if x is false.
Now that we have discussed the conditional (ternary) operator, only one group of operators remains: the assignment
Ben Abdallah Helmi Architect J2EE
operators.
The Assignment Operators
1. byte x = 2;
2. x += 3;
If this had been written using the longhand approach
1. byte x = 2;
2. x = (byte)(x + 3);
The assignment operators in Java are considered to be operators
because they have a resulting value. So, given three int variables
a, b, and c, the statement a = b = c = 0; is entirely legal. It is
executed from right to left, so that first 0 is assigned into the
variable c. After it has been executed, the expression c = 0 takes
the value that was assigned to the left side—that is, 0. Next, the
assignment of b takes place, using the value of the expression to
the right of the equal sign—again, 0. Similarly, that expression
takes the value that was assigned, so finally the variable a is also
Ben Abdallah Helmi Architect J2EE
set to 0.

More Related Content

PPTX
Chapter 3 : Programming with Java Operators and Strings
PPT
CBSE Class XI :- Operators in C++
PPT
Operators and Expressions in C++
PPT
Expressions in c++
PPT
Operator & Expression in c++
PDF
Java basic operators
PPTX
Operators and expressions in C++
PPT
Chapter 3 : Programming with Java Operators and Strings
CBSE Class XI :- Operators in C++
Operators and Expressions in C++
Expressions in c++
Operator & Expression in c++
Java basic operators
Operators and expressions in C++

What's hot (19)

PPTX
Operator.ppt
PPTX
Operators in c++
PPT
C Sharp Jn (2)
PPT
C Prog. - Operators and Expressions
PPTX
Expression and Operartor In C Programming
PPTX
Operators and Expressions
PDF
Operators in c programming
PPTX
Operators in java presentation
PPTX
05 operators
PPTX
Oop using JAVA
PPTX
Operators and expressions
ODP
operators in c++
PDF
Operators in java
PPTX
Operators in C Programming
PPTX
Precedence and associativity (Computer programming and utilization)
PPT
Operation and expression in c++
PDF
Chapter 5 - Operators in C++
Operator.ppt
Operators in c++
C Sharp Jn (2)
C Prog. - Operators and Expressions
Expression and Operartor In C Programming
Operators and Expressions
Operators in c programming
Operators in java presentation
05 operators
Oop using JAVA
Operators and expressions
operators in c++
Operators in java
Operators in C Programming
Precedence and associativity (Computer programming and utilization)
Operation and expression in c++
Chapter 5 - Operators in C++
Ad

Similar to chap 2 : Operators and Assignments (scjp/ocjp) (20)

PPTX
Chapter 3
PPTX
Chapter 3:Programming with Java Operators and Strings
PPT
3.OPERATORS_MB.ppt .
DOCX
Operators
PPT
4_A1208223655_21789_2_2018_04. Operators.ppt
PPTX
Java chapter 3
PPT
Java operators
PDF
Java basic operators
PPTX
Pj01 4-operators and control flow
PDF
itft-Operators in java
PPTX
Java Operators with Simple introduction.pptx
PPTX
OOPJ_PPT2,JAVA OPERATORS TPYE WITH EXAMPLES.pptx
PPTX
L3 operators
PPTX
L3 operators
PPTX
L3 operators
PPTX
Java Operators with Simple introduction.pptx
PPTX
Computer programming 2 Lesson 7
PDF
Java unit 3
PPT
object oriented programming java lectures
PPTX
PPT ON JAVA AND UNDERSTANDING JAVA'S PRINCIPLES
Chapter 3
Chapter 3:Programming with Java Operators and Strings
3.OPERATORS_MB.ppt .
Operators
4_A1208223655_21789_2_2018_04. Operators.ppt
Java chapter 3
Java operators
Java basic operators
Pj01 4-operators and control flow
itft-Operators in java
Java Operators with Simple introduction.pptx
OOPJ_PPT2,JAVA OPERATORS TPYE WITH EXAMPLES.pptx
L3 operators
L3 operators
L3 operators
Java Operators with Simple introduction.pptx
Computer programming 2 Lesson 7
Java unit 3
object oriented programming java lectures
PPT ON JAVA AND UNDERSTANDING JAVA'S PRINCIPLES
Ad

More from It Academy (20)

PPTX
Chapter 12:Understanding Server-Side Technologies
PPTX
Chapter 10:Understanding Java Related Platforms and Integration Technologies
PPTX
Chapter 11:Understanding Client-Side Technologies
PPTX
Chapter 9:Representing Object-Oriented Concepts with UML
PPTX
Chapter8:Understanding Polymorphism
PPTX
Chapter 7:Understanding Class Inheritance
PPTX
Chapter 6:Working with Classes and Their Relationships
PPTX
Chapter 5:Understanding Variable Scope and Class Construction
PPTX
Chapter 4:Object-Oriented Basic Concepts
PPTX
Chapter 2 : Programming with Java Statements
PPTX
Chapter 1 :
PPTX
chap 10 : Development (scjp/ocjp)
PPTX
Chap 9 : I/O and Streams (scjp/ocjp)
PPTX
chap 8 : The java.lang and java.util Packages (scjp/ocjp)
PPTX
chap 7 : Threads (scjp/ocjp)
PPTX
chap 6 : Objects and classes (scjp/ocjp)
PPTX
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
PPTX
chap4 : Converting and Casting (scjp/ocjp)
PPTX
chp 3 : Modifiers (scjp/ocjp)
PPTX
Chap1 language fondamentale of java ( scjp /ocjp)
Chapter 12:Understanding Server-Side Technologies
Chapter 10:Understanding Java Related Platforms and Integration Technologies
Chapter 11:Understanding Client-Side Technologies
Chapter 9:Representing Object-Oriented Concepts with UML
Chapter8:Understanding Polymorphism
Chapter 7:Understanding Class Inheritance
Chapter 6:Working with Classes and Their Relationships
Chapter 5:Understanding Variable Scope and Class Construction
Chapter 4:Object-Oriented Basic Concepts
Chapter 2 : Programming with Java Statements
Chapter 1 :
chap 10 : Development (scjp/ocjp)
Chap 9 : I/O and Streams (scjp/ocjp)
chap 8 : The java.lang and java.util Packages (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)
chap 6 : Objects and classes (scjp/ocjp)
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
chap4 : Converting and Casting (scjp/ocjp)
chp 3 : Modifiers (scjp/ocjp)
Chap1 language fondamentale of java ( scjp /ocjp)

Recently uploaded (20)

PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Complications of Minimal Access Surgery at WLH
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
Pharma ospi slides which help in ospi learning
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Classroom Observation Tools for Teachers
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Lesson notes of climatology university.
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
Complications of Minimal Access Surgery at WLH
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Pharma ospi slides which help in ospi learning
2.FourierTransform-ShortQuestionswithAnswers.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
VCE English Exam - Section C Student Revision Booklet
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Classroom Observation Tools for Teachers
102 student loan defaulters named and shamed – Is someone you know on the list?
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Final Presentation General Medicine 03-08-2024.pptx
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Lesson notes of climatology university.

chap 2 : Operators and Assignments (scjp/ocjp)

  • 2. Evaluation Order 1. int [] a = { 4, 4 }; 2. int b = 1; 3. a[b] = b = 0; the value 0 is first assigned to the variable called b then the value 0 is assigned into the last element of the array a . . Ben Abdallah Helmi Architect J2EE
  • 3. Overview of the Java Operators Ben Abdallah Helmi Architect J2EE
  • 4. The Unary Operators The increment and decrement operators: ++ and -The unary plus and minus operators: + and - The bitwise inversion operator: ~ The boolean complement operator: ! The cast: () Ben Abdallah Helmi Architect J2EE
  • 5. The Increment and Decrement Operators: ++ and -- Ben Abdallah Helmi Architect J2EE
  • 6. The Unary Plus and Minus Operators: + and 1. x = -3; 2. y = +3; 3. z = -(y + 6); the value of z is initialized to −9. Ben Abdallah Helmi Architect J2EE
  • 7. The Bitwise Inversion Operator: ~ For example, applying this operator to a byte containing 00001111 would result in the value 11110000. The same simple logic applies, no matter how many bits there are in the value being operated on. This operator is often used in conjunction with shift operators (<<, >>, and >>>) to perform bit manipulation, for example, when driving I/O ports. Ben Abdallah Helmi Architect J2EE
  • 8. The Boolean Complement Operator: ! 1. Vector v = new Vector(); 2. v.add ("Hello"); 3. String s = (String)v.get(0); Ben Abdallah Helmi Architect J2EE
  • 9. The Arithmetic Operators Ben Abdallah Helmi Architect J2EE
  • 10. The Multiplication and Division Operators: * and / 1. int a = 12345, b = 234567, c, d; 2. long e, f; 3. 4. c = a * b / b; // this should equal a, that is, 12345 5. d = a / b * b; // this should also equal a 6. System.out.println("a is " + a + 7. "nb is " + b + 8. "nc is " + c + 9. "nd is " + d); 10. 11. e = (long)a * b / b; 12. f = (long)a / b * b; 13. System.out.println( 14. "ne is " + e + 15. "nf is " + f); The output from this code is a is 12345 b is 234567 c is -5965 d is 0 e is 12345 f is 0 Ben Abdallah Helmi Architect J2EE
  • 11. The Modulo Operator: % Ben Abdallah Helmi Architect J2EE
  • 12. The Addition and Subtraction Operators: + and - To prepare for the Certification Exam questions, and to use the + operator effectively in your own programs, you should understand the following points: • • • • For a + expression with two operands of primitive numeric type, the result o Is of a primitive numeric type. o Is at least int, because of normal promotions. o Is of a type at least as wide as the wider of the two operands. o Has a value calculated by promoting the operands to the result type and then performing the addition using that type. This might result in overflow or loss of precision. For a + expression with any operand that is not of primitive numeric type, o At least one operand must be a String object or literal; otherwise, the expression is illegal. o Any remaining non-String operands are converted to String, and the result of the expression is the concatenation of all operands. To convert an operand of some object type to a String, the conversion is performed by invoking the toString() method of that object. To convert an operand of a primitive type to a String, the conversion is performed by a static method in a container class, such as Integer.toString(). J2EE Ben Abdallah Helmi Architect
  • 13. Arithmetic Error Conditions In exceptional conditions, the following rules apply: • Integer division by zero, including modulo (%) operation, results in an ArithmeticException. • No other arithmetic causes any exception. Instead, the operation proceeds to a result, even though that result might be arithmetically incorrect. • Floating-point calculations represent out-of-range values using the IEEE 754 infinity, minus infinity, and Not a Number (NaN) values. Named constants representing these are declared in both the Float and Double classes. • Integer calculations, other than division by zero, that cause overflow or a similar error simply leave the final, typically truncated bit pattern in the result. This bit pattern is derived from the operation and the number representation and might even be of the wrong sign. Because the operations and number representations do not depend upon the platform, neither do the result values under error conditions. These rules describe the effect of error conditions, but some additional significance is associated with the NaN values. NaN values are used to indicate that a calculation has no result in ordinary arithmetic, such as some calculations Architect J2EE infinity or the square root of a Ben Abdallah Helmi involving negative number.
  • 14. Arithmetic Promotion of Operands The diagram in Figure 2.2 shows the process by which a byte is shifted right. First the byte is promoted to an int, which is done treating the byte as a signed quantity. Next, the shift occurs, and 0 bits are indeed propagated into the top bits of the result—but these bits are not part of the original byte. When the result is cast down to a byte again, the high-order bits of that byte appear to have been created by a signed shift right, rather than an unsigned one. This is why you should generally not use the logical right-shift operator with operands smaller than an int: It is unlikely to produce the result you expected. Ben Abdallah Helmi Architect J2EE
  • 15. The Ordinal Comparisons Operators: <, <=, >, and >= int p = 9; int q = 65; int r = -12; float f = 9.0F; char c = ‘A’; the following tests all return true: p<q f<q f <= c c>r c >= q Notice that arithmetic promotions are applied when these operators are used. This is entirely according to the normal rules discussed in Chapter 4. For example, although it would be an error to attempt to assign, say, the float value 9.0F to the char variable c, it is perfectly acceptable to compare the two. To achieve the result, Java promotes the smaller type to the larger type; hence the char value ‘A’ (represented by the Unicode value 65) is promoted to a float 65.0F. The comparison is then performed on the resulting float values. Ben Abdallah Helmi Architect J2EE
  • 16. The instanceof Operator The instanceof operator tests the class of an object at runtime. The left argument can be any object reference expression, usually a variable or an array element, whereas the right operand must be a class, interface, or array type. You cannot use a java.lang.Class object reference or a String representing the name of the class as the right operand. A compiler error results if the left operand cannot be cast to the right operand. If the left argument of the instanceof operator is a null value, the instanceof test simply returns false; it does not cause an exception. Ben Abdallah Helmi Architect J2EE
  • 17. The Equality Comparison Operators: == and != The operators == and != test for equality and inequality, respectively, returning a boolean value. For primitive types, the concept of equality is quite straightforward and is subject to promotion rules so that, for example, a float value of 10.0 is considered equal to a byte value of 10. For variables of object type, the “value” is taken as the reference to the object—typically, the memory address. You should not use these operators to compare the contents of objects, such as strings, because they will return true if two references refer to the same object, rather than if the two objects have equivalent value. Object comparisons compare the data of two objects, whereas reference comparisons compare the memory locations of two objects. To achieve a content or semantic comparison, for example, so that two different Double objects containing the value 1234 are considered equal, you must use the equals() method rather than the == or != operator. Ben Abdallah Helmi Architect J2EE
  • 18. The Bitwise Operators The bitwise operations calculate each bit of their results by comparing the corresponding bits of the two operands on the basis of these three rules: • For AND operations, 1 AND 1 produces 1. Any other combination produces 0. • For XOR operations, 1 XOR 0 produces 1, as does 0 XOR 1. (All these operations are commutative.) Any other combination produces 0. • For OR operations, 0 OR 0 produces 0. Any other combination produces 1. Ben Abdallah Helmi Architect J2EE
  • 19. Boolean Operations • For AND operations, true AND true produces true. Any other combination produces false. • For XOR operations, true XOR false produces true, and false XOR true produces true.Other combinations produce false. • For OR operations, false OR false produces false. Any other combination produces true. Ben Abdallah Helmi Architect J2EE
  • 20. The Short-Circuit Logical Operators The main difference between the & and && and between the | and || operators is that the right operand might not be evaluated in the latter cases. We will look at how this happens in the rest of this section. This behavior is based on two mathematical rules that define conditions under which the result of a boolean AND or OR operation is entirely determine by one operand without regard for the value of the other: • For an AND operation, if one operand is false, the result is false, without regard to the other operand. • For an OR operation, if one operand is true, the result is true, without regard to the other operand. To put it another way, for any boolean value X, • false AND X = false • true OR X = true 1. if (s != null) { 2. if (s.length() > 20) { 3. System.out.println(s); 4. } 5. } However, the same operation can be coded very succinctly like this: 1. if ((s != null) && (s.length() > 20)) { 2. System.out.println(s); Ben Abdallah Helmi Architect J2EE 3. }
  • 21. //first example: 1. int val = (int)(2 * Math.random()); 2. boolean test = (val == 0) || (++val == 2); 3. System.out.println("test = " + test + "nval = " + val); //second example: 1. int val = (int)(2 * Math.random()); 2. boolean test = (val == 0) | (++val == 2); 3. System.out.println("test = " + test + "nval = " + val); The first example will sometimes print test = true val = 0 and sometimes it will print test = true val = 2 The second example will sometimes print test = true val = 1 and sometimes it will print test = true val = 2 Ben Abdallah Helmi Architect J2EE
  • 22. The Conditional Operator The conditional operator—?:— (also known as a ternary operator, because it takes three operands) provides a way to code simple conditions (if/else) into a single expression. The (boolean) expression to the left of the ? is evaluated. If true, the result of the whole expression is the value of the expression to the left of the colon; otherwise, it is the value of the expression to the right of the colon. The expressions on either side of the colon must be assignment-compatible with the result type. For example, if a, b, and c are int variables, and x is a boolean, then the statement a = x ? b : c; is directly equivalent to the textually longer version: 1. if (x) { 2. a = b; 3. } 4. else { 5. a = c; 6. } Of course x, a, b, and c can all be complex expressions if you desire. Here are the points you should review for handling conditional operators in an exam question, or to use them properly in a program. In an expression of the form a = x ? b : c; • The types of the expressions b and c should be compatible and are made identical through conversion. • The type of the expression x should be boolean. • The types of the expressions b and c should be assignment-compatible with the type of a. • The value assigned to a will be b if x is true or will be c if x is false. Now that we have discussed the conditional (ternary) operator, only one group of operators remains: the assignment Ben Abdallah Helmi Architect J2EE operators.
  • 23. The Assignment Operators 1. byte x = 2; 2. x += 3; If this had been written using the longhand approach 1. byte x = 2; 2. x = (byte)(x + 3); The assignment operators in Java are considered to be operators because they have a resulting value. So, given three int variables a, b, and c, the statement a = b = c = 0; is entirely legal. It is executed from right to left, so that first 0 is assigned into the variable c. After it has been executed, the expression c = 0 takes the value that was assigned to the left side—that is, 0. Next, the assignment of b takes place, using the value of the expression to the right of the equal sign—again, 0. Similarly, that expression takes the value that was assigned, so finally the variable a is also Ben Abdallah Helmi Architect J2EE set to 0.