Test Your Java Knowledge

Using Operators and Making Assignments, Part 1

Questions

By Richard G. Baldwin

Lesson 7

November 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.  Given the code in the following simple program, which of the following will be displayed by the program?
//File Q63.java
class Q63{
  public static void main(
                        String args[]){
    int [] refToArray = {10, 11,};
    int var = 1;
    refToArray[var-1] = var = 2;
    System.out.println(refToArray[0] +
                  " " + refToArray[1]);
  }//end main()
}//end class Q63

Answer and Explanation
 

2.  What output is produced by the following program?

//File Q64.java
class Q64{
  public static void main(
                        String args[]){
    int var1 = 10;
    int var2 = 20;
    System.out.println(
           var1 + var2++ + " " + var2);
  }//end main()
}//end class Q64

Answer and Explanation

3.  What output is produced by the following program?

//File Q65.java
class Q65{
   public static void main(
                        String args[]){
     int x = 1;
     int y = ~x + 1;
     System.out.println(x + " " + y);
   }//end main()
 }//end class definition

Answer and Explanation

4.   What output is produced by the following program?

//File Q66.java
class Q66{
  public static void main(
                        String args[]){
    if(!(3 < 4))
      System.out.println("true");
    else
      System.out.println("false");
  }//end main()
}//end class definition

Answer and Explanation

5.    What output is produced by the following program?

//File Q67.java
class Q67{
  public static void main(
                        String args[]){
    byte x;
    short y = 128;
    x = (byte)y;
    System.out.println(x + " " + y);
  }//end main()
}//end class definition

Answer and Explanation

6.  What output is produced by the following program?

//File Q68.java
class Q68{
  public static void main(
                        String args[]){
    byte x;
    short y = 128;
    x = y;
    System.out.println(x + " " + y);
  }//end main()
}//end class definition

Answer and Explanation

7.  What output is produced by the following program?

//File Q69.java
class Q69{
  public static void main(
                        String args[]){
    char x = 65;
    char y;
    y = (char)(2*x);
    System.out.println(y);
  }//end main()
}//end class definition

Answer and Explanation

8.  What output is produced by the following program?

//File Q70.java
class Q70{
  public static void main(
                        String args[]){
      System.out.println(3/0);
  }//end main()
}//end class definition

Answer and Explanation

9.  What output is produced by the following program?

//File Q71.java
class Q71{
  public static void main(
                        String args[]){
      System.out.println(3.0/0);
  }//end main()
}//end class definition

Answer and Explanation

10.  What output is produced by the following program?

//File Q72.java
class Q72{
  public static void main(
                        String args[]){
    byte x = -65;
    byte y = 2;
    byte z = (byte)(x * y);
    System.out.println(z);
  }//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

D.  None of the above

Back to Question 10

Explanation 10

The most negative value that can be stored in a byte type is -128.  (The range of the byte type is from -128 on the negative side to 127 on the positive side.)

The product of x and y is -130.  However, when an attempt is made to store this value in the byte variable named z, the binary value overflows the number of bits available, giving the incorrect value of 126.

Answer 9

D.  Infinity

Back to Question 9

Explanation 9

To begin with, this program performs arithmetic on mixed types.  An attempt is made to divide a double with a value of 3.0 by an int with a value of 0.

The int is promoted to a double and floating-point arithmetic is performed.

Floating divide by zero does not throw an exception.  Rather, the result of floating divide by zero, when displayed by the println() method is "infinity".

Answer 8

C.  java.lang.ArithmeticException: / by zero

Back to Question 8

Explanation 8

Integer divide by zero in Java results in an ArithmeticException being thrown.  This program attempts to divide 3 by zero.

Answer 7

D.  ? (symbol for non-printable character)

Back to Question 7

Explanation 7

Multiplication of char types is allowed in Java, so an error is not produced.  Note, however, that the multiplication of a char does not result in a char type.  (It results in an int.)  An explicit cast is required to store the result of the multiplication in a variable of type char.

The multiplication produces a value of 130.

Because the result of the multiplication is cast to a char and stored in a char variable, the println() method attempts to display it as the character represented by the value 130 instead of the actual value 130.  As a result, it displays a question mark.  (Apparently the question mark is displayed when println() is unable to resolve to a printable character for values above 127.)

Answer 6

A.  A compiler error

Back to Question 6

Explanation 6

Without a specific cast from short to byte being provided by the programmer, the compiler is unwilling to assign a short value to a byte variable because of the possibility of problems in the conversion.

In JDK 1.3, the compiler error reads partially as follows:

Q68.java:9: possible loss of precision

In this case, I would say that the potential problem is more serious than simply a loss of precision.  As shown in the previous problem, the data value is totally corrupted, being converted from +128 to -128.

Answer 5

D.  -128 128

Back to Question 5

Explanation 5

One of the more complex areas of beginning Java programming has to do with type conversions and type casting.  Certain conversions can take place automatically from one type to another.  For primitives, the automatic conversions are allowed in the direction that is known as a widening conversion.  Conversions in this direction are relatively safe, although problems can occur when converting from int to float, and from long to double.

It is also possible to force a type conversion in the other direction by using a cast operator, which has the syntax (newTypeName).

When you use a cast operator, you are telling the compiler that you know that the conversion is dangerous, but you are willing to accept responsibility for any problems that may result.

In this program, a short with a value of 128 is cast to a byte.  The byte type cannot accommodate positive values larger than 127.  Therefore, a problem results.

The resulting byte contains only the lower eight significant bits of the original short.  For a positive value of 128, the bit pattern in the short is:

0000000010000000

Only the eight least-significant shown in boldface are preserved in the cast from the short to the byte.  In twos-complement notation, this eight-bit pattern represents -128.  This results in the value of x being -128 instead of positive 128.

Answer 4

D.  false

Back to Question 4

Explanation 4

This program applies the complement operator (!) to a boolean value in the following expression:

if(!(3 < 4))

The behavior of the complement operator is to change the boolean value of its right operand.  True is changed to false and false is changed to true.

In this case, the expression (3 < 4) returns true.  Application of the complement operator changes this result to false.  Thus, the conditional expression in the if statement returns false causing the program to display the string "false".

Answer 3

C.  1 -1

Back to Question 3

Explanation 3

This program applies the bit-inversion operator (~) to the integer value 1 (stored in the variable named x).  The bit-inversion operator changes all the zero-valued bits to one and changes all the bits with a value of one to zero.

Java uses the twos-complement notation for integers.  Ignoring all but the four least-significant bits, the bit pattern for the positive value 1 is:

0001

Applying the bit-inversion operator changes this to the following bit pattern:

1110

This bit pattern represents the value -2 in twos-complement notation.

After inverting the bits of the variable x (but not storing the result back in x), the program adds 1 to the modified value and assigns the result to y.  The result of the inversion and addition causes the variable named y to contain the value -1 and the variable named x to contain the original value of 1.

Answer 2

B.  30 21

Back to Question 2

Explanation 2

This program makes use of the postfix version of the auto-increment operator in the following expression:

var1 + var2++ + " " + var2

This operator, indicated by a pair of plus signs with nothing in between, causes the value of its operand to be increased (incremented) by one.  The operator can be used in the postfix format as shown above, or in a prefix version that would look like the following:

var1 + ++var2 + " " + var2

The value of the operand will always be increased by one.  The issue has to do with when the increment operation takes place.  This can make a difference if the operator is applied to an operand inside of a larger overall expression as is the case here.

If the plus signs appear before the operand (prefix), the operand will be incremented before it is used to evaluate the larger overall expression.  If the plus signs follow the operand, the operand will first be used to evaluate the larger overall expression, and then it will be incremented.

This program uses the postfix version.  Therefore, the value of var2 is added to var1 before it is incremented.

Answer 1

C.  2 11

Back to Question 1

Explanation 1

To begin with, this is a coding style that you might do well to avoid due to the potential for improperly interpreting what will happen.  The issue here is whether the value of var is modified before or after it is used to calculate the array index in the expression refToArray[var-1].  If it is modified first, then the calculated index value will be 2-1 or 1 and the new value will be stored in the array element at index 1.  If it is used to calculate the index before it is modified, then the calculated index value will be 1-1 or 0 and the new value will be stored in the array element at index 0.

According to The Complete Java 2 Certification Study Guide by Roberts, Heller, and Ernest, "all operands are evaluated left to right, even if the order of execution of the operations is something different."

In this case, this means that the value of var is used to calculate the index before its value is modified, resulting in a calculated index value of 0.  This causes the value 2 to be stored in the array element at index value 0.  The value in the array element at index value 1 is not modified.  Thus, the output is 2 11.



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-