I do not undrestand something,I'm a beginner

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thatos
    New Member
    • Aug 2007
    • 105

    I do not undrestand something,I'm a beginner

    I was told and read that in java for a byte can represent values from -128 to 127 but when I write byte x = 2.5; it gives me an error can a byte only represent integers from -128 to 127 not number between the integers?
    One more question why can't I say float x = 2.5; It gives me an error it wants me to say double x = 2,5;
    doesn't float represent every decimal number?
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by thatos
    I was told and read that in java for a byte can represent values from -128 to 127 but when I write byte x = 2.5; it gives me an error can a byte only represent integers from -128 to 127 not number between the integers?
    One more question why can't I say float x = 2.5; It gives me an error it wants me to say double x = 2,5;
    doesn't float represent every decimal number?
    The person who told you that a "byte can represent values from -128 to 127" forgot to mention that those values must be integers.
    All decimal numbers are treated as type double by default.
    To make it a float, you need to put an f at the end float x = 2.5f.
    More details are in the Sun's tutorial

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      Originally posted by thatos
      I was told and read that in java for a byte can represent values from -128 to 127 but when I write byte x = 2.5; it gives me an error can a byte only represent integers from -128 to 127 not number between the integers?
      One more question why can't I say float x = 2.5; It gives me an error it wants me to say double x = 2,5;
      doesn't float represent every decimal number?
      Yep, bytes are small integers in the range you mentioned; floats can store fractions
      and double types can do that as well; when you type 2.5 it is assumed to be of
      type double. Doubles can store more fraction digits than floats can and the
      compiler is afraid that you'll lose precision (the rightmost fractional digits) and
      starts whining about it; append your number with an 'f' like this: 2.5f. This tells
      the compiler that you explicitly mean a float number, not a double number.

      kind regards,

      Jos

      Comment

      Working...