Results 1 to 2 of 2
  1. #1
    baltimore is offline Member
    Join Date
    Jul 2007
    Posts
    40
    Rep Power
    0

    Default Help with valid declarations of a float

    Hi, Ok please can someone explain if the value 3.14 is a double or a float...I am looking at this Java Sun Certification book and it says that 3.14 is a float and not a double.

    The question is as follows:
    Which 3 are valid declarations of a float? (Choose 3)
    • A. float f1 = -343;
    • B. float f2 = 3.14;
    • C. float f3 = 0x12345;
    • D. float f4 = 42e7;
    • E. float f5 = 2001.0D;
    • F. float f6 - 2.81F;

    I chose the answers to be A, B and F. The book says A, C and F. Can someone explain this to me? I mean I am leaning towards the I am wrong but the book is right kind of deals but something tells me I am right and the book wrong.
    Thanks.

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    If a number has a decimal it is a double. To make such a number a float you can do
    Java Code:
    float f = (float)3.14;  // cast
    // or
    float c = 3.14f;  // or 3.14F
    And any number of lesser precision can be assigned to a reference of higher precision.
    Java Code:
    float f = 25;
    double d = 15f;
    long b = 88;  // int
    To see what java says:
    Java Code:
    class FloatTest {
        public static void main(String[] args) {
            check(-343);
            check(3.14);
            check(0x12345);
            check(42e7);
            check(2001.0D);
            check(2.81F);
        }
    
        private static void check(Number n) {
            System.out.println(n + " = " + n.getClass().getName());
        }
    }

Similar Threads

  1. Replies: 3
    Last Post: 07-25-2011, 03:19 PM
  2. Replies: 2
    Last Post: 01-21-2008, 08:15 AM
  3. Float to String
    By mew in forum New To Java
    Replies: 4
    Last Post: 12-29-2007, 05:08 PM
  4. Valid declarations
    By heat84 in forum New To Java
    Replies: 1
    Last Post: 12-22-2007, 02:29 AM
  5. MySite/Valid.java:56: cannot resolve symbol
    By Albert in forum Enterprise JavaBeans (EJB)
    Replies: 1
    Last Post: 07-05-2007, 05:49 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •