Java Operators   

Peter Komisar
©      Conestoga College        version 5.4         2008


So far in the course we have seen how the Java system
works at the 'macroscopic' level of the language, the world
of classes and objects and their internal members. We now
zoom into Java's 'micro' zone, below the packages which
contain more packages which contain classes containing
variables, constructors and methods (and perhaps other
nested classes).

Inside the class, usually inside methods and constructors, 
Java language statements are defined. The statements in
turn are made of expressions. The expressions are made
up of operators and operands, the atomic elements of the
Java language.

Those of you who are familiar with other programming
languages, can relax a little. Java is pretty conventional
in how it defines and uses operators.



Operands, Unary, Binary & Ternary Operators


Operators are a little like methods but much more primitive.
They are the verbs of the language at the atomic level.
These operators work on values or variables. Depending
on the operator, the variables may be primitive or reference
types.

Operators do the rudimentary tasks that are required of a
computer program like adding and dividing. The value or
variable that
is acted on by an operator is called an 'operand'.
If an operator works on a single
operand it is called a 'unary'
operator.

Example 

x ++  

// the post increment operator is a unary operator


If the operator works on two operands, it is called a 'binary'
operator. An example of a binary operator is the multiplication
operator, *.


Example

int x = 4 * 3; 

// the multiplication operator is a binary operator


There is only one 'ternary' operator in java, which works
on three operands. It is an abbreviated form of an 'if else'
statement. We will explain this operator shortly.  


Example  

String boo=false? "Boo" : "Hoo" ;
              System.out.println(boo);    

// The ternary operator will assign boo the value "Hoo" here



Precedence, Associativity & Order of Evaluation 

Precedence

The order in which operations are executed is governed
by the rules of precedence, associativity and order of
evaluation. Precedence is the idea that certain operations
will occur
before others. We expect multiplication to occur
before addition as in the
following example.


Example 1
   

3 + 2 * 2  // evaluates to 7  not 10

We can use round brackets to overrule the default rules
of precedence.


Example 2
    (3 + 2) * 2  
// does evaluate to 10
 

Associativity

Associativity is the property that decides which operation
goes first when operators
have equal precedence. This
property is the 'tie breaker' between operations with equal

precedence in an expression. For instance, the multiplication
and modula operators
have the same precedence. Which
operator executes first is explained shortly.


Example    

4 * 5  % 10

// if operators have the same precedence,
// rules of associativity decide which goes first

The Coffee Pot Property

Peter Van Der Linden in his book 'Just Java' describes
the 'Coffee Pot' rule which is used to decide between
operators with equal precedence. The name
abbreviates
'Code Order For Finding Evaluating Equal Precedence
Operator Textstrings'.

One might suspect the rule was invented over coffee and
the words were invented to fit the phrase! The 'code order'
that the rule describes is
summarized in tables below.

With respect to the example above, the rule states that
multiplication and division are
left-associative and so are
evaluated from left to right as in ( 4 * 5 ) % 10.

 

Order of Evaluation

Order of Evaluation describes the sequence in which
operands are evaluated. Java
is strictly a left to right
language for order of evaluation. Notice we are talking
about
values and variables. This means the value of the
left most operand is evaluated first and the left most
operand is evaluated last. Evaluation proceeds before
any operations are done.


Example

// Example adapted from the 'JavaCertification Guide',
// by Heller & Roberts

int [] A = new  int [2];
int b =(1+2) / 3 ;
A [ b ] = b = 1-1;

The question is which value of b is used?

Looking at the third line and evaluating left to right, A[b]
is evaluated first. 'b' needs for be determined in order to
evaluate A so it evaluated and set to the value 1. This
evaluation determines the second element of the A array
will be the receiver of the assignment.

Moving to the right b is evaluated again at it's second
occurrence in the statement. Once more, it takes it's
value from the value, 1. Then the simple expression
1-1 is evaluated to 0. That ends the evaluation phase.

// first evaluation takes place left to right

Now the operations take place in order of precedence
and associativity. First we see the two assignments
have equal precedence so we need to refer to the table
describing the CoffeePot rule for associativity. We notice
assignment is listed under the right-associative operators
so assignment proceeds from right to left. The value zero
is assigned to variable b, displacing it's previous value of
1 and then the value zero held in b is assigned to the
second element of array A.
 

Java Operators in Order of Precedence
 
  Operator Type  Operator Symbols   Precedence
 Braces,the
 Dot Operator
 ( )   { }     .   
  highest
 Unary  ++   --   -   +   ! ~ 
 (type cast)
 pre     16
 post   15
 ~ !      14
 (cast) 13
 Arithmetic   *   /    %   +   -  * / %   12
   + -    11
 Shift    <<    >>    >>>            10
 Comparison    <  <=  >  >= 
  instanceof
            9
 Equality   ==   !=             8
 Bitwise   &     ^     |   &        7
 ^         6
 |          5
 Short Circuit   &&    ||  &&    4
 ||       3
 Ternary   ? :           2 
 Assignment
  (= or op= )
 =   *=  /=  %=  +=
 -=  <<= >>>= >>>=
 &=   ^=  |=
 lowest  1
 

Coffee Pot rule for determining Associativity
// higher # corresponds  to higher precedence

 
 left associative
 operators
 precedence  right associative
 operators
 precedence
 post-increment
 & decrement
 15  ++ pre-increment & decrement   16
 *  /  %  multiplicative   12  ~ inversion (bit flip)   14
 + -   add and subtract  11  !  logical not   14 
 <<   >>   >>>   bit wise shift  10  - + arithmetic negative & positive  14
 instanceof  <  <=  >  >=  relational    9   type conversion (cast)  13
 ==   !=    equality    8  . .
 &   bitwise AND    7 . .
 ^ exclusive OR    6 . .
 |   bitwise (inclusive) OR   5 . .
 && conditional AND    4  tertiary (conditional) operator   2
   | |  conditional OR    3  assignment     = *=  /= %= += 
 -=  <<=  >>=  >>>=  &=  ^=   |= 
  1



Unary Operators


The increment  & decrement Operators, ++ &  - -

The increment and decrement operators modify a value
of an operand by adding or subtracting 1. They come in
pre- and post- versions. The pre-increment/decrement
types carry out their operations before they are involved
in an operation while the post versions execute after.


Example  1    

int start = 7;
int getPost = start ++;

 // in post-increment, getPost has value 7 assigned
// then start is incremented to 8

Example 2      

int start2 = 11;
int getPre = ++start2;

// in pre-increment, first start2 is incremented to 12,
// then getPre is assigned 12

 

Code Example

class OpShow{
    public static void main(String[] args){
        int X,Y, preTake, postTake;
        X=1;
        postTake=X++;
        Y=1;
        preTake=++Y;

// Examine what  the values that each variable contain after the pre
// and post increment operations

System.out.println("X is now " + X +
                                  " and postTake has the value " + postTake);
System.out.println("Y is now " + Y +
                                  " and preTake has the value " + preTake);
    }
}

OUTPUT

[Examples]$ java OpShow
X is now 2 and postTake has the value 1
Y is now 2 and preTake has the value 2


The Unary +  and  -  Operators  // overloaded versions

Unary ' + ' and ' - ' are distinct from the binary + and -
which usually refer to add and
subtract. These operators
precede the expression that they are being applied
to.
The unary + operator makes a value explicitly positive
while the unary - negates
an expression. These operators
can be applied to literal values as well as variables
and
larger expressions.


Example  
 

int x= +3;
int y=  -3;
int z =  2;
z= -z;
z = - ( x + y + z );
 

The Bitwise Inversion Operator, ~

The ~ operator performs bitwise inversion on integral
types. The bitwise operator
operates at the machine
language level of the computer. At this binary level,
the 0s and
1s are inverted; zeros become ones and
ones become zeros. For example, applying
the
bitwise inversion operator to the byte value 5 causes
it's binary representation,
0000 0101 to becomes
1111 1010.


Example

class Inversion{
    public static void main(String[] args){
       int five = 5;
       int invert = ~5;
       System.out.println
                 ("five: " + five + " five inverted: " + invert );
    }
}

OUTPUT

[Examples]$ java Inversion
five: 5 five inverted: -6

The inversion operator can be applied to literals, variables
and larger expressions. How the operator is applied is
shown
in the following example. Notice the ~ can only be
applied to
integral values and not type floating point types
like float and double.

// not used with floating point types

The first example below works because the bitwise
operator inverts the integral value before it is
promoted
to the double type.  

Example     

double doo = ~ 1;  

// works as the operator applies before promotion to double

The second demonstrates that the bitwise operator cannot
be applied to a double.

double doo = 6;
double doonut= ~doo;      // doesn't compile
           
 

The Boolean Complement Operator !

The ! operator inverts the value of a boolean expression.
The value ' !true ' evaluates to ' false '
and  ' !false '
evaluates to ' true '. This operator only applies to boolean
type so ' !1 ',  for
instance is illegal. The following example
shows the complement operator applied to a literal boolean
value, false and to a boolean variable.

Example

boolean boo;    // if declared in class scope the boolean default is false
boo= !false;       // boo stores true
boo = !boo;     // but now it's reverted to false again

boo=!4              //  not a legal form

The Cast Operator, ( type )

Casts can be made to explicitly change the type of an
expression. Casts can be
applied to primitive values as
well as reference values We have seen there are a lot
of
rules, with respect to primitives and reference types,
covering which assignments and casts are legal or not.


Example 

double d = 1.412;
int i = (int) d;     // 1.412  is converted to the int value 1


The following shows a primitive cast that is not allowed.

Example

boolean bee = true;
char unsigned = (char)bee;  //  inconvertible types'



Arithmetic Operators


Multiplication and Division Operators * and  /

The * and / operators perform multiplication and division
on primitive numeric types
including the 'char' type.
Multiplying two integer types may result in 'overflow',
the
condition where a number is too large to be
represented by the range of it's type.
In this case a
relatively meaningless value is obtained. ( The term
relatively is used as
the overflow occurs in a logical
manner).

// two integers multiplied out of range is called 'overflow'

Dividing with integers may result in the loss of fractional
information so a 'loss of precision' occurs.
(Integer division
truncates towards zero. 9/5 is equivalent to 1.8 and
truncates to 1. -9/2 is equivalent to -4.5 and truncates
to -4 )

// two integers divided so that fractional information is loss
// is referred to as a 'loss of precision'.


How fractional results are interpreted in integral divides

           ------|------|------|------|------|------|------|-------
negative fractions truncate towards zero -> 0 <- positive fractions truncate towards zero
         (i.e -3.7 becomes -3 )                           (i.e. 4.9 becomes 4 )



The following examples show overflow and loss of precision
due to truncation.


Example

int bigInt= 2147483647;      // the biggest int before overflow
int lever= 1;
int  tooBig = bigInt + lever;

// adding one overflows to the largest negative int value,
// -2147483648

int x = 9;
int y = 5;
int z = x / y;    

// case of integer imprecision shows the value of 9/5 is
// reduced to the value 1


If forced to do an operation involving both a multiplication,
that will go meaninglessly out of
range, and a division that
will lose precision, it is better to divide
and lose precision
first and then to multiply, staying in range, as you are at
least left
with a value that has some strict meaning.
 

The Modulo Operator  %

The modulo operator is also called the remainder operator.
The operator returns the remainder of a division. It is usually
used with integer values but may also by used with floating
point types. As with a division of integer types by zero
involving
a modulo operator will throw the ArithmeticException
at runtime.

Example

int h = -7 % 2; // h is assigned the value -1
int mod = 9 % 3;    // 9 divided by 3 is 3 with a 0 remainder so 0 is assigned to mod
int ula  = 9 % 2;     // 9 divided by 2 is 4 with 1 remainder so 1 is assigned to mod
int err = 9 % 0;      // this compiles but throws an ArithmeticException at runtime


Floating Point Example With Modulo

class H{
public static void main(String[] args){
 double d =4.8 % 2.3;
 System.out.println(d);
 }
 }

OUTPUT

>java H
0.20000000000000018

 
 
More on  Modulo 

 Heller & Robert's in ' The JavaCertification Guide'
 offer the following useful rule for
calculating modulo
 results from negative numbers: 

 Drop the negative signs from either operand. Calculate
 the result. If the  original left-hand
operand was negative,
 negate the result. The sign of the right hand operand is
 irrelevant.  

 if (-3%-2 == -3%2)
 System.out.println("Heller & Robert's rule is true");
 // is true!

   .


 

The Addition and Subtraction Operators + and  -

The addition and subtraction operator are perhaps the most
predictable because they are so familiar. The operators, +
and - perform addition and subtraction. The addition operator
+ is also Java's only overloaded operator. This means it has
two functions depending on the context in which it is used.
The + operator also does concatenation. We have frequently
seen the + operator used in this context as in the following
example.


Example
 

String waterfall = "water" + "fall";


The following example shows the + operator being used
to add two numbers. The + operator promotes the result
to String type and concatenates the newly formed string
to the preceding String literal, "One plus two is 3".


Example   

System.out.println ("One plus two is " + ( 1 + 2 ) );
 
// + is used as a unary operator as well


Shift Operators


Shift operators work at the binary level, shifting the bit
patterns of integral numbers left or right. When shift
operators are used on types smaller than int they are
first promoted to the int type. Given this fact, these
operators should normally just be used with 'int' and
long types.

At the register levels of the computer, shifting is done
using a technique that results in a cyclic shift behavior
whenever the number of shifts are more than the number
of bits used in the type being shifted. For instance, for an
int type, a shift of 34 will have the same effect as a shift
of 2 and a shift of ( ( 32 * 3 ) + 1) or 97 will have the same
effect as a shift of 1.

Example  

System.out.println
((4000>>33) + " is the same as " + (4000>>1));

// The output is '2000 is the same as 2000'
 

The signed right shift operator   >>

The signed right shift operator moves the bit pattern to
the right, filling vacated top most bit positions with the
same value that was there before the shift, maintaining
the sign of the number.

For example, the number 8, when represented as an
int in binary form is shown below. ( Spacing, color and
bolding are used to clarity the example.)

Example     

0000 0000   0000 0000   0000 0000  0000 1000
 

The following shift statement results in the this bit pattern
being right shifted two places. The right most two ones
are lost and the top bit, each shift is replaced with the
values that had been stored there before, in the case of
a positive number the top most bit will be a zero.

Right Shift Two Places

int v = 8 >> 2;
 

The result of the shift is the creation of the binary
representation of the number 2. The net effect is a
division by two for each time the bit pattern is shifted.

Example     

0000 0000   0000 0000   0000 0000  0000 0010


If the top most bit is a binary one the value created would
be a negative number and the bit values added would be
ones retaining the sign by adding two more binary ones.
Following is an example of logically right shifting a
negative number.

Example        

1111 1111   1111 1111   1111 1111   1111 1000

int v = -8 >> 2;

1111 1111   1111 1111   1111 1111 1111 1110
 

The signed left shift operator,   <<

The signed left shift operator works opposite to the right
shift operator shifting values
to the left, filling the least
significant bit positions with zeros. The net effect of the
shift is to multiply the value by two for each shift of the
bits to the left.
 

The unsigned right shift operator,  >>>     

The unsigned right shift operator shifts in the same way
the signed right shift operator
does except it always zero
fills the most significant digit whether that bit was originally

a 1 or a zero. Thus the output of an unsigned right shift
operator is always a positive
number. This can create
some odd results when doing an unsigned right shift
on
a small negative number.

Following is the before and after bit pattern of a unsigned
right shift. Notice a relatively small negative number
becomes a huge positive number.

Example        

1111 1111   1111 1111   1111 1111   1111 1000

int v = -8 >>> 2;

0011 1111   1111 1111   1111 1111 1111 1110

The unsigned right shift number had a technical origin
and was not designed in the first case to be used for
arithmetic. It could be used with the unsigned char type
or in graphics where color values are always positive.
It may also be used in logic circuits to do sequential
switching at the binary level.
 


Comparison Operators


The Equality and Inequality Operators = =  and !=

The operators, ' = = '  and ' !=  ' , are used to test for
equality and inequality and return a boolean value. For

primitives, actual values are compared. For reference
types, memory locations are compared.
These operators
should not be used to compare the contents pointed to
by object references.
This is a so called 'deep comparison'
for which the equals( ) method is provided to all objects

as it is defined in the Object class.


Example  
 

int  L=4321;
int R=4321;
if (L==R)    // evaluates to true so L will be assigned 0
L=0;


The ordinal comparison operators ,  <     >   <=    >=

The ordinal comparison operators are used to compare
numbers. They evaluate to
a boolean value, true or false.
Different types can be compared using the ordinal
operators.


Example

int p = 12;
double d= 244;
if (p < d )
System.out.println(" True, p is less than d");     

// p is less than d so the line is printed
 

The instanceof Operator

The instanceof operator is unique in that it is also a
keyword. Notice it follows the keyword pattern of being
all lowercase. It is used to do comparisons on reference
types. It returns true if the class type represented by the
reference in the left argument is the same type represented
in the right-hand argument. In other words, the left argument
type must be an object of the class or a subclass of the
type represented by the right-side argument.


Example 
  

String s ="X";
  if ( s instanceof Object )
  System.out.println
("Evaluates to true as all classes share Object type");

 



Logical Operators


The Bitwise Operators

The bitwise operators, & , |  and  ^  are used to do
boolean logic at the bitwise level
of integral types.
They provide bitwise AND OR and Exclusive OR
operations, taking either two booleans or integral type
operands.

They follow the boolean algebra rules where

1) 1 AND 1 yields 1, all other combinations produce zero.
2) 0 OR 0 yields 0, all other combinations produce 1.
3) 1 XOR 0 and 0 XOR 1 both produce 1, and any other
   combination results in zero.

The following tables show how the different operators
work with different boolean combinations of values.
 

 The AND Operator, &,  Used with Bitwise and Boolean Combinations
 
 0 (false)  AND  0 (false)  evaluates to  0 (false) 
 1 (true)   AND   0( false)   evaluates to  0 (false) 
 0 (false)  AND   1 (true)   evaluates to  0 (false)
 1 (true)   AND   1 (true)   evaluates to  1 (true) 


The first table shows with AND operations both values
have to be 1 or true for the result to be true.
 

 The OR Operator, | , Used With Bitwise and Boolean Combinations
 
 0 (false)  OR  0 (false)  evaluates to  0 (false) 
 1 (true)  OR  0( false)   evaluates to  1 (true) 
 0 (false)  OR  1 (true)   evaluates to  1 (true) 
 1 (true)   OR  1 (true)   evaluates to  1 (true) 


With the OR operation, only when both values are 0 or false
does the resultant value evaluate to false.


Exclusive OR, ^ ,  Bitwise and Boolean Combinations

 
 0 (false)  OR  0 (false)  evaluates to  0 (false) 
 1 (true)   OR  0( false)   evaluates to  1 (true) 
 0 (false)  OR  1 (true)   evaluates to  1 (true) 
 1 (true)   OR  1 (true)   evaluates to  0 (false) 


With the Exclusive OR operation, only when both values
are different does the result evaluate to true. Otherwise
the resultant value is false. The following code shows the
effect of the bitwise & operator.


Code Example

class BitWise{
  public static void main(String[]args){
    System.out.println
     ("OR combos: FF:" + (false | false) + " FT:" + (false | true)
                     + " TF:" + (true | false) + " TT:" + (true | true));    
    System.out.println
     ("AND combos: FF:" + (false & false) + " FT:" + (false & true)
                       + " TF:" + (true & false) + " TT:" + (true & true));
    System.out.println
     ("XOR combos: FF:" + (false ^ false) + " FT:" + (false ^ true)
                       + " TF:" + (true ^ false) + " TT:" + (true ^ true));
    }
}

OUTPUT

[Examples]$ java BitWise
OR combos: FF:false FT:true TF:true TT:true
AND combos: FF:false FT:false TF:false TT:true
XOR combos: FF:false FT:true TF:true TT:false


When applied to numbers the bits in each digit column are
submitted to and / or operations.  The following statement
can be interpreted in binary as shown below. Applying the
OR operation to each column results in the binary 7.


Example 
 

int j= 5 | 2;

// at the binary level the following results

0000 0101    // 5  in binary   OR
0000 0010    // 2 in binary
0000 0111    // results in 7 binary
 

//   System.out.println( 5 | 2 );' outputs ' 7 '
//   System.out.println( 4 | 4); outputs  ' 4 '
 

Short Circuit Operators, &&  and  ||

The short circuit operators, && and  || , are also called
the 'conditional AND / OR
' operators. These operators
only take boolean values and do not work on number

types. The 'short circuit' accolade derives from the
operator's characteristic behavior where
the second
expression is not evaluated if the results of the first
evaluation predict the ultimate outcome of the &&
evaluation. 

For instance a 'false' evaluation in the left hand operand
of an && operation will result in a false for the whole
evaluation so the right hand operand of an && operation
need not be evaluated.  


There is no short circuit XOR operator. The advantage
these operators offer is they
allow eliminating  a second
evaluation that may result in unnecessary code execution
or the generation of some error
condition.

Example         

JLabel label=null;
  if( ( label != null ) && label.isVisible( ) ) {
        System.out.println
        (" The label is assigned an object and is visible");

        }   
        System.out.println("The label variable is null");


Avoiding Throwing a NullPointer Exception

This operator allows testing if a class is null and avoiding
calling a method on the
class. If the isVisible( ) method is
called on a null reference a NullPointerException
would be
thrown.

The following code, includes the use of the short-circuit
operator and the similar bitwise comparison operator. The
code that uses the bitwise comparison evaluates both
boolean expressions and causes the NullPointerException
to be thrown. Error handling code is included to supply a
'graceful exit'.

Code Sample

import javax.swing.*;

class ShortCircuits{
public static void main(String[] args){
 
JLabel label=null;
   // Using the short circuit operator

  if( ( label != null ) && label.isVisible( ) )
      System.out.println
      (" \'label\' references a JLabel object and is visible");
  else   
     System.out.println
                     ("The label reference holds a null value");

  // compared to the regular bitwise comparison operator
 try{
  if( ( label != null ) & label.isVisible( ) )
      System.out.println
         (" \'label\' references a JLabel object and is visible");
  else   
     System.out.println("The label reference holds a null value");
    }
    catch(NullPointerException ne){
    System.out.println("A NullPointerException was thrown");
    }
  }
}

OUTPUT

[Examples]$ java ShortCircuits
The label reference holds a null value
A NullPointerException was thrown


Assignment & Ternary Operators


Assignment Operators

The assignment operator is the lowest operator on the
totem pole. It makes sense as clearly assignment is the
last thing you would want to happen after an expression
is fully completed. In this sense, assignment is 'last but
not least'.

The assignment operator ,may be combined with other
operators to create various short forms. The general
formula is  op =  where op may be  *, /, %, +, -, <<, >>,
>>>, &, ^, and |. In combo type assignment operators,
the specified operator executes first and then the
assignment is made.


Examples
  

int p += 5;      // is the same as
p= p + 5;

int n=1000;
n<<=2;  // is the same as
n = n << 2;
 

The Ternary if...else   Operator,  ?   :

The ternary if... else operator is a short form of the if ...
else construct. It has the
form illustrated in the following
statement.

Ternary Operator Form

a = (boolean expression) ? b : c;

// where b and c must be type compatible with a.


Example
 

      boolean b = true ;
      int x=0;
      int y=1;
      int z=2;
      x = b ? y :  z ;

// results in 1 being assigned to x. If bool was false 2
// would be assigned to x.

The ternary if else operator also works on reference types.


Example    

class Ternary{
public static void main(String[] args){
String XX=new String("X" );
String XY=new String("Y" );
String q=XX.equals(XY)?XX:XY;
System.out.println(q);

}


// Output is Y



Self Test                            Self Test With Answers

1) Precedence tell us the expression ( 7*3+3*2 ) evaluates to

a) 48
b) 84
c) 27
d) 60
 

2) The variable x when combined with ++ is best described as

a) an operand being acted upon by a unary operator
b) a operator acted upon by a operand
c) an operand being acted on by two binary operators
d) an unary operand used with a variable operator
 

3) Which of the following has the highest precedence

a ) assignment operators
b) post-increment operators
c) addition and subtraction operators
d) short circuit operators
 

4) In the following code what will be printed to console?

    int x=9;
    int y= --x;
    System.out.println( y );

 a) 7
 b) 8
 c) 9
 d) 10
 

5) int zz = 6;          ( Hint: Do the binary )
     int k= ~zz;

a)   5
b) -5
c) -6
d) -7
 

6) Which of the following is not legal?

a) long lo= ~3L;
b double dx= ~7.0;
c) double dy= float(~1 );
d) int j = int (~l);
 

7)  In the following statement int oxo stores which of the following values?

     int oxo= -8 % -5;

a )  -1
b)    1
c)   -3
d)    3
 

8 ) What number is stored in c as the result of the division?

     int a=  14;
     int b = -5;
     int c=a/b;

a )   -2.8
b)       -3
c)       -2
d)    -3.0
 

9) Which of the following expressions result in a very large positive number?

a)  ( -30 <<  20 )
b)  ( 200 >>   6 )
c)  ( 400 >>> 8 )
d)  (   -3 >>> 2 )
 

10)  The following code will print out which one of the following lettered statements?

        boolean yes=true;
        int y = yes? 7: 11;
           if ( y == (6+1)   |   false ) {
              System.out.println( "Lucky Seven!");
              }
        else{
              System.out.println("I guess not!");
              }
           if (y == 7 &  false  ) {
              System.out.println( "Whatever!");
              }
    else if ( y==11){
              System.out.println("Must be Eleven!");
              }
 

a) Lucky Seven!
b) I guess not!
c) Whatever!
d) Must be Eleven!
 


Exercise


1) Create a program that outputs the results of using the AND, OR
and Exclusive  OR operators in all possible combinations both for 1s
and zeros and for boolean values. The model used in the example in
the discussion above can be used and extended.

// Hint: One of the examples is much like this.
// Better to do this exercise without referring to it

2) Use 6 of the operators to work on 6 numbers to create a lotto
number generator. Lotto 649 in Ontario uses 6 two digit numbers
between 0 and  49 inclusive. Some how scrambler numbers should
be derived from adjacent numbers. The modulo operator is handy
to use to restrict the range of the resultant number to 0 to 49. You
can also use them in combination. There is a random number
generator in the Math class but we can go without it.
 

Example

     A birthday  27th of June 1960  could be used for four starting numbers.
     As well today's date could be used. say 17 of the 11 month. For now
     we can pass the arguments in from the command line and store them in
     main's String array.

      06 27 19 60 17 11

     // samples
     int one= ( 06 * 27 * 19 * 60 * 17 * 11 )  %  49;
     int two = ( 06 | 27 | 19 | 60 | 17 | 11 ) % 49;
      // etc.

System.out.println ( Your lotto 649 numbers are " one + "  " + two  + " etc");