Test Your Java Knowledge

Using Operators and Making Assignments, Part 3

Questions

By Richard G. Baldwin

Lesson 9

December 9, 2000


Welcome

The purpose of this series of tutorial lessons is to help you learn Java by approaching it from a question and answer viewpoint.

I recommend that you also make use of my online Java tutorial lessons, which are designed from a more conventional textbook approach.  Those tutorial lessons are published at Gamelan.com.

For your convenience, I also maintain a consolidated Table of Contents on my personal web site that links to the individual lessons on the Gamelan site.

Insofar as possible, I will make use of Sun Java in these lessons.  However, it will not be possible for me to go back and do a full update each time Sun releases a new version, so over the course of time, I expect to use different versions of Sun Java.

Just in case you would like to sneak a peek, the answers to the questions, and the explanations of those answers are located (in reverse order) at the end of this file.

The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the question to the answer and back.  It is recommended that you make your first pass through the questions in the order that they appear so as to avoid inadvertently seeing the answer to a question before you provide your own answer.



1.  What is the operator for the bit shift and rotate operation in Java?

Answer and Explanation

2.  True or false?  Integer division by zero, including a modulo (%) operation results in an ArithmeticException.  No other arithmetic operation in Java can throw an exception.  Instead, all other arithmetic operations proceed to a result, even though that result might be arithmetically incorrect.

Answer and Explanation

3.  What output is produced by the following program?

class Q84{
  public static void main(
                        String args[]){
    try{
      byte x = 5;
      byte y = x << 2;
      System.out.println(y);
    }catch(Exception e){
      System.out.println("Exception");
    }//end catch
  }//end main()
}//end class definition

Answer and Explanation

4.  What output is produced by the following program?

class Q85{
  public static void main(
                        String args[]){
    try{
      byte x = 5;
      byte y = (byte)(x << 2);
      System.out.println(y);
    }catch(Exception e){
      System.out.println("Exception");
    }//end catch
  }//end main()
}//end class definition

Answer and Explanation

5.  What output is produced by the following program?

class Q86{
  public static void main(
                        String args[]){
    try{
      byte x = 32;
      byte y = (byte)(x << 2);
      System.out.println(y);
    }catch(Exception e){
      System.out.println("Exception");
    }//end catch
  }//end main()
}//end class definition

Answer and Explanation

6.  What output is produced by the following program?

class Q87{
  public static void main(
                        String args[]){
    try{
      byte x = -32;
      byte y = (byte)(x >> 2);
      System.out.println(y);
    }catch(Exception e){
      System.out.println("Exception");
    }//end catch
  }//end main()
}//end class definition

Answer and Explanation

7.  What output is produced by the following program?

class Q88{
  public static void main(
                        String args[]){
    try{
      int x = -32;
      int y = x >>> 2;
      System.out.println(y);
    }catch(Exception e){
      System.out.println("Exception");
    }//end catch
  }//end main()
}//end class definition

Answer and Explanation

8.  What output is produced by the following program?

class Q89{
  public static void main(
                        String args[]){
    try{
      byte x = -32;
      byte y = (byte)(x >>> 2);
      System.out.println(y);
    }catch(Exception e){
      System.out.println("Exception");
    }//end catch
  }//end main()
}//end class definition

Answer and Explanation

9.  What output is produced by the following program?

class Q90{
  public static void main(
                        String args[]){
    try{
      int x = -7;
      System.out.println(
                x/2 + " " + (x >> 1) );
    }catch(Exception e){
      System.out.println("Exception");
    }//end catch
  }//end main()
}//end class definition

Answer and Explanation

10.  What output is produced by the following program?

class Q91{
  public static void main(
                        String args[]){
    try{
      int x = 16384;
      System.out.println(x >> 33);
    }catch(Exception e){
      System.out.println("Exception");
    }//end catch
  }//end main()
}//end class definition

Answer and Explanation



Copyright 2000, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com



 

Answers and Explanations

Answer 10

F.  None of the above

Back to Question 10

Explanation 10

For an int or a long, a signed right shift will not shift more than the number of bits used to represent the type being shifted.

If the specified number of bits to be shifted exceeds this number, then the number of bit positions actually shifted is the specified number modulo the number of bits in the type.

In this case, the number of bits actually shifted is 33 modulo 32 or 1.  This gives a result of 16384/2 or 8192.

Answer 9

D.  -3 -4

Back to Question 9

Explanation 9

Whereas integer division truncates to the next lower integer value in an absolute sense, division by right shifting truncates to the next lower integer value in an algebraic sense.  Algebraically, -4 is a "lower" integer value than -3.

Answer 8

D.  -8

Back to Question 8

Explanation 8

Although the unsigned right shift pulls zeros in at the most significant end, the shift is actually performed on a sign-extended int representation of the byte data.  When the shifted result is then cast back to type byte, the most significant 24 bits are discarded, leaving a result that is exactly the same as performing a signed right shift on the same byte data.  Thus, the byte value of -32 is divided by 4 giving a result of -8.

Answer 7

G.  None of the above

Back to Question 7

Explanation 7

The following statement in this program performs an unsigned right shift on x and stores the resulting bit pattern in y:

int y = x >>> 2;

An unsigned right shift pulls a zero into the most-significant bit as each shift takes place, regardless of whether the original value was positive or negative.

The original value of x expressed in decimal was:

-32

The original value of x, corresponding to -32 and expressed as a hexadecimal string was:

ffffffe0

After the shift, the value of y expressed as a hexadecimal string was:

3ffffff8

When expressed as a decimal value, this is:

1073741816

In comparison, if this were a signed right shift, the four values in the same order as above would be:

-32
ffffffe0
fffffff8
-8

Thus, an unsigned right shift on a negative value does not preserve the sign and does not result in values that are easily explained in terms of simple division by a factor of two.  Generally speaking, the unsigned right-shift operator should not be thought of in terms of arithmetic division.  Rather, it has other purposes.

Answer 6

D.  -8

Back to Question 6

Explanation 6

A signed right shift of a negative number by two bits divides the value by a factor of 4, preserving the sign.  In this case, the value -32 is shifted to the right by two bits, dividing it by 4, and giving a resulting value of -8.

Answer 5

G.  None of the above.

Back to Question 5

Explanation 5

All byte and short types are promoted to type int before being shifted.  When the byte value of 32 is promoted to an int and shifted two bits to the left, the resulting value is 128.  However, when it is cast back to a byte and stored in the variable named y, significant data is lost in the process, and the nonsense value of -128 is produced.

Answer 4

F.  20

Back to Question 4

Explanation 4

Each time an integer value is shifted one bit to the right, its value is divided by two.  Any fractional part resulting from the division is lost.

Each time an integer value is shifted one bit to the left, its value is multiplied by a factor of two, provided that no data is lost in the process.

Therefore, a two-bit left shift multiplies the operand by a factor of 4, provided no data is lost in the process.  In this case, no data was lost, and the value assigned to y was equal to the value stored in x multiplied by four, giving a result of 20.

Answer 3

A.  A compiler error

Back to Question 3

Explanation 3

All byte and short types are promoted to type int before being shifted. The result of the shift is type int.  Does this matter?  Sometimes it does.

In this case, the shifted result must be explicitly cast back to type byte before being assigned to a byte variable.  Of course, the use of a cast operator following a left shift can sometimes cause a loss of data in the higher-order bits that are discarded in the conversion.

Under JDK 1.3, the compiler error reads as follows:

Q84.java:8: possible loss of precision
found   : int
required: byte
      byte y = x << 2;

Other compilers may provide a different error message that means the same thing.

Answer 2

True.

Back to Question 2

Explanation 2

According to The Complete Java 2 Certification Study Guide by Roberts, Heller, and Ernest, the statement provided in this question is true.  The authors go on to explain about infinity, NaN, and how certain integer operations can produce incorrect results due to truncation.

For example, the largest positive value that can be stored in type int, as indicated by the constant named Integer.MAX_VALUE, is 2147483647.  The following statement is intended to produce a result that is twice the maximum value.

System.out.println(
   2*Integer.MAX_VALUE);

However, it produces the output value -2 instead.  This indicates serious arithmetic overflow problems.

It is very important to understand that this arithmetic error does not throw an exception.  Rather, it simply produces an incorrect result.

One way to avoid this particular problem is to force the arithmetic to be performed as type long as shown below:

System.out.println(
   (long)2*Integer.MAX_VALUE);

This statement produces the output 4294967294 as expected.

If you do this, however, you must be careful not to cast the result back to type int, or you will simply reintroduce the same problem as before.

Answer 1

There is no bit shift and rotate operator.

Back to Question 1

Explanation 1

This question is designed specifically for those of you whose programming background supports the rotation of the least-significant bit into the most-significant bit in a right-shift operation.  There is no bit shift and rotate operation in Java, so there is no such operator.



Copyright 2000, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com

-end-