0% found this document useful (0 votes)
47 views

Computer Science Reference Operators

Operators with a higher precedence are executed before those of a lower precedence. Operators on the same line have the same precedence: operator precedence (), [], postfix ++, prefix -left Highest unary +, unary -, prefix --, instanceof ==,!=.

Uploaded by

Javier Solis
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Computer Science Reference Operators

Operators with a higher precedence are executed before those of a lower precedence. Operators on the same line have the same precedence: operator precedence (), [], postfix ++, prefix -left Highest unary +, unary -, prefix --, instanceof ==,!=.

Uploaded by

Javier Solis
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

3.

Operators
3. 1. Operators( 5 ) 3. 6. Relational Operators( 2 )
3. 2. Assignment Operators( 1 ) 3. 7. Logical Operators( 10 )
3. 3. Increment Decrement Operators( 5 ) 3. 8. Ternary Operator( 1 )
3. 4. Arithmetic Operators( 6 ) 3. 9. Comma Operator( 1 )
3. 5. Bitwise Operators( 23 ) 3. 10. instanceof( 4 )

3. 1. Operators
3. 1. 1. Six categories of operators

3. 1. 2. Operator Precedence

3. 1. 3. The op= Operators


The ternary operator (The Conditional Operator): result =
3. 1. 4.
value>conditionValue ? result1 : result2
Tests all the operators on all the primitive data types to show
3. 1. 5.
which ones are accepted by the Java compiler

3. 1. 1. Six categories of operators

In Java, there are six categories of operators.


1. Unary operators
2. Arithmetic operators
3. Relational and conditional operators
4. Shift and logical operators
5. Assignment operators
6. Other operators

Precedence Operator Description Association


1 ++,-- Postincrement, Postdecrement R -> L
2 ++,-- Preincrement, Predecrement R -> L
+,- Unary plus, unary minus R -> L
~ Bitwise compliment R -> L
! Boolean NOT R -> L
3 new Create object R -> L
(type) Type cast R -> L
4 *,/,% Multiplication, division, remainder L -> R
5 +,- Addition, subtraction L -> R
+ String concatenation L -> R
6 <<, >>, >>> Left shift, right shift, unsigned right shift L -> R
7 <, <=, >, >= L -> R
instanceof Type comparison L -> R
8 ==, != Value equality and inequality L -> R
==, != Reference equality and inequality L -> R
9 & Boolean AND L -> R
& Bitwise AND L -> R
10 ^ Boolean XOR L -> R
^ Bitwise XOR L -> R
11 | Boolean OR L -> R
| Bitwise OR L -> R
12 && Conditional AND L -> R
13 || Conditional OR L -> R
14 ?: Conditional Ternary Operator L -> R
15 =,+=,-=, Assignment Operators R -> L
*=,/ =,%=,
&=,^=, |=,
<<=, >> =,
>>>=

3. 1. 2. Operator Precedence

Operators with a higher precedence are executed before those of a lower precedence.
Operators on the same line have the same precedence:
Operator Precedence Group Associativity Operator Precedence
(), [], postfix ++, postfix -- left Highest
unary +, unary -, prefix ++, prefix --, ~, ! right
(type), new left
*, /, % left
+, - left
<<, >>, >>> left
< ,<= , >, >=, instanceof
==, !=
& left
^ left
| left
&& left
|| left
?: left
=, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, |=, ^= right lowest

3. 1. 3. The op= Operators


count += 5 has the same effect as the statement: count = count + 5;
public class MainClass {

public static void main(String[] arg) {


int count = 1;

count += 5;
System.out.println(count);

count = count + 5;
System.out.println(count);

6
11
The complete set of op= operators:
1. +=
2. -=
3. *=
4. /=
5. %=
6. <<=
7. >>=
8. >>>=
9. &=
10. |=
11. ^=

3. 1. 4. The ternary operator (The Conditional Operator):


result = value>conditionValue ? result1 : result2

if(value > conditionValue){


result = result1;
}else{
result = result2;
}

logical_expression ? expression1 : expression2

public class MainClass {


public static void main(String[] args) {
int v = 1;
System.out.println(v == 1 ? "A" : "B");
v++;
System.out.println(v == 1 ? "A" : "B");
}
}

A
B

3. 1. 5. Tests all the operators on all the primitive data types to show
ones are accepted by the Java compiler

public class MainClass {


public static void main(String[] a){
boolTest(true, false);
charTest('x', 'y');
byteTest((byte)0, (byte)1);
shortTest((short)0, (short)1);
intTest(1, 2);
longTest(11L, 22L);
floatTest(1.1F, 2.2F);
doubleTest(1.1, 2.2);
}

// To accept the results of a boolean test:


static void f(boolean b) {
System.out.println("f:"+b);
}
static void boolTest(boolean x, boolean y) {
// Arithmetic operators:
//! x = x * y;
//! x = x / y;
//! x = x % y;
//! x = x + y;
//! x = x - y;
//! x++;
//! x--;
//! x = +y;
//! x = -y;
// Relational and logical:
//! f(x > y);
//! f(x >= y);
//! f(x < y);
//! f(x <= y);
f(x == y);
f(x != y);
f(!y);
x = x && y;
x = x || y;
// Bitwise operators:
//! x = ~y;
x = x & y;
x = x | y;
x = x ^ y;
//! x = x << 1;
//! x = x >> 1;
//! x = x >>> 1;
// Compound assignment:
//! x += y;
//! x -= y;
//! x *= y;
//! x /= y;
//! x %= y;
//! x <<= 1;
//! x >>= 1;
//! x >>>= 1;
x &= y;
x ^= y;
x |= y;
// Casting:
//! char c = (char)x;
//! byte B = (byte)x;
//! short s = (short)x;
//! int i = (int)x;
//! long l = (long)x;
//! float f = (float)x;
//! double d = (double)x;
}
static void charTest(char x, char y) {
// Arithmetic operators:
x = (char)(x * y);
x = (char)(x / y);
x = (char)(x % y);
x = (char)(x + y);
x = (char)(x - y);
x++;
x--;
x = (char)+y;
x = (char)-y;
// Relational and logical:
f(x > y);
f(x >= y);
f(x < y);
f(x <= y);
f(x == y);
f(x != y);
//! f(!x);
//! f(x && y);
//! f(x || y);
// Bitwise operators:
x= (char)~y;
x = (char)(x & y);
x = (char)(x | y);
x = (char)(x ^ y);
x = (char)(x << 1);
x = (char)(x >> 1);
x = (char)(x >>> 1);
// Compound assignment:
x += y;
x -= y;
x *= y;
x /= y;
x %= y;
x <<= 1;
x >>= 1;
x >>>= 1;
x &= y;
x ^= y;
x |= y;
// Casting:
//! boolean b = (boolean)x;
byte B = (byte)x;
short s = (short)x;
int i = (int)x;
long l = (long)x;
float f = (float)x;
double d = (double)x;
}
static void byteTest(byte x, byte y) {
// Arithmetic operators:
x = (byte)(x* y);
x = (byte)(x / y);
x = (byte)(x % y);
x = (byte)(x + y);
x = (byte)(x - y);
x++;
x--;
x = (byte)+ y;
x = (byte)- y;
// Relational and logical:
f(x > y);
f(x >= y);
f(x < y);
f(x <= y);
f(x == y);
f(x != y);
//! f(!x);
//! f(x && y);
//! f(x || y);
// Bitwise operators:
x = (byte)~y;
x = (byte)(x & y);
x = (byte)(x | y);
x = (byte)(x ^ y);
x = (byte)(x << 1);
x = (byte)(x >> 1);
x = (byte)(x >>> 1);
// Compound assignment:
x += y;
x -= y;
x *= y;
x /= y;
x %= y;
x <<= 1;
x >>= 1;
x >>>= 1;
x &= y;
x ^= y;
x |= y;
// Casting:
//! boolean b = (boolean)x;
char c = (char)x;
short s = (short)x;
int i = (int)x;
long l = (long)x;
float f = (float)x;
double d = (double)x;
}
static void shortTest(short x, short y) {
// Arithmetic operators:
x = (short)(x * y);
x = (short)(x / y);
x = (short)(x % y);
x = (short)(x + y);
x = (short)(x - y);
x++;
x--;
x = (short)+y;
x = (short)-y;
// Relational and logical:
f(x > y);
f(x >= y);
f(x < y);
f(x <= y);
f(x == y);
f(x != y);
//! f(!x);
//! f(x && y);
//! f(x || y);
// Bitwise operators:
x = (short)~y;
x = (short)(x & y);
x = (short)(x | y);
x = (short)(x ^ y);
x = (short)(x << 1);
x = (short)(x >> 1);
x = (short)(x >>> 1);
// Compound assignment:
x += y;
x -= y;
x *= y;
x /= y;
x %= y;
x <<= 1;
x >>= 1;
x >>>= 1;
x &= y;
x ^= y;
x |= y;
// Casting:
//! boolean b = (boolean)x;
char c = (char)x;
byte B = (byte)x;
int i = (int)x;
long l = (long)x;
float f = (float)x;
double d = (double)x;
}
static void intTest(int x, int y) {
// Arithmetic operators:
x = x * y;
x = x / y;
x = x % y;
x = x + y;
x = x - y;
x++;
x--;
x = +y;
x = -y;
// Relational and logical:
f(x > y);
f(x >= y);
f(x < y);
f(x <= y);
f(x == y);
f(x != y);
//! f(!x);
//! f(x && y);
//! f(x || y);
// Bitwise operators:
x = ~y;
x = x & y;
x = x | y;
x = x ^ y;
x = x << 1;
x = x >> 1;
x = x >>> 1;
// Compound assignment:
x += y;
x -= y;
x *= y;
x /= y;
x %= y;
x <<= 1;
x >>= 1;
x >>>= 1;
x &= y;
x ^= y;
x |= y;
// Casting:
//! boolean b = (boolean)x;
char c = (char)x;
byte B = (byte)x;
short s = (short)x;
long l = (long)x;
float f = (float)x;
double d = (double)x;
}
static void longTest(long x, long y) {
// Arithmetic operators:
x = x * y;
x = x / y;
x = x % y;
x = x + y;
x = x - y;
x++;
x--;
x = +y;
x = -y;
// Relational and logical:
f(x > y);
f(x >= y);
f(x < y);
f(x <= y);
f(x == y);
f(x != y);
//! f(!x);
//! f(x && y);
//! f(x || y);
// Bitwise operators:
x = ~y;
x = x & y;
x = x | y;
x = x ^ y;
x = x << 1;
x = x >> 1;
x = x >>> 1;
// Compound assignment:
x += y;
x -= y;
x *= y;
x /= y;
x %= y;
x <<= 1;
x >>= 1;
x >>>= 1;
x &= y;
x ^= y;
x |= y;
// Casting:
//! boolean b = (boolean)x;
char c = (char)x;
byte B = (byte)x;
short s = (short)x;
int i = (int)x;
float f = (float)x;
double d = (double)x;
}
static void floatTest(float x, float y) {
// Arithmetic operators:
x = x * y;
x = x / y;
x = x % y;
x = x + y;
x = x - y;
x++;
x--;
x = +y;
x = -y;
// Relational and logical:
f(x > y);
f(x >= y);
f(x < y);
f(x <= y);
f(x == y);
f(x != y);
//! f(!x);
//! f(x && y);
//! f(x || y);
// Bitwise operators:
//! x = ~y;
//! x = x & y;
//! x = x | y;
//! x = x ^ y;
//! x = x << 1;
//! x = x >> 1;
//! x = x >>> 1;
// Compound assignment:
x += y;
x -= y;
x *= y;
x /= y;
x %= y;
//! x <<= 1;
//! x >>= 1;
//! x >>>= 1;
//! x &= y;
//! x ^= y;
//! x |= y;
// Casting:
//! boolean b = (boolean)x;
char c = (char)x;
byte B = (byte)x;
short s = (short)x;
int i = (int)x;
long l = (long)x;
double d = (double)x;
}
static void doubleTest(double x, double y) {
// Arithmetic operators:
x = x * y;
x = x / y;
x = x % y;
x = x + y;
x = x - y;
x++;
x--;
x = +y;
x = -y;
// Relational and logical:
f(x > y);
f(x >= y);
f(x < y);
f(x <= y);
f(x == y);
f(x != y);
//! f(!x);
//! f(x && y);
//! f(x || y);
// Bitwise operators:
//! x = ~y;
//! x = x & y;
//! x = x | y;
//! x = x ^ y;
//! x = x << 1;
//! x = x >> 1;
//! x = x >>> 1;
// Compound assignment:
x += y;
x -= y;
x *= y;
x /= y;
x %= y;
//! x <<= 1;
//! x >>= 1;
//! x >>>= 1;
//! x &= y;
//! x ^= y;
//! x |= y;
// Casting:
//! boolean b = (boolean)x;
char c = (char)x;
byte B = (byte)x;
short s = (short)x;
int i = (int)x;
long l = (long)x;
float f = (float)x;
}
}

3. 2. Assignment Operators
3. 2. 1. Several assignment operators

3. 2. 1. Several assignment operators

public class MainClass {


public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;

a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}

a = 6
b = 8
c = 3

3. 3. Increment Decrement Operators


3. 3. 1. Increment and Decrement: Demonstrate ++.

3. 3. 2. The increment and decrement operators

3. 3. 3. Using the increment and decrement operators in an expression

3. 3. 4. The prefix form and the postfix form

3. 3. 5. Using ++ and -- with floating-point variables

3. 3. 1. Increment and Decrement: Demonstrate ++.

public class MainClass {


public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}

a = 2
b = 3
c = 4
d = 1

3. 3. 2. The increment and decrement operators

1. add an integer variable by one.


2. increment operator: two successive plus signs, ++.
3. decrement operator: --.

public class MainClass {

public static void main(String[] argv) {


int count = 10;
++count; // Add 1 to count
--count; // Subtract 1 from count

System.out.println(count);
}

10

3. 3. 3. Using the increment and decrement operators in an express

public class MainClass {


public static void main(String[] args) {
int numA = 5;
int numB = 10;
int numC = 0;

numC = ++numA + numB;

System.out.println(numA);
System.out.println(numC);
}
}

6
16

3. 3. 4. The prefix form and the postfix form


public class MainClass {
public static void main(String[] args) {
int numA = 5;
int numB = 10;
int numC = 0;

numC = ++numA + numB;

System.out.println(numA);
System.out.println(numC);
}
}

6
16
public class MainClass {
public static void main(String[] args) {
int numA = 5;
int numB = 10;
int numC = 0;

numC = --numA + numB--;


System.out.println(numA);
System.out.println(numC);
}
}

4
14

3. 3. 5. Using ++ and -- with floating-point variables

public class MainClass{

public static void main(String[] arg){


double a = 12.12;

System.out.println( a-- );
System.out.println( a++ );
System.out.println( --a );
System.out.println( ++a );
}

12.12
11.12
11.12
12.12

3. 4. Arithmetic Operators
3. 4. 1. Arithmetic Calculations

3. 4. 2. Arithmetic Operators

3. 4. 3. The Basic Arithmetic Operators

3. 4. 4. Demonstrates the mathematical operators

3. 4. 5. Modulus operator %: obtain the remainder after a division

3. 4. 6. Applying the modulus operator, %, to floating-point values

3. 4. 1. Arithmetic Calculations

An assignment statement has three elements:


1. the variable to store the result,
2. the assignment operator: =,
3. an arithmetic expression

The statement is terminated by a semicolon.


public class MainClass{
public static void main(String[] argv){
int a = 1;
int b = 2;
int c = 0;

c = a + b;

System.out.println(c);
}

3. 4. 2. Arithmetic Operators

Operator Result
+ Addition
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
-- Decrement

3. 4. 3. The Basic Arithmetic Operators

public class MainClass {


public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);

// arithmetic using doubles


System.out.println("\nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}

Integer Arithmetic
a = 2
b = 6
c = 1
d = -1
e = 1

Floating Point Arithmetic


da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5

3. 4. 4. Demonstrates the mathematical operators

import java.util.Random;

public class MainClass {


static void printInt(String s, int i) {
System.out.println(s + " = " + i);
}

static void printFloat(String s, float f) {


System.out.println(s + " = " + f);
}

public static void main(String[] args) {


Random rand = new Random();
int i, j, k;
j = rand.nextInt(100) + 1;
k = rand.nextInt(100) + 1;
printInt("j", j);
printInt("k", k);
i = j + k;
printInt("j + k", i);
i = j - k;
printInt("j - k", i);
i = k / j;
printInt("k / j", i);
i = k * j;
printInt("k * j", i);
i = k % j;
printInt("k % j", i);
j %= k;
printInt("j %= k", j);
// Floating-point number tests:
float u, v, w; // applies to doubles, too
v = rand.nextFloat();
w = rand.nextFloat();
printFloat("v", v);
printFloat("w", w);
u = v + w;
printFloat("v + w", u);
u = v - w;
printFloat("v - w", u);
u = v * w;
printFloat("v * w", u);
u = v / w;
printFloat("v / w", u);
// the following also works for
// char, byte, short, int, long,
// and double:
u += v;
printFloat("u += v", u);
u -= v;
printFloat("u -= v", u);
u *= v;
printFloat("u *= v", u);
u /= v;
printFloat("u /= v", u);
}
}

j = 31
k = 84
j + k = 115
j - k = -53
k / j = 2
k * j = 2604
k % j = 22
j %= k = 31
v = 0.79780066
w = 0.9309381
v + w = 1.7287388
v - w = -0.13313746
v * w = 0.7427031
v / w = 0.8569857
u += v = 1.6547863
u -= v = 0.8569857
u *= v = 0.6837037
u /= v = 0.8569856

3. 4. 5. Modulus operator %: obtain the remainder after a division

public class MainClass {

public static void main(String[] argv) {


int a = 3 % 2;
int b = 11 % 3;
int c = 7 % -3;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}

1
2
1

3. 4. 6. Applying the modulus operator, %, to floating-point values

public class MainClass{

public static void main(String[] arg){


double a = 2.4;
double b = 0.2;

System.out.println( a % b );
}

0.1999999999999998

3. 5. Bitwise Operators

The Bitwise Operators can be applied to the integer types, long, int,
3. 5. 1.
short, char, and byte.

3. 5. 2. The Bitwise Logical Operators

3. 5. 3. Bitwise AND (&)

3. 5. 4. Bitwise OR (|)

3. 5. 5. Bitwise XOR (^)

3. 5. 6. Left shift (<<)

3. 5. 7. Bitwise complement (~): inverts ones and zeros in a number


3. 5. 8. Demonstrate the bitwise logical operators

3. 5. 9. All bitwise operators in action

3. 5. 10. Bitwise Operator Assignments

3. 5. 11. The Left Shift

3. 5. 12. Left shifting as a quick way to multiply by 2

3. 5. 13. The Right Shift

3. 5. 14. The Unsigned Right Shift

3. 5. 15. Signed shift to the right

3. 5. 16. Unsigned shifting a byte value.

3. 5. 17. Convert a number to negative and back

3. 5. 18. Performing Bitwise Operations on a Bit Vector

3. 5. 19. Converting Between a BitSet and a Byte Array

3. 5. 20. Returns a byte array of at least length 1

3. 5. 21. Use bitwise operator to create hash code

3. 5. 22. Operations on bit-mapped fields.

3. 5. 23. Represents a collection of 64 boolean (on/off) flags.

3. 5. 1. The Bitwise Operators can be applied to the integer types, lo


int, short, char, and byte.

Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>> Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment

3. 5. 2. The Bitwise Logical Operators

A B A | B A & B A ^ B ~A

0 0 0 0 0 1

1 0 1 0 1 0

0 1 1 0 1 1

1 1 1 1 0 0

The Bitwise NOT

00101010 42

becomes

11010101

The Bitwise AND

00101010 42
& 00001111 15
__________
00001010 10

The Bitwise OR

00101010 42
| 00001111 15
_________
00101111 47

The Bitwise XOR


00101010 42
^ 00001111 15
_________
00100101 37

3. 5. 3. Bitwise AND (&)

public class Main {


public static void main(String[] a) {
System.out.println(9 & 7);
}
}
//1

3. 5. 4. Bitwise OR (|)

public class Main {


public static void main(String[] a) {

System.out.println(19 | 7);
}
}
//23

3. 5. 5. Bitwise XOR (^)

public class Main {


public static void main(String[] a) {

System.out.println(9 ^ 7);
}
}
//14

3 . 5. 6. Left shift (<<)

public class Main {


public static void main(String[] a) {

System.out.println(9 << 7);


}
}
//1152

3. 5. 7. Bitwise complement (~): inverts ones and zeros in a number


public class Main {
public static void main(String[] a) {
int i = 1;
System.out.println(i);

int j = ~i + 1;
System.out.println(j);

i = ~j + 1;
System.out.println(i);
}
}
/*
1
-1
1
*/

3. 5. 8. Demonstrate the bitwise logical operators

public class MainClass {


public static void main(String args[]) {
String binary[] = {
"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
};
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;

System.out.println(" a = " + binary[a]);


System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}

a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100
3. 5. 9. All bitwise operators in action

// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002


// www.BruceEckel.com. See copyright notice in CopyRight.txt.

import java.util.Random;

public class MainClass {


public static void main(String[] args) {
Random rand = new Random();
int i = rand.nextInt();
int j = rand.nextInt();
printBinaryInt("-1", -1);
printBinaryInt("+1", +1);
int maxpos = 2147483647;
printBinaryInt("maxpos", maxpos);
int maxneg = -2147483648;
printBinaryInt("maxneg", maxneg);
printBinaryInt("i", i);
printBinaryInt("~i", ~i);
printBinaryInt("-i", -i);
printBinaryInt("j", j);
printBinaryInt("i & j", i & j);
printBinaryInt("i | j", i | j);
printBinaryInt("i ^ j", i ^ j);
printBinaryInt("i << 5", i << 5);
printBinaryInt("i >> 5", i >> 5);
printBinaryInt("(~i) >> 5", (~i) >> 5);
printBinaryInt("i >>> 5", i >>> 5);
printBinaryInt("(~i) >>> 5", (~i) >>> 5);

long l = rand.nextLong();
long m = rand.nextLong();
printBinaryLong("-1L", -1L);
printBinaryLong("+1L", +1L);
long ll = 9223372036854775807L;
printBinaryLong("maxpos", ll);
long lln = -9223372036854775808L;
printBinaryLong("maxneg", lln);
printBinaryLong("l", l);
printBinaryLong("~l", ~l);
printBinaryLong("-l", -l);
printBinaryLong("m", m);
printBinaryLong("l & m", l & m);
printBinaryLong("l | m", l | m);
printBinaryLong("l ^ m", l ^ m);
printBinaryLong("l << 5", l << 5);
printBinaryLong("l >> 5", l >> 5);
printBinaryLong("(~l) >> 5", (~l) >> 5);
printBinaryLong("l >>> 5", l >>> 5);
printBinaryLong("(~l) >>> 5", (~l) >>> 5);
}
static void printBinaryInt(String s, int i) {
System.out.println(s + ", int: " + i + ", binary: ");
System.out.print(" ");
for (int j = 31; j >= 0; j--)
if (((1 << j) & i) != 0)
System.out.print("1");
else
System.out.print("0");
System.out.println();
}

static void printBinaryLong(String s, long l) {


System.out.println(s + ", long: " + l + ", binary: ");
System.out.print(" ");
for (int i = 63; i >= 0; i--)
if (((1L << i) & l) != 0)
System.out.print("1");
else
System.out.print("0");
System.out.println();
}
}

-1, int: -1, binary:


11111111111111111111111111111111
+1, int: 1, binary:
00000000000000000000000000000001
maxpos, int: 2147483647, binary:
01111111111111111111111111111111
maxneg, int: -2147483648, binary:
10000000000000000000000000000000
i, int: 907739811, binary:
00110110000110110000001010100011
~i, int: -907739812, binary:
11001001111001001111110101011100
-i, int: -907739811, binary:
11001001111001001111110101011101
j, int: -1527787021, binary:
10100100111011111101000111110011
i & j, int: 604700835, binary:
00100100000010110000000010100011
i | j, int: -1224748045, binary:
10110110111111111101001111110011
i ^ j, int: -1829448880, binary:
10010010111101001101001101010000
i << 5, int: -1017097120, binary:
11000011011000000101010001100000
i >> 5, int: 28366869, binary:
00000001101100001101100000010101
(~i) >> 5, int: -28366870, binary:
11111110010011110010011111101010
i >>> 5, int: 28366869, binary:
00000001101100001101100000010101
(~i) >>> 5, int: 105850858, binary:
00000110010011110010011111101010
-1L, long: -1, binary:
1111111111111111111111111111111111111111111111111111111111111111
+1L, long: 1, binary:
0000000000000000000000000000000000000000000000000000000000000001
maxpos, long: 9223372036854775807, binary:
0111111111111111111111111111111111111111111111111111111111111111
maxneg, long: -9223372036854775808, binary:
1000000000000000000000000000000000000000000000000000000000000000
l, long: 6929873296403828491, binary:
0110000000101011110110110000110000001010100111011000111100001011
~l, long: -6929873296403828492, binary:
1001111111010100001001001111001111110101011000100111000011110100
-l, long: -6929873296403828491, binary:
1001111111010100001001001111001111110101011000100111000011110101
m, long: -352541115944271612, binary:
1111101100011011100001011011100100001111011011000000000100000100
l & m, long: 6920767123913179392, binary:
0110000000001011100000010000100000001010000011000000000100000000
l | m, long: -343434943453622513, binary:
1111101100111011110111111011110100001111111111011000111100001111
l ^ m, long: -7264202067366801905, binary:
1001101100110000010111101011010100000101111100011000111000001111
l << 5, long: 395016600407892320, binary:
0000010101111011011000011000000101010011101100011110000101100000
l >> 5, long: 216558540512619640, binary:
0000001100000001010111101101100001100000010101001110110001111000
(~l) >> 5, long: -216558540512619641, binary:
1111110011111110101000010010011110011111101010110001001110000111
l >>> 5, long: 216558540512619640, binary:
0000001100000001010111101101100001100000010101001110110001111000
(~l) >>> 5, long: 359902211790803847, binary:
0000010011111110101000010010011110011111101010110001001110000111

3. 5. 10. Bitwise Operator Assignments

public class MainClass {


public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;

a |= 4;
b >>= 1;
c <<= 1;
a ^= c;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}

a = 3
b = 1
c = 6

3. 5. 11. The Left Shift

// Left shifting a byte value.


public class MainClass {
public static void main(String args[]) {
byte a = 64, b;
int i;

i = a << 2;
b = (byte) (a << 2);

System.out.println("Original value of a: " + a);


System.out.println("i and b: " + i + " " + b);
}
}

Original value of a: 64
i and b: 256 0

3. 5. 12. Left shifting as a quick way to multiply by 2

public class MainClass {


public static void main(String args[]) {
int i;
int num = 0xFFFFFFE;
for(i=0; i<4; i++) {
num = num << 1;
System.out.println(num);
}
}
}

536870908
1073741816
2147483632
-32

3. 5. 13. The Right Shift

public class MainClass {


public static void main(String args[]) {

int a = 32;
a = a >> 2; // a now contains 8

System.out.println(a);

}
}

3. 5. 14. The Unsigned Right Shift

public class MainClass {


public static void main(String args[]) {

int a = -1;
a = a >>> 24;

System.out.println(a);

}
}

255

3. 5. 15. Signed shift to the right


public class Main {
public static void main(String[] argv) throws Exception {
byte b = 11;

System.out.println(b >> 1);


}
}

3. 5. 16. Unsigned shifting a byte value.

public class MainClass {


static public void main(String args[]) {
char hex[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
byte b = (byte) 0xf1;
byte c = (byte) (b >> 4);
byte d = (byte) (b >>> 4);
byte e = (byte) ((b & 0xff) >> 4);
System.out.println(" b = 0x"
+ hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
System.out.println(" b >> 4 = 0x"
+ hex[(c >> 4) & 0x0f] + hex[c & 0x0f]);
System.out.println(" b >>> 4 = 0x"
+ hex[(d >> 4) & 0x0f] + hex[d & 0x0f]);
System.out.println("(b & 0xff) >> 4 = 0x"
+ hex[(e >> 4) & 0x0f] + hex[e & 0x0f]);
}
}

b = 0xf1
b >> 4 = 0xff
b >>> 4 = 0xff
(b & 0xff) >> 4 = 0x0f

3. 5. 17. Convert a number to negative and back

public class Main {


public static void main(String[] a) {
int i = 1;

System.out.println(i);
int j = ~i + 1;
System.out.println(j);

i = ~j + 1;
System.out.println(i);
}
}
/*
1
-1
1
*/

3. 5. 18. Performing Bitwise Operations on a Bit Vector

import java.util.BitSet;

public class Main {


public static void main(String[] argv) throws Exception {
// Create the bitset
BitSet bits = new BitSet();

// Set a bit on
bits.set(2);

// Retrieving the value of a bit


boolean b = bits.get(0);
b = bits.get(2);

// Clear a bit
bits.clear(1);

// Setting a range of bits


BitSet bits2 = new BitSet();
bits2.set(1, 4);

// And'ing two bitsets


bits.and(bits2);

// Xor'ing two bitsets


bits.xor(bits2);

// Flip all bits in the bitset


bits.flip(0, bits.length());

// Andnot'ing two bitsets


bits.andNot(bits2);

// Or'ing two bitsets


bits.or(bits2);
}
}

3. 5. 19. Converting Between a BitSet and a Byte Array


import java.util.BitSet;

public class Main {


public static void main(String[] argv) throws Exception {
System.out.println(fromByteArray(new byte[]{1,2,3}));
}

// Returns a bitset containing the values in bytes.


public static BitSet fromByteArray(byte[] bytes) {
BitSet bits = new BitSet();
for (int i = 0; i < bytes.length * 8; i++) {
if ((bytes[bytes.length - i / 8 - 1] & (1 << (i % 8))) > 0) {
bits.set(i);
}
}
return bits;
}
}
//{0, 1, 9, 16}

3. 5. 20. Returns a byte array of at least length 1

import java.util.BitSet;

public class Main {


public static void main(String[] argv) throws Exception {
BitSet bitset = new BitSet();
bitset.set(1);
System.out.println(toByteArray(bitset));
}

public static byte[] toByteArray(BitSet bits) {


byte[] bytes = new byte[bits.length() / 8 + 1];
for (int i = 0; i < bits.length(); i++) {
if (bits.get(i)) {
bytes[bytes.length - i / 8 - 1] |= 1 << (i % 8);
}
}
return bytes;
}
}

3. 5. 21. Use bitwise operator to create hash code

public class Main {


int instanceField;
{
int hc = hashCode();
instanceField = hc;
for (int i = 0; i < 32; i++) {
System.out.print((hc & 0x80000000) != 0 ? '1' : '0');
hc <<= 1;
}
}

public static void main(String[] args) {


System.out.println(new Main().instanceField);
System.out.println(new Main().instanceField);
}
}

3. 5. 22. Operations on bit-mapped fields.

/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* Operations on bit-mapped fields.
*
* @author Apache Jakarta POI
* @author Scott Sanders (sanders at apache dot org)
* @author Marc Johnson (mjohnson at apache dot org)
* @author Andrew C. Oliver (acoliver at apache dot org)
* @author Stephen Colebourne
* @author Pete Gieser
* @author Gary Gregory
* @since 2.0
* @version $Id: BitField.java 437554 2006-08-28 06:21:41Z bayard $
*/
public class BitField {

private final int _mask;


private final int _shift_count;

/**
* Creates a BitField instance.
*
* @param mask the mask specifying which bits apply to this
* BitField. Bits that are set in this mask are the bits
* that this BitField operates on
*/
public BitField(int mask) {
_mask = mask;
int count = 0;
int bit_pattern = mask;

if (bit_pattern != 0) {
while ((bit_pattern & 1) == 0) {
count++;
bit_pattern >>= 1;
}
}
_shift_count = count;
}

/**
* Obtains the value for the specified BitField, appropriately
* shifted right.
*
* Many users of a BitField will want to treat the specified
* bits as an int value, and will not want to be aware that the
* value is stored as a BitField (and so shifted left so many
* bits).
*
* @see #setValue(int,int)
* @param holder the int data containing the bits we're interested
* in
* @return the selected bits, shifted right appropriately
*/
public int getValue(int holder) {
return getRawValue(holder) >> _shift_count;
}

/**
* Obtains the value for the specified BitField, appropriately
* shifted right, as a short.
*
* Many users of a BitField will want to treat the specified
* bits as an int value, and will not want to be aware that the
* value is stored as a BitField (and so shifted left so many
* bits).
*
* @see #setShortValue(short,short)
* @param holder the short data containing the bits we're
* interested in
* @return the selected bits, shifted right appropriately
*/
public short getShortValue(short holder) {
return (short) getValue(holder);
}

/**
* Obtains the value for the specified BitField, unshifted.
*
* @param holder the int data containing the bits we're
* interested in
* @return the selected bits
*/
public int getRawValue(int holder) {
return holder & _mask;
}

/**
* Obtains the value for the specified BitField, unshifted.
*
* @param holder the short data containing the bits we're
* interested in
* @return the selected bits
*/
public short getShortRawValue(short holder) {
return (short) getRawValue(holder);
}

/**
* Returns whether the field is set or not.
*
* This is most commonly used for a single-bit field, which is
* often used to represent a boolean value; the results of using
* it for a multi-bit field is to determine whether *any* of its
* bits are set.
*
* @param holder the int data containing the bits we're interested
* in
* @return <code>true</code> if any of the bits are set,
* else <code>false</code>
*/
public boolean isSet(int holder) {
return (holder & _mask) != 0;
}

/**
* Returns whether all of the bits are set or not.
*
* This is a stricter test than {@link #isSet(int)},
* in that all of the bits in a multi-bit set must be set
* for this method to return <code>true</code>.
*
* @param holder the int data containing the bits we're
* interested in
* @return <code>true</code> if all of the bits are set,
* else <code>false</code>
*/
public boolean isAllSet(int holder) {
return (holder & _mask) == _mask;
}

/**
* Replaces the bits with new values.
*
* @see #getValue(int)
* @param holder the int data containing the bits we're
* interested in
* @param value the new value for the specified bits
* @return the value of holder with the bits from the value
* parameter replacing the old bits
*/
public int setValue(int holder, int value) {
return (holder & ~_mask) | ((value << _shift_count) & _mask);
}

/**
* Replaces the bits with new values.
*
* @see #getShortValue(short)
* @param holder the short data containing the bits we're
* interested in
* @param value the new value for the specified bits
* @return the value of holder with the bits from the value
* parameter replacing the old bits
*/
public short setShortValue(short holder, short value) {
return (short) setValue(holder, value);
}

/**
* Clears the bits.
*
* @param holder the int data containing the bits we're
* interested in
* @return the value of holder with the specified bits cleared
* (set to <code>0</code>)
*/
public int clear(int holder) {
return holder & ~_mask;
}

/**
* Clears the bits.
*
* @param holder the short data containing the bits we're
* interested in
* @return the value of holder with the specified bits cleared
* (set to <code>0</code>)
*/
public short clearShort(short holder) {
return (short) clear(holder);
}

/**
* Clears the bits.
*
* @param holder the byte data containing the bits we're
* interested in
*
* @return the value of holder with the specified bits cleared
* (set to <code>0</code>)
*/
public byte clearByte(byte holder) {
return (byte) clear(holder);
}

/**
* Sets the bits.
*
* @param holder the int data containing the bits we're
* interested in
* @return the value of holder with the specified bits set
* to <code>1</code>
*/
public int set(int holder) {
return holder | _mask;
}

/**
* Sets the bits.
*
* @param holder the short data containing the bits we're
* interested in
* @return the value of holder with the specified bits set
* to <code>1</code>
*/
public short setShort(short holder) {
return (short) set(holder);
}

/**
* Sets the bits.
*
* @param holder the byte data containing the bits we're
* interested in
*
* @return the value of holder with the specified bits set
* to <code>1</code>
*/
public byte setByte(byte holder) {
return (byte) set(holder);
}

/**
* Sets a boolean BitField.
*
* @param holder the int data containing the bits we're
* interested in
* @param flag indicating whether to set or clear the bits
* @return the value of holder with the specified bits set or
* cleared
*/
public int setBoolean(int holder, boolean flag) {
return flag ? set(holder) : clear(holder);
}

/**
* Sets a boolean BitField.
*
* @param holder the short data containing the bits we're
* interested in
* @param flag indicating whether to set or clear the bits
* @return the value of holder with the specified bits set or
* cleared
*/
public short setShortBoolean(short holder, boolean flag) {
return flag ? setShort(holder) : clearShort(holder);
}

/**
* Sets a boolean BitField.
*
* @param holder the byte data containing the bits we're
* interested in
* @param flag indicating whether to set or clear the bits
* @return the value of holder with the specified bits set or
* cleared
*/
public byte setByteBoolean(byte holder, boolean flag) {
return flag ? setByte(holder) : clearByte(holder);
}

3. 5. 23. Represents a collection of 64 boolean (on/off) flags.

/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.Serializable;

/**
* Represents a collection of 64 boolean (on/off) flags. Individual flags
* are represented by powers of 2. For example,<br/>
* Flag 1 = 1<br/>
* Flag 2 = 2<br/>
* Flag 3 = 4<br/>
* Flag 4 = 8<br/><br/>
* or using shift operator to make numbering easier:<br/>
* Flag 1 = 1 &lt;&lt; 0<br/>
* Flag 2 = 1 &lt;&lt; 1<br/>
* Flag 3 = 1 &lt;&lt; 2<br/>
* Flag 4 = 1 &lt;&lt; 3<br/>
*
*
* There cannot be a flag with a value of 3 because that represents Flag 1
* and Flag 2 both being on/true.
*
*
* @version $Revision: 478334 $ $Date: 2006-11-
22 21:31:54 +0000 (Wed, 22 Nov 2006) $
*/
public class Flags implements Serializable {

/**
* Represents the current flag state.
*/
private long flags = 0;

/**
* Create a new Flags object.
*/
public Flags() {
super();
}

/**
* Initialize a new Flags object with the given flags.
*
* @param flags collection of boolean flags to represent.
*/
public Flags(long flags) {
super();
this.flags = flags;
}

/**
* Returns the current flags.
*
* @return collection of boolean flags represented.
*/
public long getFlags() {
return this.flags;
}

/**
* Tests whether the given flag is on. If the flag is not a power of 2
* (ie. 3) this tests whether the combination of flags is on.
*
* @param flag Flag value to check.
*
* @return whether the specified flag value is on.
*/
public boolean isOn(long flag) {
return (this.flags & flag) > 0;
}

/**
* Tests whether the given flag is off. If the flag is not a power of 2
* (ie. 3) this tests whether the combination of flags is off.
*
* @param flag Flag value to check.
*
* @return whether the specified flag value is off.
*/
public boolean isOff(long flag) {
return (this.flags & flag) == 0;
}

/**
* Turns on the given flag. If the flag is not a power of 2 (ie. 3) this
* turns on multiple flags.
*
* @param flag Flag value to turn on.
*/
public void turnOn(long flag) {
this.flags |= flag;
}

/**
* Turns off the given flag. If the flag is not a power of 2 (ie. 3) this
* turns off multiple flags.
*
* @param flag Flag value to turn off.
*/
public void turnOff(long flag) {
this.flags &= ~flag;
}

/**
* Turn off all flags.
*/
public void turnOffAll() {
this.flags = 0;
}

/**
* Turn off all flags. This is a synonym for <code>turnOffAll()</code>.
* @since Validator 1.1.1
*/
public void clear() {
this.flags = 0;
}

/**
* Turn on all 64 flags.
*/
public void turnOnAll() {
this.flags = Long.MAX_VALUE;
}
/**
* Clone this Flags object.
*
* @return a copy of this object.
* @see java.lang.Object#clone()
*/
public Object clone() {
try {
return super.clone();
} catch(CloneNotSupportedException e) {
throw new RuntimeException("Couldn't clone Flags object.");
}
}

/**
* Tests if two Flags objects are in the same state.
* @param obj object being tested
* @see java.lang.Object#equals(java.lang.Object)
*
* @return whether the objects are equal.
*/
public boolean equals(Object obj) {
if (!(obj instanceof Flags)) {
return false;
}

if (obj == this) {
return true;
}

Flags f = (Flags) obj;

return this.flags == f.flags;


}

/**
* The hash code is based on the current state of the flags.
* @see java.lang.Object#hashCode()
*
* @return the hash code for this object.
*/
public int hashCode() {
return (int) this.flags;
}

/**
* Returns a 64 length String with the first flag on the right and the
* 64th flag on the left. A 1 indicates the flag is on, a 0 means it's
* off.
*
* @return string representation of this object.
*/
public String toString() {
StringBuffer bin = new StringBuffer(Long.toBinaryString(this.flags));
for (int i = 64 - bin.length(); i > 0; i--) {
bin.insert(0, "0");
}
return bin.toString();
}

3. 6. Relational Operators

3. 6. 1. Relational Operators

3. 6. 2. Relational and logical operators

3. 6. 1. Relational Operators

Relational Operators Description


> greater than
>= greater than or equal to
== equal to
!= not equal to
<= less than or equal to
< less than

3. 6. 2. Relational and logical operators

import java.util.Random;

public class MainClass {


public static void main(String[] args) {
Random rand = new Random();
int i = rand.nextInt(100);
int j = rand.nextInt(100);
System.out.println("i = " + i);
System.out.println("j = " + j);
System.out.println("i > j is " + (i > j));
System.out.println("i < j is " + (i < j));
System.out.println("i >= j is " + (i >= j));
System.out.println("i <= j is " + (i <= j));
System.out.println("i == j is " + (i == j));
System.out.println("i != j is " + (i != j));

System.out.println("(i < 10) && (j < 10) is " + ((i < 10) && (j < 10)));
System.out.println("(i < 10) || (j < 10) is " + ((i < 10) || (j < 10)));
}
}
i = 92
j = 22
i > j is true
i < j is false
i >= j is true
i <= j is false
i == j is false
i != j is true
(i < 10) && (j < 10) is false
(i < 10) || (j < 10) is false

3. 7. Logical Operators

3. 7. 1. Boolean Logical Operators

3. 7. 2. The following table shows the effect of each logical operation

3. 7. 3. Logical operators in action

3. 7. 4. Demonstrate the boolean logical operators

3. 7. 5. Logical Operators

3. 7. 6. AND operator

3. 7. 7. && versus &

3. 7. 8. Logical OR Operations

3. 7. 9. Boolean NOT Operations: applies to one boolean operand

3. 7. 10. Demonstrates short-circuiting behavior

3. 7. 1. Boolean Logical Operators

Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else

3. 7. 2. The following table shows the effect of each logical operation

A B A | B A & B A ^ B !A

False False False False False True

True False True False True False

False True True False True True

True True True True False False

3. 7. 3. Logical operators in action

public class MainClass


{
public static void main( String args[] )
{
// create truth table for && (conditional AND) operator
System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n",
"Conditional AND (&&)", "false && false", ( false && false ),
"false && true", ( false && true ),
"true && false", ( true && false ),
"true && true", ( true && true ) );

// create truth table for || (conditional OR) operator


System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n",
"Conditional OR (||)", "false || false", ( false || false ),
"false || true", ( false || true ),
"true || false", ( true || false ),
"true || true", ( true || true ) );

// create truth table for & (boolean logical AND) operator


System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n",
"Boolean logical AND (&)", "false & false", ( false & false ),
"false & true", ( false & true ),
"true & false", ( true & false ),
"true & true", ( true & true ) );
// create truth table for | (boolean logical inclusive OR) operator
System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n",
"Boolean logical inclusive OR (|)",
"false | false", ( false | false ),
"false | true", ( false | true ),
"true | false", ( true | false ),
"true | true", ( true | true ) );

// create truth table for ^ (boolean logical exclusive OR) operator


System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n",
"Boolean logical exclusive OR (^)",
"false ^ false", ( false ^ false ),
"false ^ true", ( false ^ true ),
"true ^ false", ( true ^ false ),
"true ^ true", ( true ^ true ) );

// create truth table for ! (logical negation) operator


System.out.printf( "%s\n%s: %b\n%s: %b\n", "Logical NOT (!)",
"!false", ( !false ), "!true", ( !true ) );
}
}

Conditional AND (&&)


false && false: false
false && true: false
true && false: false
true && true: true

Conditional OR (||)
false || false: false
false || true: true
true || false: true
true || true: true

Boolean logical AND (&)


false & false: false
false & true: false
true & false: false
true & true: true

Boolean logical inclusive OR (|)


false | false: false
false | true: true
true | false: true
true | true: true

Boolean logical exclusive OR (^)


false ^ false: false
false ^ true: true
true ^ false: true
true ^ true: false

Logical NOT (!)


!false: true
!true: false

3. 7. 4. Demonstrate the boolean logical operators

public class MainClass {


public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}

a = true
b = false
a|b = true
a&b = false
a^b = true
!a&b|a&!b = true
!a = false

3. 7. 5. Logical Operators

1. You use logical operators to Combine a number of conditions.


2. Logical operators operate on boolean values.

Symbol Long Name


& logical AND
&& conditional AND
| logical OR
|| conditional OR
! logical negation (NOT)

3. 7. 6. AND operator

public class MainClass {

public static void main(String[] arg) {


int a = 0;
int b = 1;

if (a == 0 && b == 1) {
System.out.println("here");
} else {
System.out.println("there");
}
}
}

here

3. 7. 7. && versus &

Conditional && will not evaluate the right-hand operand if the left-hand operand is false.
public class MainClass {

public static void main(String[] arg) {


int value = 8;
int count = 10;
int limit = 11;

if (++value % 2 == 0 & ++count < limit) {


System.out.println("here");
System.out.println(value);
System.out.println(count);
}
System.out.println("there");
System.out.println(value);
System.out.println(count);
}
}

there
9
11

3. 7. 8. Logical OR Operations

The logical OR, ||, omits the evaluation of the right-hand operand when the left-hand operand is true.
public class MainClass {

public static void main(String[] arg) {


int value = 8;
int count = 10;
int limit = 11;

if (++value % 2 == 0 | ++count < limit) {


System.out.println("here");
System.out.println(value);
System.out.println(count);
}
System.out.println("there");
System.out.println(value);
System.out.println(count);
}
}

there
9
11

3. 7. 9. Boolean NOT Operations: applies to one boolean operand

public class MainClass {

public static void main(String[] arg) {


int a = 0;
if (!(a == 0)) {
System.out.println("a is not 0");
} else {
System.out.println("a is 0");
}
}

a is 0
3. 7. 10. Demonstrates short-circuiting behavior

public class MainClass {

static boolean test1(int val) {


System.out.println("test1(" + val + ")");
System.out.println("result: " + (val < 1));
return val < 1;
}

static boolean test2(int val) {


System.out.println("test2(" + val + ")");
System.out.println("result: " + (val < 2));
return val < 2;
}

static boolean test3(int val) {


System.out.println("test3(" + val + ")");
System.out.println("result: " + (val < 3));
return val < 3;
}

public static void main(String[] args) {


if (test1(0) && test2(2) && test3(2))
System.out.println("expression is true");
else
System.out.println("expression is false");
}
}

test1(0)
result: true
test2(2)
result: false
expression is false

3. 8. Ternary Operator

3. 8. 1. The ? Operator (Ternary)

3. 8. 1. The ? Operator (Ternary)

public class MainClass {


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 ");
System.out.println(i + " is " + k);

i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}

Absolute value of 10 is 10
Absolute value of -10 is 10

3. 9. Comma Operator

3. 9. 1. Comma Operator

3. 9. 1. Comma Operator

public class MainClass {

public static void main(String[] args) {


for(int i = 1, j = i + 10; i < 5;
i++, j = i * 2) {
System.out.println("i= " + i + " j= " + j);
}
}
}

i= 1 j= 11
i= 2 j= 4
i= 3 j= 6
i= 4 j= 8

3. 10. instanceof

3. 10. 1. The instanceof Keyword

3. 10. 2. Identifying Objects


Finding Out of what Class an Object is
3. 10. 3.
Instantiated

3. 10. 4. instanceof operator and class hierarchy

3. 10. 1. The instanceof Keyword

The instanceof keyword can be used to test if an object is of a specified type.


if (objectReference instanceof type)

The following if statement returns true.


public class MainClass {
public static void main(String[] a) {

String s = "Hello";
if (s instanceof java.lang.String) {
System.out.println("is a String");
}
}

is a String
However, applying instanceof on a null reference variable returns false. For
example, the following if statement returns false.
public class MainClass {
public static void main(String[] a) {

String s = null;
if (s instanceof java.lang.String) {
System.out.println("true");
} else {
System.out.println("false");
}
}

false
Since a subclass 'is a' type of its superclass, the following if statement, where Child
is a subclass of Parent, returns true.
class Parent {
public Parent() {

}
}
class Child extends Parent {
public Child() {
super();
}
}

public class MainClass {


public static void main(String[] a) {

Child child = new Child();


if (child instanceof Parent) {
System.out.println("true");
}

true

3. 10. 2. Identifying Objects

class Animal {
public String toString() {
return "This is an animal ";
}
}
class Dog extends Animal {
public void sound() {
System.out.println("Woof Woof");
}
}
public class MainClass {
public static void main(String[] a) {
Dog aDog = new Dog();
if (aDog instanceof Animal) {
Animal ani = (Animal) aDog;
System.out.println(ani);
}
}
}

This is an animal

3. 10. 3. Finding Out of what Class an Object is Instantiated


import java.util.ArrayList;
import java.util.Vector;

public class Main {

public static void main(String[] args) {


Object testObject = new Vector();
if (testObject instanceof Vector)
System.out.println("Object was an instance of the class java.util.Vector");
else if (testObject instanceof ArrayList)
System.out.println("Object was an instance of the class java.util.ArrayList");
else
System.out.println("Object was an instance of the " + testObject.getClass());

}
}
//Object was an instance of the class java.util.Vector

3. 10. 4. instanceof operator and class hierarchy

class A {
int i, j;
}

class B {
int i, j;
}

class C extends A {
int k;
}

class D extends A {
int k;
}

class InstanceOf {
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
D d = new D();

if (a instanceof A)
System.out.println("a is instance of A");
if (b instanceof B)
System.out.println("b is instance of B");
if (c instanceof C)
System.out.println("c is instance of C");
if (c instanceof A)
System.out.println("c can be cast to A");

if (a instanceof C)
System.out.println("a can be cast to C");
System.out.println();

A ob;

ob = d; // A reference to d
System.out.println("ob now refers to d");
if (ob instanceof D)
System.out.println("ob is instance of D");

System.out.println();

ob = c; // A reference to c
System.out.println("ob now refers to c");

if (ob instanceof D)
System.out.println("ob can be cast to D");
else
System.out.println("ob cannot be cast to D");

if (ob instanceof A)
System.out.println("ob can be cast to A");

System.out.println();

// all objects can be cast to Object


if (a instanceof Object)
System.out.println("a may be cast to Object");
if (b instanceof Object)
System.out.println("b may be cast to Object");
if (c instanceof Object)
System.out.println("c may be cast to Object");
if (d instanceof Object)
System.out.println("d may be cast to Object");
}
}

You might also like