CHAPTER 4 ■ OPERATORS
context is textual, it performs concatenation operations. Listing 4-8 demonstrates what happens when
the JVM encounters different contexts:
Listing 4-8. The ShiftDemo context switching example
int a = 1;
int b = 2;
int c = 3;
System.out.println(a + b + c);
System.out.println("a + b + c = " + a + b + c);
System.out.println("a + b + c = " + (a + b + c));
When run in a program, that code produces the following output (see Listing 4-9):
Listing 4-9. Contect switching example output
6
a + b + c = 123
a + b + c = 6
The context for the first line is numeric, because the first value processed by the println method is
numeric. The context for the second line is textual because the first value processed by the println
method is a String literal. The third line gets the right value because the parentheses force the addition to
happen first, even though the context is textual.
Shift Operators
The shift operators take us back to working with bits. The shift operators require two operands: The
integral (no floating-point values allowed) value to shift and the number of places to shift the bits that
comprise the value. The signed left shift operator (<<) shifts bits to the left. The signed right shift
operator (>>) shifts bits to the right. The signed right shift operator (>>>) shifts bits to the right and fills
the left bits with zeroes.
■ Note The shift operators work only on integer values.
Listing 4-10 demonstrates what the shift operators do to the value of an int variable.
Listing 4-10. ShiftDemo
package com.apress.javaforabsolutebeginners .examples.shiftDemo;
public class ShiftDemo {
public static void main(String[] args) throws Exception {
int b = 127;
System.out.println("b: " + b);