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