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