Results 1 to 2 of 2
  1. #1
    naxalyte is offline Member
    Join Date
    Nov 2007
    Posts
    4
    Rep Power
    0

    Default What does this line of code mean?

    Could someone please explain why in the following line of code, int is used within brackets after the equals sign?

    Java Code:
    int x = (int)((width/2) + (0.5-Math.random())*width);

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

    Default

    ((width/2) + (0.5-Math.random())*width)
    Math.random returns a double — we know this is true because we can look up the method in the Math class api and see the return type specified in the first column of the table in the Methods Summary section.
    So the expression
    (0.5-Math.random())*width)
    will evaluate to a double.
    For precision the (width/2) term, which may be an int, is grouped into the same expression and the whole thing is cast to an int.
    int x = the value over here must be an int so we cast the double expression to the lesser–precision int primitive data type. Going from higher to lower precision requires an explicit cast.

Similar Threads

  1. I need help fixing my code.. or non code?
    By MrHuggykins in forum New To Java
    Replies: 1
    Last Post: 03-19-2008, 10:12 PM
  2. java in cmd line :(
    By Joe2003 in forum New To Java
    Replies: 2
    Last Post: 02-01-2008, 08:51 AM
  3. line feed in CSV
    By javaplus in forum New To Java
    Replies: 2
    Last Post: 01-24-2008, 03:46 PM
  4. Reading in data from file line by line
    By bluekswing in forum New To Java
    Replies: 1
    Last Post: 10-02-2007, 12:19 AM
  5. Replies: 1
    Last Post: 04-26-2007, 03:52 PM

Posting Permissions

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