1 /* 2 * Copyright (c) 1994, 2020, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang; 27 28 import java.lang.invoke.MethodHandles; 29 import java.lang.constant.Constable; 30 import java.lang.constant.ConstantDesc; 31 import java.util.Optional; 32 33 import jdk.internal.math.FloatingDecimal; 34 import jdk.internal.HotSpotIntrinsicCandidate; 35 36 /** 37 * The {@code Float} class wraps a value of primitive type 38 * {@code float} in an object. An object of type 39 * {@code Float} contains a single field whose type is 40 * {@code float}. 41 * 42 * <p>In addition, this class provides several methods for converting a 43 * {@code float} to a {@code String} and a 44 * {@code String} to a {@code float}, as well as other 45 * constants and methods useful when dealing with a 46 * {@code float}. 47 * 48 * @author Lee Boynton 49 * @author Arthur van Hoff 50 * @author Joseph D. Darcy 51 * @since 1.0 52 */ 53 public final class Float extends Number 54 implements Comparable<Float>, Constable, ConstantDesc { 55 /** 56 * A constant holding the positive infinity of type 57 * {@code float}. It is equal to the value returned by 58 * {@code Float.intBitsToFloat(0x7f800000)}. 59 */ 60 public static final float POSITIVE_INFINITY = 1.0f / 0.0f; 61 62 /** 63 * A constant holding the negative infinity of type 64 * {@code float}. It is equal to the value returned by 65 * {@code Float.intBitsToFloat(0xff800000)}. 66 */ 67 public static final float NEGATIVE_INFINITY = -1.0f / 0.0f; 68 69 /** 70 * A constant holding a Not-a-Number (NaN) value of type 71 * {@code float}. It is equivalent to the value returned by 72 * {@code Float.intBitsToFloat(0x7fc00000)}. 73 */ 74 public static final float NaN = 0.0f / 0.0f; 75 76 /** 77 * A constant holding the largest positive finite value of type 78 * {@code float}, (2-2<sup>-23</sup>)·2<sup>127</sup>. 79 * It is equal to the hexadecimal floating-point literal 80 * {@code 0x1.fffffeP+127f} and also equal to 81 * {@code Float.intBitsToFloat(0x7f7fffff)}. 82 */ 83 public static final float MAX_VALUE = 0x1.fffffeP+127f; // 3.4028235e+38f 84 85 /** 86 * A constant holding the smallest positive normal value of type 87 * {@code float}, 2<sup>-126</sup>. It is equal to the 88 * hexadecimal floating-point literal {@code 0x1.0p-126f} and also 89 * equal to {@code Float.intBitsToFloat(0x00800000)}. 90 * 91 * @since 1.6 92 */ 93 public static final float MIN_NORMAL = 0x1.0p-126f; // 1.17549435E-38f 94 95 /** 96 * A constant holding the smallest positive nonzero value of type 97 * {@code float}, 2<sup>-149</sup>. It is equal to the 98 * hexadecimal floating-point literal {@code 0x0.000002P-126f} 99 * and also equal to {@code Float.intBitsToFloat(0x1)}. 100 */ 101 public static final float MIN_VALUE = 0x0.000002P-126f; // 1.4e-45f 102 103 /** 104 * Maximum exponent a finite {@code float} variable may have. It 105 * is equal to the value returned by {@code 106 * Math.getExponent(Float.MAX_VALUE)}. 107 * 108 * @since 1.6 109 */ 110 public static final int MAX_EXPONENT = 127; 111 112 /** 113 * Minimum exponent a normalized {@code float} variable may have. 114 * It is equal to the value returned by {@code 115 * Math.getExponent(Float.MIN_NORMAL)}. 116 * 117 * @since 1.6 118 */ 119 public static final int MIN_EXPONENT = -126; 120 121 /** 122 * The number of bits used to represent a {@code float} value. 123 * 124 * @since 1.5 125 */ 126 public static final int SIZE = 32; 127 128 /** 129 * The number of bytes used to represent a {@code float} value. 130 * 131 * @since 1.8 132 */ 133 public static final int BYTES = SIZE / Byte.SIZE; 134 135 /** 136 * The {@code Class} instance representing the primitive type 137 * {@code float}. 138 * 139 * @since 1.1 140 */ 141 @SuppressWarnings("unchecked") 142 public static final Class<Float> TYPE = (Class<Float>) Class.getPrimitiveClass("float"); 143 144 /** 145 * Returns a string representation of the {@code float} 146 * argument. All characters mentioned below are ASCII characters. 147 * <ul> 148 * <li>If the argument is NaN, the result is the string 149 * "{@code NaN}". 150 * <li>Otherwise, the result is a string that represents the sign and 151 * magnitude (absolute value) of the argument. If the sign is 152 * negative, the first character of the result is 153 * '{@code -}' ({@code '\u005Cu002D'}); if the sign is 154 * positive, no sign character appears in the result. As for 155 * the magnitude <i>m</i>: 156 * <ul> 157 * <li>If <i>m</i> is infinity, it is represented by the characters 158 * {@code "Infinity"}; thus, positive infinity produces 159 * the result {@code "Infinity"} and negative infinity 160 * produces the result {@code "-Infinity"}. 161 * <li>If <i>m</i> is zero, it is represented by the characters 162 * {@code "0.0"}; thus, negative zero produces the result 163 * {@code "-0.0"} and positive zero produces the result 164 * {@code "0.0"}. 165 * <li> If <i>m</i> is greater than or equal to 10<sup>-3</sup> but 166 * less than 10<sup>7</sup>, then it is represented as the 167 * integer part of <i>m</i>, in decimal form with no leading 168 * zeroes, followed by '{@code .}' 169 * ({@code '\u005Cu002E'}), followed by one or more 170 * decimal digits representing the fractional part of 171 * <i>m</i>. 172 * <li> If <i>m</i> is less than 10<sup>-3</sup> or greater than or 173 * equal to 10<sup>7</sup>, then it is represented in 174 * so-called "computerized scientific notation." Let <i>n</i> 175 * be the unique integer such that 10<sup><i>n</i> </sup>≤ 176 * <i>m</i> {@literal <} 10<sup><i>n</i>+1</sup>; then let <i>a</i> 177 * be the mathematically exact quotient of <i>m</i> and 178 * 10<sup><i>n</i></sup> so that 1 ≤ <i>a</i> {@literal <} 10. 179 * The magnitude is then represented as the integer part of 180 * <i>a</i>, as a single decimal digit, followed by 181 * '{@code .}' ({@code '\u005Cu002E'}), followed by 182 * decimal digits representing the fractional part of 183 * <i>a</i>, followed by the letter '{@code E}' 184 * ({@code '\u005Cu0045'}), followed by a representation 185 * of <i>n</i> as a decimal integer, as produced by the 186 * method {@link java.lang.Integer#toString(int)}. 187 * 188 * </ul> 189 * </ul> 190 * How many digits must be printed for the fractional part of 191 * <i>m</i> or <i>a</i>? There must be at least one digit 192 * to represent the fractional part, and beyond that as many, but 193 * only as many, more digits as are needed to uniquely distinguish 194 * the argument value from adjacent values of type 195 * {@code float}. That is, suppose that <i>x</i> is the 196 * exact mathematical value represented by the decimal 197 * representation produced by this method for a finite nonzero 198 * argument <i>f</i>. Then <i>f</i> must be the {@code float} 199 * value nearest to <i>x</i>; or, if two {@code float} values are 200 * equally close to <i>x</i>, then <i>f</i> must be one of 201 * them and the least significant bit of the significand of 202 * <i>f</i> must be {@code 0}. 203 * 204 * <p>To create localized string representations of a floating-point 205 * value, use subclasses of {@link java.text.NumberFormat}. 206 * 207 * @param f the float to be converted. 208 * @return a string representation of the argument. 209 */ toString(float f)210 public static String toString(float f) { 211 return FloatingDecimal.toJavaFormatString(f); 212 } 213 214 /** 215 * Returns a hexadecimal string representation of the 216 * {@code float} argument. All characters mentioned below are 217 * ASCII characters. 218 * 219 * <ul> 220 * <li>If the argument is NaN, the result is the string 221 * "{@code NaN}". 222 * <li>Otherwise, the result is a string that represents the sign and 223 * magnitude (absolute value) of the argument. If the sign is negative, 224 * the first character of the result is '{@code -}' 225 * ({@code '\u005Cu002D'}); if the sign is positive, no sign character 226 * appears in the result. As for the magnitude <i>m</i>: 227 * 228 * <ul> 229 * <li>If <i>m</i> is infinity, it is represented by the string 230 * {@code "Infinity"}; thus, positive infinity produces the 231 * result {@code "Infinity"} and negative infinity produces 232 * the result {@code "-Infinity"}. 233 * 234 * <li>If <i>m</i> is zero, it is represented by the string 235 * {@code "0x0.0p0"}; thus, negative zero produces the result 236 * {@code "-0x0.0p0"} and positive zero produces the result 237 * {@code "0x0.0p0"}. 238 * 239 * <li>If <i>m</i> is a {@code float} value with a 240 * normalized representation, substrings are used to represent the 241 * significand and exponent fields. The significand is 242 * represented by the characters {@code "0x1."} 243 * followed by a lowercase hexadecimal representation of the rest 244 * of the significand as a fraction. Trailing zeros in the 245 * hexadecimal representation are removed unless all the digits 246 * are zero, in which case a single zero is used. Next, the 247 * exponent is represented by {@code "p"} followed 248 * by a decimal string of the unbiased exponent as if produced by 249 * a call to {@link Integer#toString(int) Integer.toString} on the 250 * exponent value. 251 * 252 * <li>If <i>m</i> is a {@code float} value with a subnormal 253 * representation, the significand is represented by the 254 * characters {@code "0x0."} followed by a 255 * hexadecimal representation of the rest of the significand as a 256 * fraction. Trailing zeros in the hexadecimal representation are 257 * removed. Next, the exponent is represented by 258 * {@code "p-126"}. Note that there must be at 259 * least one nonzero digit in a subnormal significand. 260 * 261 * </ul> 262 * 263 * </ul> 264 * 265 * <table class="striped"> 266 * <caption>Examples</caption> 267 * <thead> 268 * <tr><th scope="col">Floating-point Value</th><th scope="col">Hexadecimal String</th> 269 * </thead> 270 * <tbody> 271 * <tr><th scope="row">{@code 1.0}</th> <td>{@code 0x1.0p0}</td> 272 * <tr><th scope="row">{@code -1.0}</th> <td>{@code -0x1.0p0}</td> 273 * <tr><th scope="row">{@code 2.0}</th> <td>{@code 0x1.0p1}</td> 274 * <tr><th scope="row">{@code 3.0}</th> <td>{@code 0x1.8p1}</td> 275 * <tr><th scope="row">{@code 0.5}</th> <td>{@code 0x1.0p-1}</td> 276 * <tr><th scope="row">{@code 0.25}</th> <td>{@code 0x1.0p-2}</td> 277 * <tr><th scope="row">{@code Float.MAX_VALUE}</th> 278 * <td>{@code 0x1.fffffep127}</td> 279 * <tr><th scope="row">{@code Minimum Normal Value}</th> 280 * <td>{@code 0x1.0p-126}</td> 281 * <tr><th scope="row">{@code Maximum Subnormal Value}</th> 282 * <td>{@code 0x0.fffffep-126}</td> 283 * <tr><th scope="row">{@code Float.MIN_VALUE}</th> 284 * <td>{@code 0x0.000002p-126}</td> 285 * </tbody> 286 * </table> 287 * @param f the {@code float} to be converted. 288 * @return a hex string representation of the argument. 289 * @since 1.5 290 * @author Joseph D. Darcy 291 */ toHexString(float f)292 public static String toHexString(float f) { 293 if (Math.abs(f) < Float.MIN_NORMAL 294 && f != 0.0f ) {// float subnormal 295 // Adjust exponent to create subnormal double, then 296 // replace subnormal double exponent with subnormal float 297 // exponent 298 String s = Double.toHexString(Math.scalb((double)f, 299 /* -1022+126 */ 300 Double.MIN_EXPONENT- 301 Float.MIN_EXPONENT)); 302 return s.replaceFirst("p-1022$", "p-126"); 303 } 304 else // double string will be the same as float string 305 return Double.toHexString(f); 306 } 307 308 /** 309 * Returns a {@code Float} object holding the 310 * {@code float} value represented by the argument string 311 * {@code s}. 312 * 313 * <p>If {@code s} is {@code null}, then a 314 * {@code NullPointerException} is thrown. 315 * 316 * <p>Leading and trailing whitespace characters in {@code s} 317 * are ignored. Whitespace is removed as if by the {@link 318 * String#trim} method; that is, both ASCII space and control 319 * characters are removed. The rest of {@code s} should 320 * constitute a <i>FloatValue</i> as described by the lexical 321 * syntax rules: 322 * 323 * <blockquote> 324 * <dl> 325 * <dt><i>FloatValue:</i> 326 * <dd><i>Sign<sub>opt</sub></i> {@code NaN} 327 * <dd><i>Sign<sub>opt</sub></i> {@code Infinity} 328 * <dd><i>Sign<sub>opt</sub> FloatingPointLiteral</i> 329 * <dd><i>Sign<sub>opt</sub> HexFloatingPointLiteral</i> 330 * <dd><i>SignedInteger</i> 331 * </dl> 332 * 333 * <dl> 334 * <dt><i>HexFloatingPointLiteral</i>: 335 * <dd> <i>HexSignificand BinaryExponent FloatTypeSuffix<sub>opt</sub></i> 336 * </dl> 337 * 338 * <dl> 339 * <dt><i>HexSignificand:</i> 340 * <dd><i>HexNumeral</i> 341 * <dd><i>HexNumeral</i> {@code .} 342 * <dd>{@code 0x} <i>HexDigits<sub>opt</sub> 343 * </i>{@code .}<i> HexDigits</i> 344 * <dd>{@code 0X}<i> HexDigits<sub>opt</sub> 345 * </i>{@code .} <i>HexDigits</i> 346 * </dl> 347 * 348 * <dl> 349 * <dt><i>BinaryExponent:</i> 350 * <dd><i>BinaryExponentIndicator SignedInteger</i> 351 * </dl> 352 * 353 * <dl> 354 * <dt><i>BinaryExponentIndicator:</i> 355 * <dd>{@code p} 356 * <dd>{@code P} 357 * </dl> 358 * 359 * </blockquote> 360 * 361 * where <i>Sign</i>, <i>FloatingPointLiteral</i>, 362 * <i>HexNumeral</i>, <i>HexDigits</i>, <i>SignedInteger</i> and 363 * <i>FloatTypeSuffix</i> are as defined in the lexical structure 364 * sections of 365 * <cite>The Java Language Specification</cite>, 366 * except that underscores are not accepted between digits. 367 * If {@code s} does not have the form of 368 * a <i>FloatValue</i>, then a {@code NumberFormatException} 369 * is thrown. Otherwise, {@code s} is regarded as 370 * representing an exact decimal value in the usual 371 * "computerized scientific notation" or as an exact 372 * hexadecimal value; this exact numerical value is then 373 * conceptually converted to an "infinitely precise" 374 * binary value that is then rounded to type {@code float} 375 * by the usual round-to-nearest rule of IEEE 754 floating-point 376 * arithmetic, which includes preserving the sign of a zero 377 * value. 378 * 379 * Note that the round-to-nearest rule also implies overflow and 380 * underflow behaviour; if the exact value of {@code s} is large 381 * enough in magnitude (greater than or equal to ({@link 382 * #MAX_VALUE} + {@link Math#ulp(float) ulp(MAX_VALUE)}/2), 383 * rounding to {@code float} will result in an infinity and if the 384 * exact value of {@code s} is small enough in magnitude (less 385 * than or equal to {@link #MIN_VALUE}/2), rounding to float will 386 * result in a zero. 387 * 388 * Finally, after rounding a {@code Float} object representing 389 * this {@code float} value is returned. 390 * 391 * <p>To interpret localized string representations of a 392 * floating-point value, use subclasses of {@link 393 * java.text.NumberFormat}. 394 * 395 * <p>Note that trailing format specifiers, specifiers that 396 * determine the type of a floating-point literal 397 * ({@code 1.0f} is a {@code float} value; 398 * {@code 1.0d} is a {@code double} value), do 399 * <em>not</em> influence the results of this method. In other 400 * words, the numerical value of the input string is converted 401 * directly to the target floating-point type. In general, the 402 * two-step sequence of conversions, string to {@code double} 403 * followed by {@code double} to {@code float}, is 404 * <em>not</em> equivalent to converting a string directly to 405 * {@code float}. For example, if first converted to an 406 * intermediate {@code double} and then to 407 * {@code float}, the string<br> 408 * {@code "1.00000017881393421514957253748434595763683319091796875001d"}<br> 409 * results in the {@code float} value 410 * {@code 1.0000002f}; if the string is converted directly to 411 * {@code float}, <code>1.000000<b>1</b>f</code> results. 412 * 413 * <p>To avoid calling this method on an invalid string and having 414 * a {@code NumberFormatException} be thrown, the documentation 415 * for {@link Double#valueOf Double.valueOf} lists a regular 416 * expression which can be used to screen the input. 417 * 418 * @param s the string to be parsed. 419 * @return a {@code Float} object holding the value 420 * represented by the {@code String} argument. 421 * @throws NumberFormatException if the string does not contain a 422 * parsable number. 423 */ valueOf(String s)424 public static Float valueOf(String s) throws NumberFormatException { 425 return new Float(parseFloat(s)); 426 } 427 428 /** 429 * Returns a {@code Float} instance representing the specified 430 * {@code float} value. 431 * If a new {@code Float} instance is not required, this method 432 * should generally be used in preference to the constructor 433 * {@link #Float(float)}, as this method is likely to yield 434 * significantly better space and time performance by caching 435 * frequently requested values. 436 * 437 * @param f a float value. 438 * @return a {@code Float} instance representing {@code f}. 439 * @since 1.5 440 */ 441 @HotSpotIntrinsicCandidate valueOf(float f)442 public static Float valueOf(float f) { 443 return new Float(f); 444 } 445 446 /** 447 * Returns a new {@code float} initialized to the value 448 * represented by the specified {@code String}, as performed 449 * by the {@code valueOf} method of class {@code Float}. 450 * 451 * @param s the string to be parsed. 452 * @return the {@code float} value represented by the string 453 * argument. 454 * @throws NullPointerException if the string is null 455 * @throws NumberFormatException if the string does not contain a 456 * parsable {@code float}. 457 * @see java.lang.Float#valueOf(String) 458 * @since 1.2 459 */ parseFloat(String s)460 public static float parseFloat(String s) throws NumberFormatException { 461 return FloatingDecimal.parseFloat(s); 462 } 463 464 /** 465 * Returns {@code true} if the specified number is a 466 * Not-a-Number (NaN) value, {@code false} otherwise. 467 * 468 * @param v the value to be tested. 469 * @return {@code true} if the argument is NaN; 470 * {@code false} otherwise. 471 */ isNaN(float v)472 public static boolean isNaN(float v) { 473 return (v != v); 474 } 475 476 /** 477 * Returns {@code true} if the specified number is infinitely 478 * large in magnitude, {@code false} otherwise. 479 * 480 * @param v the value to be tested. 481 * @return {@code true} if the argument is positive infinity or 482 * negative infinity; {@code false} otherwise. 483 */ isInfinite(float v)484 public static boolean isInfinite(float v) { 485 return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY); 486 } 487 488 489 /** 490 * Returns {@code true} if the argument is a finite floating-point 491 * value; returns {@code false} otherwise (for NaN and infinity 492 * arguments). 493 * 494 * @param f the {@code float} value to be tested 495 * @return {@code true} if the argument is a finite 496 * floating-point value, {@code false} otherwise. 497 * @since 1.8 498 */ isFinite(float f)499 public static boolean isFinite(float f) { 500 return Math.abs(f) <= Float.MAX_VALUE; 501 } 502 503 /** 504 * The value of the Float. 505 * 506 * @serial 507 */ 508 private final float value; 509 510 /** 511 * Constructs a newly allocated {@code Float} object that 512 * represents the primitive {@code float} argument. 513 * 514 * @param value the value to be represented by the {@code Float}. 515 * 516 * @deprecated 517 * It is rarely appropriate to use this constructor. The static factory 518 * {@link #valueOf(float)} is generally a better choice, as it is 519 * likely to yield significantly better space and time performance. 520 */ 521 @Deprecated(since="9") Float(float value)522 public Float(float value) { 523 this.value = value; 524 } 525 526 /** 527 * Constructs a newly allocated {@code Float} object that 528 * represents the argument converted to type {@code float}. 529 * 530 * @param value the value to be represented by the {@code Float}. 531 * 532 * @deprecated 533 * It is rarely appropriate to use this constructor. Instead, use the 534 * static factory method {@link #valueOf(float)} method as follows: 535 * {@code Float.valueOf((float)value)}. 536 */ 537 @Deprecated(since="9") Float(double value)538 public Float(double value) { 539 this.value = (float)value; 540 } 541 542 /** 543 * Constructs a newly allocated {@code Float} object that 544 * represents the floating-point value of type {@code float} 545 * represented by the string. The string is converted to a 546 * {@code float} value as if by the {@code valueOf} method. 547 * 548 * @param s a string to be converted to a {@code Float}. 549 * @throws NumberFormatException if the string does not contain a 550 * parsable number. 551 * 552 * @deprecated 553 * It is rarely appropriate to use this constructor. 554 * Use {@link #parseFloat(String)} to convert a string to a 555 * {@code float} primitive, or use {@link #valueOf(String)} 556 * to convert a string to a {@code Float} object. 557 */ 558 @Deprecated(since="9") Float(String s)559 public Float(String s) throws NumberFormatException { 560 value = parseFloat(s); 561 } 562 563 /** 564 * Returns {@code true} if this {@code Float} value is a 565 * Not-a-Number (NaN), {@code false} otherwise. 566 * 567 * @return {@code true} if the value represented by this object is 568 * NaN; {@code false} otherwise. 569 */ isNaN()570 public boolean isNaN() { 571 return isNaN(value); 572 } 573 574 /** 575 * Returns {@code true} if this {@code Float} value is 576 * infinitely large in magnitude, {@code false} otherwise. 577 * 578 * @return {@code true} if the value represented by this object is 579 * positive infinity or negative infinity; 580 * {@code false} otherwise. 581 */ isInfinite()582 public boolean isInfinite() { 583 return isInfinite(value); 584 } 585 586 /** 587 * Returns a string representation of this {@code Float} object. 588 * The primitive {@code float} value represented by this object 589 * is converted to a {@code String} exactly as if by the method 590 * {@code toString} of one argument. 591 * 592 * @return a {@code String} representation of this object. 593 * @see java.lang.Float#toString(float) 594 */ toString()595 public String toString() { 596 return Float.toString(value); 597 } 598 599 /** 600 * Returns the value of this {@code Float} as a {@code byte} after 601 * a narrowing primitive conversion. 602 * 603 * @return the {@code float} value represented by this object 604 * converted to type {@code byte} 605 * @jls 5.1.3 Narrowing Primitive Conversion 606 */ byteValue()607 public byte byteValue() { 608 return (byte)value; 609 } 610 611 /** 612 * Returns the value of this {@code Float} as a {@code short} 613 * after a narrowing primitive conversion. 614 * 615 * @return the {@code float} value represented by this object 616 * converted to type {@code short} 617 * @jls 5.1.3 Narrowing Primitive Conversion 618 * @since 1.1 619 */ shortValue()620 public short shortValue() { 621 return (short)value; 622 } 623 624 /** 625 * Returns the value of this {@code Float} as an {@code int} after 626 * a narrowing primitive conversion. 627 * 628 * @return the {@code float} value represented by this object 629 * converted to type {@code int} 630 * @jls 5.1.3 Narrowing Primitive Conversion 631 */ intValue()632 public int intValue() { 633 return (int)value; 634 } 635 636 /** 637 * Returns value of this {@code Float} as a {@code long} after a 638 * narrowing primitive conversion. 639 * 640 * @return the {@code float} value represented by this object 641 * converted to type {@code long} 642 * @jls 5.1.3 Narrowing Primitive Conversion 643 */ longValue()644 public long longValue() { 645 return (long)value; 646 } 647 648 /** 649 * Returns the {@code float} value of this {@code Float} object. 650 * 651 * @return the {@code float} value represented by this object 652 */ 653 @HotSpotIntrinsicCandidate floatValue()654 public float floatValue() { 655 return value; 656 } 657 658 /** 659 * Returns the value of this {@code Float} as a {@code double} 660 * after a widening primitive conversion. 661 * 662 * @return the {@code float} value represented by this 663 * object converted to type {@code double} 664 * @jls 5.1.2 Widening Primitive Conversion 665 */ doubleValue()666 public double doubleValue() { 667 return (double)value; 668 } 669 670 /** 671 * Returns a hash code for this {@code Float} object. The 672 * result is the integer bit representation, exactly as produced 673 * by the method {@link #floatToIntBits(float)}, of the primitive 674 * {@code float} value represented by this {@code Float} 675 * object. 676 * 677 * @return a hash code value for this object. 678 */ 679 @Override hashCode()680 public int hashCode() { 681 return Float.hashCode(value); 682 } 683 684 /** 685 * Returns a hash code for a {@code float} value; compatible with 686 * {@code Float.hashCode()}. 687 * 688 * @param value the value to hash 689 * @return a hash code value for a {@code float} value. 690 * @since 1.8 691 */ hashCode(float value)692 public static int hashCode(float value) { 693 return floatToIntBits(value); 694 } 695 696 /** 697 * Compares this object against the specified object. The result 698 * is {@code true} if and only if the argument is not 699 * {@code null} and is a {@code Float} object that 700 * represents a {@code float} with the same value as the 701 * {@code float} represented by this object. For this 702 * purpose, two {@code float} values are considered to be the 703 * same if and only if the method {@link #floatToIntBits(float)} 704 * returns the identical {@code int} value when applied to 705 * each. 706 * 707 * <p>Note that in most cases, for two instances of class 708 * {@code Float}, {@code f1} and {@code f2}, the value 709 * of {@code f1.equals(f2)} is {@code true} if and only if 710 * 711 * <blockquote><pre> 712 * f1.floatValue() == f2.floatValue() 713 * </pre></blockquote> 714 * 715 * <p>also has the value {@code true}. However, there are two exceptions: 716 * <ul> 717 * <li>If {@code f1} and {@code f2} both represent 718 * {@code Float.NaN}, then the {@code equals} method returns 719 * {@code true}, even though {@code Float.NaN==Float.NaN} 720 * has the value {@code false}. 721 * <li>If {@code f1} represents {@code +0.0f} while 722 * {@code f2} represents {@code -0.0f}, or vice 723 * versa, the {@code equal} test has the value 724 * {@code false}, even though {@code 0.0f==-0.0f} 725 * has the value {@code true}. 726 * </ul> 727 * 728 * This definition allows hash tables to operate properly. 729 * 730 * @param obj the object to be compared 731 * @return {@code true} if the objects are the same; 732 * {@code false} otherwise. 733 * @see java.lang.Float#floatToIntBits(float) 734 */ equals(Object obj)735 public boolean equals(Object obj) { 736 return (obj instanceof Float) 737 && (floatToIntBits(((Float)obj).value) == floatToIntBits(value)); 738 } 739 740 /** 741 * Returns a representation of the specified floating-point value 742 * according to the IEEE 754 floating-point "single format" bit 743 * layout. 744 * 745 * <p>Bit 31 (the bit that is selected by the mask 746 * {@code 0x80000000}) represents the sign of the floating-point 747 * number. 748 * Bits 30-23 (the bits that are selected by the mask 749 * {@code 0x7f800000}) represent the exponent. 750 * Bits 22-0 (the bits that are selected by the mask 751 * {@code 0x007fffff}) represent the significand (sometimes called 752 * the mantissa) of the floating-point number. 753 * 754 * <p>If the argument is positive infinity, the result is 755 * {@code 0x7f800000}. 756 * 757 * <p>If the argument is negative infinity, the result is 758 * {@code 0xff800000}. 759 * 760 * <p>If the argument is NaN, the result is {@code 0x7fc00000}. 761 * 762 * <p>In all cases, the result is an integer that, when given to the 763 * {@link #intBitsToFloat(int)} method, will produce a floating-point 764 * value the same as the argument to {@code floatToIntBits} 765 * (except all NaN values are collapsed to a single 766 * "canonical" NaN value). 767 * 768 * @param value a floating-point number. 769 * @return the bits that represent the floating-point number. 770 */ 771 @HotSpotIntrinsicCandidate floatToIntBits(float value)772 public static int floatToIntBits(float value) { 773 if (!isNaN(value)) { 774 return floatToRawIntBits(value); 775 } 776 return 0x7fc00000; 777 } 778 779 /** 780 * Returns a representation of the specified floating-point value 781 * according to the IEEE 754 floating-point "single format" bit 782 * layout, preserving Not-a-Number (NaN) values. 783 * 784 * <p>Bit 31 (the bit that is selected by the mask 785 * {@code 0x80000000}) represents the sign of the floating-point 786 * number. 787 * Bits 30-23 (the bits that are selected by the mask 788 * {@code 0x7f800000}) represent the exponent. 789 * Bits 22-0 (the bits that are selected by the mask 790 * {@code 0x007fffff}) represent the significand (sometimes called 791 * the mantissa) of the floating-point number. 792 * 793 * <p>If the argument is positive infinity, the result is 794 * {@code 0x7f800000}. 795 * 796 * <p>If the argument is negative infinity, the result is 797 * {@code 0xff800000}. 798 * 799 * <p>If the argument is NaN, the result is the integer representing 800 * the actual NaN value. Unlike the {@code floatToIntBits} 801 * method, {@code floatToRawIntBits} does not collapse all the 802 * bit patterns encoding a NaN to a single "canonical" 803 * NaN value. 804 * 805 * <p>In all cases, the result is an integer that, when given to the 806 * {@link #intBitsToFloat(int)} method, will produce a 807 * floating-point value the same as the argument to 808 * {@code floatToRawIntBits}. 809 * 810 * @param value a floating-point number. 811 * @return the bits that represent the floating-point number. 812 * @since 1.3 813 */ 814 @HotSpotIntrinsicCandidate floatToRawIntBits(float value)815 public static native int floatToRawIntBits(float value); 816 817 /** 818 * Returns the {@code float} value corresponding to a given 819 * bit representation. 820 * The argument is considered to be a representation of a 821 * floating-point value according to the IEEE 754 floating-point 822 * "single format" bit layout. 823 * 824 * <p>If the argument is {@code 0x7f800000}, the result is positive 825 * infinity. 826 * 827 * <p>If the argument is {@code 0xff800000}, the result is negative 828 * infinity. 829 * 830 * <p>If the argument is any value in the range 831 * {@code 0x7f800001} through {@code 0x7fffffff} or in 832 * the range {@code 0xff800001} through 833 * {@code 0xffffffff}, the result is a NaN. No IEEE 754 834 * floating-point operation provided by Java can distinguish 835 * between two NaN values of the same type with different bit 836 * patterns. Distinct values of NaN are only distinguishable by 837 * use of the {@code Float.floatToRawIntBits} method. 838 * 839 * <p>In all other cases, let <i>s</i>, <i>e</i>, and <i>m</i> be three 840 * values that can be computed from the argument: 841 * 842 * <blockquote><pre>{@code 843 * int s = ((bits >> 31) == 0) ? 1 : -1; 844 * int e = ((bits >> 23) & 0xff); 845 * int m = (e == 0) ? 846 * (bits & 0x7fffff) << 1 : 847 * (bits & 0x7fffff) | 0x800000; 848 * }</pre></blockquote> 849 * 850 * Then the floating-point result equals the value of the mathematical 851 * expression <i>s</i>·<i>m</i>·2<sup><i>e</i>-150</sup>. 852 * 853 * <p>Note that this method may not be able to return a 854 * {@code float} NaN with exactly same bit pattern as the 855 * {@code int} argument. IEEE 754 distinguishes between two 856 * kinds of NaNs, quiet NaNs and <i>signaling NaNs</i>. The 857 * differences between the two kinds of NaN are generally not 858 * visible in Java. Arithmetic operations on signaling NaNs turn 859 * them into quiet NaNs with a different, but often similar, bit 860 * pattern. However, on some processors merely copying a 861 * signaling NaN also performs that conversion. In particular, 862 * copying a signaling NaN to return it to the calling method may 863 * perform this conversion. So {@code intBitsToFloat} may 864 * not be able to return a {@code float} with a signaling NaN 865 * bit pattern. Consequently, for some {@code int} values, 866 * {@code floatToRawIntBits(intBitsToFloat(start))} may 867 * <i>not</i> equal {@code start}. Moreover, which 868 * particular bit patterns represent signaling NaNs is platform 869 * dependent; although all NaN bit patterns, quiet or signaling, 870 * must be in the NaN range identified above. 871 * 872 * @param bits an integer. 873 * @return the {@code float} floating-point value with the same bit 874 * pattern. 875 */ 876 @HotSpotIntrinsicCandidate intBitsToFloat(int bits)877 public static native float intBitsToFloat(int bits); 878 879 /** 880 * Compares two {@code Float} objects numerically. There are 881 * two ways in which comparisons performed by this method differ 882 * from those performed by the Java language numerical comparison 883 * operators ({@code <, <=, ==, >=, >}) when 884 * applied to primitive {@code float} values: 885 * 886 * <ul><li> 887 * {@code Float.NaN} is considered by this method to 888 * be equal to itself and greater than all other 889 * {@code float} values 890 * (including {@code Float.POSITIVE_INFINITY}). 891 * <li> 892 * {@code 0.0f} is considered by this method to be greater 893 * than {@code -0.0f}. 894 * </ul> 895 * 896 * This ensures that the <i>natural ordering</i> of {@code Float} 897 * objects imposed by this method is <i>consistent with equals</i>. 898 * 899 * @param anotherFloat the {@code Float} to be compared. 900 * @return the value {@code 0} if {@code anotherFloat} is 901 * numerically equal to this {@code Float}; a value 902 * less than {@code 0} if this {@code Float} 903 * is numerically less than {@code anotherFloat}; 904 * and a value greater than {@code 0} if this 905 * {@code Float} is numerically greater than 906 * {@code anotherFloat}. 907 * 908 * @since 1.2 909 * @see Comparable#compareTo(Object) 910 */ compareTo(Float anotherFloat)911 public int compareTo(Float anotherFloat) { 912 return Float.compare(value, anotherFloat.value); 913 } 914 915 /** 916 * Compares the two specified {@code float} values. The sign 917 * of the integer value returned is the same as that of the 918 * integer that would be returned by the call: 919 * <pre> 920 * new Float(f1).compareTo(new Float(f2)) 921 * </pre> 922 * 923 * @param f1 the first {@code float} to compare. 924 * @param f2 the second {@code float} to compare. 925 * @return the value {@code 0} if {@code f1} is 926 * numerically equal to {@code f2}; a value less than 927 * {@code 0} if {@code f1} is numerically less than 928 * {@code f2}; and a value greater than {@code 0} 929 * if {@code f1} is numerically greater than 930 * {@code f2}. 931 * @since 1.4 932 */ compare(float f1, float f2)933 public static int compare(float f1, float f2) { 934 if (f1 < f2) 935 return -1; // Neither val is NaN, thisVal is smaller 936 if (f1 > f2) 937 return 1; // Neither val is NaN, thisVal is larger 938 939 // Cannot use floatToRawIntBits because of possibility of NaNs. 940 int thisBits = Float.floatToIntBits(f1); 941 int anotherBits = Float.floatToIntBits(f2); 942 943 return (thisBits == anotherBits ? 0 : // Values are equal 944 (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN) 945 1)); // (0.0, -0.0) or (NaN, !NaN) 946 } 947 948 /** 949 * Adds two {@code float} values together as per the + operator. 950 * 951 * @param a the first operand 952 * @param b the second operand 953 * @return the sum of {@code a} and {@code b} 954 * @jls 4.2.4 Floating-Point Operations 955 * @see java.util.function.BinaryOperator 956 * @since 1.8 957 */ sum(float a, float b)958 public static float sum(float a, float b) { 959 return a + b; 960 } 961 962 /** 963 * Returns the greater of two {@code float} values 964 * as if by calling {@link Math#max(float, float) Math.max}. 965 * 966 * @param a the first operand 967 * @param b the second operand 968 * @return the greater of {@code a} and {@code b} 969 * @see java.util.function.BinaryOperator 970 * @since 1.8 971 */ max(float a, float b)972 public static float max(float a, float b) { 973 return Math.max(a, b); 974 } 975 976 /** 977 * Returns the smaller of two {@code float} values 978 * as if by calling {@link Math#min(float, float) Math.min}. 979 * 980 * @param a the first operand 981 * @param b the second operand 982 * @return the smaller of {@code a} and {@code b} 983 * @see java.util.function.BinaryOperator 984 * @since 1.8 985 */ min(float a, float b)986 public static float min(float a, float b) { 987 return Math.min(a, b); 988 } 989 990 /** 991 * Returns an {@link Optional} containing the nominal descriptor for this 992 * instance, which is the instance itself. 993 * 994 * @return an {@link Optional} describing the {@linkplain Float} instance 995 * @since 12 996 */ 997 @Override describeConstable()998 public Optional<Float> describeConstable() { 999 return Optional.of(this); 1000 } 1001 1002 /** 1003 * Resolves this instance as a {@link ConstantDesc}, the result of which is 1004 * the instance itself. 1005 * 1006 * @param lookup ignored 1007 * @return the {@linkplain Float} instance 1008 * @since 12 1009 */ 1010 @Override resolveConstantDesc(MethodHandles.Lookup lookup)1011 public Float resolveConstantDesc(MethodHandles.Lookup lookup) { 1012 return this; 1013 } 1014 1015 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 1016 @java.io.Serial 1017 private static final long serialVersionUID = -2671257302660747028L; 1018 } 1019