December 20, 2014
Hot Topics:

Test Your Java Knowledge: Using Operators and Making Assignments, Part 2

  • December 8, 2000
  • By Richard G. Baldwin
  • Send Email »
  • More Articles »

Questions

By Richard G. Baldwin

Lesson 8


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 output is produced by the following program?
  • A.  -11 10
  • B.  -11 11
  • C.  -10 10
  • D.  -10 11
class Q73{
  public static void main(
                        String args[]){
    int x;
    double y = -10.9;
    x = (int)y;
    System.out.print(x + " ");
    y = 10.9;
    x = (int)y;
    System.out.println(x);
  }//end main()
}//end class definition

Answer and Explanation

2.  What output is produced by the following program?

  • A.  A compiler error
  • B.  A runtime error
  • C.  10 4
  • D.  10 -4
class Q74{
  public static void main(
                        String args[]){
    byte x = -64;
    byte y = -6;
    System.out.println(
                      x/y + " " + x%y);
  }//end main()
}//end class definition

Answer and Explanation

3.  What output is produced by the following program?

  • A.  A compiler error
  • B.  A runtime error
  • C.  10.75 4.5
  • D.  10.75 0
class Q75{
  public static void main(
                        String args[]){
    double x = 64.5;
    double y = 6.0;
    System.out.println(
                      x/y + " " + x%y);
  }//end main()
}//end class definition

Answer and Explanation

4.  What output is produced by the following program?

  • A.  A compiler error
  • B.  Exception
  • C.  Infinity
  • D.  NaN
class Q76{
  public static void main(
                        String args[]){
    try{
      double x = 64.0;
      double y = 0.0;
      System.out.println(x%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?

  • A.  A compiler error
  • B.  Exception
  • C.  Infinity
  • D.  NaN
class Q78{
  public static void main(
                        String args[]){
    try{
      int x = 64;
      int y = 0;
      System.out.println(x%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?

  • A.  A compiler error
  • B.  Exception
  • C.  128
  • D.  -128
class Q79{
  public static void main(
                        String args[]){
    try{
      byte x = 64;
      byte y = 64;
      byte z = (byte)(x + y);
      System.out.println(z);
    }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?

  • A.  A compiler error
  • B.  Exception
  • C.  128
  • D.  -128
class Q80{
  public static void main(
                        String args[]){
    try{
      byte x = 64;
      byte y = 64;
      System.out.println(x + 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?

  • A.  false false
  • B.  false true
  • C.  true false
  • D.  true true
class Q81{
  public static void main(
                        String args[]){
    System.out.print(
                  Double.isNaN(3.0%0));
    System.out.print(" ");
    System.out.println(
                  Double.isNaN(3.0/0));
  }//end main()
}//end class definition

Answer and Explanation
 

9.  What output is produced by the following program?

  • A.  A compiler error
  • B.  Exception
  • C.  true
  • D.  false
class Q82{
  public static void main(
                        String args[]){
    try{
      double x = 64.0;
      double y = 0.0;
      System.out.println(x%y == x%y);
    }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?

  • A.  A compiler error
  • B.  Exception
  • C.  true true
  • D.  false true
  • E.  false false
class Q83{
  public static void main(
                        String args[]){
    try{
      System.out.print(
               Float.NaN == Float.NaN);
      System.out.println(" " +
           (Float.POSITIVE_INFINITY ==
             Float.POSITIVE_INFINITY));
    }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

D.  false true

Back to Question 10

Explanation 10

This program pushes the NaN issue illustrated in a previous question one step further.

In particular, this program illustrates that even if you compare the NaN constant found in the Float class to itself, the comparison will indicate that the two values are not equal.

This is decidedly unusual behavior.  Normally, if you compare a properly initialized public static final variable to itself, you would expect the comparison to indicate that the two are equal.  This is illustrated by the fact that when the program compares the POSITIVE_INFINITY constant found in the Float class to itself, the comparison indicates that the two values are equal.

So, you need to remember that NaN exhibits strange behavior, which may not be what you would expect.

Answer 9

D.  false

Back to Question 9

Explanation 9

The modulo operation with zero as the right operand produces NaN.  However, according to Roberts, if you compare NaN with any other value, including the same NaN, the comparison will return false.  This applies to all of the comparison operators, not just the == operator used in this program.

Answer 8

C.  true false

Back to Question 8

Explanation 8

In a different question, I illustrated that the constant whose name is Double.NaN cannot be used (reliably) with a simple equivalence test (==) to determine if a value is equal to NaN.

However, the Double and Float classes provide a method named isNaN() that can be used for this purpose.  This program uses that method to evaluate the result of floating-point modulo by zero and floating-point division by zero.

Floating-point modulo by zero produces NaN causing the method to return true.

Floating-point divide by zero does not produce NaN.  Therefore, the method returns false.

Answer 7

C.  128

Back to Question 7

Explanation 7

If this arithmetic had been performed using an eight-bit byte type for storage of the result, arithmetic overflow would result.

However, according to Roberts, the result of arithmetic addition will produce a result that is always at least as wide an an int.

Therefore, even though the operands are of type byte, the result of the addition is of type int. No integer overflow occurs because the result is not cast back to a byte.  It is simply printed while it is still type int.

Answer 6

D.  -128

Back to Question 6

Explanation 6

According to Roberts, the result of arithmetic addition will always produce a result that is at least as wide an int.

In this program, the sum of the byte types x and y is performed producing a result of type int.  The value of the result is 128.

However, the largest positive value that can be stored in a byte type is 127.  Casting the sum back to a byte type produces integer overflow, resulting in a nonsense result of -128.

When you use a cast operator, you are telling the compiler that you are aware that problems may result, but you are assuming responsibility for those problems.  In this case, the problem is very significant.

Answer 5

B.  Exception

Back to Question 5

Explanation 5

Because the modulus operator involves division and integer division by zero throws an exception, integer modulo by zero also throws an exception.

Note however that floating-point division by zero doesn't throw an exception.  Therefore, floating-point modulo by zero also doesn't throw an exception.  Rather, it returns NaN as illustrated in an earlier question.
 

Answer 4

D.  NaN

Back to Question 4

Explanation 4

NaN stands for Not-a-Number.  The primary message conveyed here is that the result is not a valid floating-point value.

Quite a lot of detailed information regarding NaN is provided in the Sun documentation, but unless you are interested in the bit patterns used for floating point types, most of that information won't be of much interest to you.

You should note, however, that both the Float and Double classes provide a constant for NaN.  This would lead you to believe that the constant can be used in your code to test for NaN.  However, there are many bit patterns that qualify as NNaN and the constants provided in the Float and Double classes are only two of them.

For example, the following program displays NaN Oops indicating that even though the println() method regards the value of z as NaN, the test for NaN in the if statement was not successful in identifying the value of z as NaN.
 

class Q77{
  public static void main(
                        String args[]){
    double x = 64.0;
    double y = 0.0;
    double z = x%y;
    System.out.print(z + " ");
    if(z == Double.NaN)
      System.out.println(
                       "Not-a-Number");
    else
      System.out.println("Oops");

  }//end main()
}//end class definition

If Double.NaN can be used to test for NaN, then some code structure other than that used in this program is required.  Perhaps the value Double.NaN is provided to allow you to set a value to NaN rather than to test to see if a value is equal to NaN.

Answer 3

C.  10.75 4.5

Back to Question 3

Explanation 3

According to The Complete Java 2 Certification Study Guide, by Roberts, Heller, and Ernest,  "When the modulo operator is applied to floating point types, the effect is to perform an integral number of subtractions, leaving a floating point result that might well have  a fractional part."

Thus, the result of the modulo operation is the remainder that results after subtracting the right operand from the left operand an integral number of times.  In this case, the right operand was subtracted from the left operand ten times, leaving a remainder of 4.5.  Apparently the subtraction process continues until the remainder is less than the right operand.

Note, however, that because of arithmetic inaccuracy, this process can produce strange results.  For example, if the value of the variable y is changed to 6.45 in this program, the output from the program is the following:

10.0 6.449999999999998

In this case, it appears that nine subtractions were performed leaving a remainder that was smaller than the right operand by a very tiny amount.  Ideally, the remainder should have been zero.  Therefore, extreme care should be taken when making use of the modulus operator with floating point types.

Answer 2

D.  10 -4

Back to Question 2

Explanation 2

The result of the modulus operator takes the sign of the left operand, regardless of the sign of the quotient and regardless of the sign of the right operand.

Answer 1

C.  -10 10

Back to Question 1

Explanation 1

Casting the double to the int truncates the double value to the next lower integer value (in an absolute sense, and not in an algebraic sense), which is -10 or 10 in this case.  (If the truncation were performed in an algebraic sense, -10.9 would be truncated to -11 instead of -10.)



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






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel