001package beginner; 002 003import com.sandwich.koan.Koan; 004 005import static com.sandwich.koan.constant.KoanConstants.__; 006import static com.sandwich.util.Assert.assertEquals; 007 008public class AboutBitwiseOperators { 009 010 @Koan 011 public void fullAnd() { 012 int i = 1; 013 if (true & (++i < 8)) i = i + 1; 014 assertEquals(i, __); 015 } 016 017 @Koan 018 public void shortCircuitAnd() { 019 int i = 1; 020 if (true && (i < -28)) i = i + 1; 021 assertEquals(i, __); 022 } 023 024 @Koan 025 public void aboutXOR() { 026 int i = 1; 027 int a = 6; 028 if ((a < 9) ^ false) i = i + 1; 029 assertEquals(i, __); 030 } 031 032 @Koan 033 public void dontMistakeEqualsForEqualsEquals() { 034 int i = 1; 035 boolean a = false; 036 if (a = true) i++; 037 assertEquals(a, __); 038 assertEquals(i, __); 039 // How could you write the condition 'with a twist' to avoid this trap? 040 } 041 042 @Koan 043 public void aboutBitShiftingRightShift() { 044 int rightShift = 8; 045 rightShift = rightShift >> 1; 046 assertEquals(rightShift, __); 047 } 048 049 @Koan 050 public void aboutBitShiftingLeftShift() { 051 int leftShift = 0x80000000; // Is this number positive or negative? 052 leftShift = leftShift << 1; 053 assertEquals(leftShift, __); 054 } 055 056 @Koan 057 public void aboutBitShiftingRightUnsigned() { 058 int rightShiftNegativeStaysNegative = 0x80000000; 059 rightShiftNegativeStaysNegative = rightShiftNegativeStaysNegative >> 4; 060 assertEquals(rightShiftNegativeStaysNegative, __); 061 int unsignedRightShift = 0x80000000; // always fills with 0 062 unsignedRightShift >>>= 4; // Just like += 063 assertEquals(unsignedRightShift, __); 064 } 065}