Owl Sams Teach Yourself Java 2 in 21 Days Professional Reference Edition

Day 4: Object Lessons


  • None



  • Q: The length() and charAt() methods in Listing 4.3 don't appear to make sense. If length() says that a string is 48 characters long, shouldn't the characters be numbered from 1 to 48 when charAt() is used to display characters in the string?
    A: The two methods look at strings a little differently. The length() method counts the characters in the string, with the first character counting as 1, the second as 2, and so on. The string Charlie Brown has 13 characters. The charAt() method considers the first character in the string to be located at position number 0. This is the same numbering system used with array elements in Java. The string Charlie Brown has characters ranging from position 0 -- the letter "C" -- to position 12 -- the letter "n".
  • Q: I've got the following question about the line found in Day 4; Page 103:  "The exception is casting integers to floating point values -- casting an int or a long to a float, or a long to a double can cause some loss of precision."
    How can an integer lose precision when it doesn't have it to begin with (in other words, it's not a real number)? -- P. R.
    The loss of precision occurs because integer types can hold more whole numbers than floating-point types. For this reason, you run into a loss of precision when casting very large int and long values to float and very large long values to double.
         Both int and float are 32-bit values in Java. The int primitive data type can represent 2.14 trillion different whole numbers, but float can only represent around 16.78 million whole numbers, because it also has to represent other values. When you cast an int value higher than 16,777,216 to a float, because of how Java applies the rules of floating-point arithmetic, the int value will be converted to the closest whole number that float can represent.
         To see this in action, write an application with the following code:

    int i = 2000000000;
    float one = i;
    float two = i + 5;
    if (one == two)
        System.out.println("Numbers are equal.");
        System.out.println("Numbers are not equal.");

         This will display the string "Numbers are equal." If you change the first line to int i = 16777216, the code will display the string "Numbers are not equal."