Class Integer
In addition, this class provides several methods for converting an int to a String and a String to an int , as well as other constants and methods useful when dealing with an int .
This is a value-based class; programmers should treat instances that are equal as interchangeable and should not use instances for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail.
Implementation note: The implementations of the «bit twiddling» methods (such as highestOneBit and numberOfTrailingZeros ) are based on material from Henry S. Warren, Jr.’s Hacker’s Delight, (Addison Wesley, 2002).
Field Summary
Constructor Summary
Method Summary
Methods declared in class java.lang.Object
Field Details
MIN_VALUE
MAX_VALUE
BYTES
Constructor Details
Integer
Integer
Method Details
toString
If the radix is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX , then the radix 10 is used instead.
If the first argument is negative, the first element of the result is the ASCII minus character ‘-‘ ( ‘\u002D’ ). If the first argument is not negative, no sign character appears in the result.
The remaining characters of the result represent the magnitude of the first argument. If the magnitude is zero, it is represented by a single zero character ‘0’ ( ‘\u0030’ ); otherwise, the first character of the representation of the magnitude will not be the zero character. The following ASCII characters are used as digits:
toUnsignedString
If the radix is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX , then the radix 10 is used instead.
Note that since the first argument is treated as an unsigned value, no leading sign character is printed.
If the magnitude is zero, it is represented by a single zero character ‘0’ ( ‘\u0030’ ); otherwise, the first character of the representation of the magnitude will not be the zero character.
The behavior of radixes and the characters used as digits are the same as toString .
toHexString
The unsigned integer value is the argument plus 2 32 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0 s.
The value of the argument can be recovered from the returned string s by calling Integer.parseUnsignedInt(s, 16) .
If the unsigned magnitude is zero, it is represented by a single zero character ‘0’ ( ‘\u0030’ ); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The following characters are used as hexadecimal digits:
toOctalString
The unsigned integer value is the argument plus 2 32 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in octal (base 8) with no extra leading 0 s.
The value of the argument can be recovered from the returned string s by calling Integer.parseUnsignedInt(s, 8) .
If the unsigned magnitude is zero, it is represented by a single zero character ‘0’ ( ‘\u0030’ ); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The following characters are used as octal digits:
toBinaryString
The unsigned integer value is the argument plus 2 32 if the argument is negative; otherwise it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0 s.
The value of the argument can be recovered from the returned string s by calling Integer.parseUnsignedInt(s, 2) .
If the unsigned magnitude is zero, it is represented by a single zero character ‘0’ ( ‘\u0030’ ); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The characters ‘0’ ( ‘\u0030’ ) and ‘1’ ( ‘\u0031’ ) are used as binary digits.
toString
toUnsignedString
parseInt
- The first argument is null or is a string of length zero.
- The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX .
- Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ ( ‘\u002D’ ) or plus sign ‘+’ ( ‘\u002B’ ) provided that the string is longer than length 1.
- The value represented by the string is not a value of type int .
parseInt
The method does not take steps to guard against the CharSequence being mutated while parsing.
parseInt
parseUnsignedInt
- The first argument is null or is a string of length zero.
- The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX .
- Any character of the string is not a digit of the specified radix, except that the first character may be a plus sign ‘+’ ( ‘\u002B’ ) provided that the string is longer than length 1.
- The value represented by the string is larger than the largest unsigned int , 2 32 -1.
parseUnsignedInt
The method does not take steps to guard against the CharSequence being mutated while parsing.
parseUnsignedInt
valueOf
In other words, this method returns an Integer object equal to the value of:
valueOf
In other words, this method returns an Integer object equal to the value of:
valueOf
byteValue
shortValue
intValue
longValue
floatValue
doubleValue
toString
hashCode
hashCode
equals
getInteger
The first argument is treated as the name of a system property. System properties are accessible through the System.getProperty(java.lang.String) method. The string value of this property is then interpreted as an integer value using the grammar supported by decode and an Integer object representing this value is returned.
If there is no property with the specified name, if the specified name is empty or null , or if the property does not have the correct numeric format, then null is returned.
In other words, this method returns an Integer object equal to the value of:
getInteger
The first argument is treated as the name of a system property. System properties are accessible through the System.getProperty(java.lang.String) method. The string value of this property is then interpreted as an integer value using the grammar supported by decode and an Integer object representing this value is returned.
The second argument is the default value. An Integer object that represents the value of the second argument is returned if there is no property of the specified name, if the property does not have the correct numeric format, or if the specified name is empty or null .
In other words, this method returns an Integer object equal to the value of:
getInteger
- If the property value begins with the two ASCII characters 0x or the ASCII character # , not followed by a minus sign, then the rest of it is parsed as a hexadecimal integer exactly as by the method valueOf(java.lang.String, int) with radix 16.
- If the property value begins with the ASCII character 0 followed by another character, it is parsed as an octal integer exactly as by the method valueOf(java.lang.String, int) with radix 8.
- Otherwise, the property value is parsed as a decimal integer exactly as by the method valueOf(java.lang.String, int) with radix 10.
The second argument is the default value. The default value is returned if there is no property of the specified name, if the property does not have the correct numeric format, or if the specified name is empty or null .
# Primitive Data Types
It has a minimum value of \u0000 (0 in the decimal representation, also called the null character) and a maximum value of \uffff (65,535).
The default value of a char is \u0000 .
In order to define a char of ‘ value an escape sequence (character preceded by a backslash) has to be used:
There are also other escape sequences:
You can declare a char of any Unicode character.
It is also possible to add to a char . e.g. to iterate through every lower-case letter, you could do to the following:
# Primitive Types Cheatsheet
Table showing size and values range of all primitive types:
| data type | numeric representation | range of values | default value |
|---|---|---|---|
| boolean | n/a | false and true | false |
| byte | 8-bit signed | -2 7 to 2 7 — 1 | 0 |
| -128 to +127 | |||
| short | 16-bit signed | -2 15 to 2 15 — 1 | 0 |
| -32,768 to +32,767 | |||
| int | 32-bit signed | -2 31 to 2 31 — 1 | 0 |
| -2,147,483,648 to +2,147,483,647 | |||
| long | 64-bit signed | -2 63 to 2 63 — 1 | 0L |
| -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | |||
| float | 32-bit floating point | 1.401298464e-45 to 3.402823466e+38 (positive or negative) | 0.0F |
| double | 64-bit floating point | 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative) | 0.0D |
| char | 16-bit unsigned | 0 to 2 16 — 1 | 0 |
| 0 to 65,535 |
- The Java Language Specification mandates that signed integral types ( byte through long ) use binary twos-complement representation, and the floating point types use standard IEE 754 binary floating point representations.
- Java 8 and later provide methods to perform unsigned arithmetic operations on int and long . While these methods allow a program to treat values of the respective types as unsigned, the types remain signed types.
- The smallest floating point shown above are subnormal; i.e. they have less precision than a normal value. The smallest normal numbers are 1.175494351e−38 and 2.2250738585072014e−308
- A char conventionally represents a Unicode / UTF-16 code unit.
- Although a boolean contains just one bit of information, its size in memory varies depending on the Java Virtual Machine implementation (see boolean type
# The float primitive
A float is a single-precision 32-bit IEEE 754 floating point number. By default, decimals are interpreted as doubles. To create a float , simply append an f to the decimal literal.
Floats handle the five common arithmetical operations: addition, subtraction, multiplication, division, and modulus.
Note: The following may vary slightly as a result of floating point errors. Some results have been rounded for clarity and readability purposes (i.e. the printed result of the addition example was actually 34.600002).
Because of the way floating point numbers are stored (i.e. in binary form), many numbers don’t have an exact representation.
While using float is fine for most applications, neither float nor double should be used to store exact representations of decimal numbers (like monetary amounts), or numbers where higher precision is required. Instead, the BigDecimal class should be used.
The default value of a float is 0.0f.
A float is precise to roughly an error of 1 in 10 million.
Note: Float.POSITIVE_INFINITY , Float.NEGATIVE_INFINITY , Float.NaN are float values. NaN stands for results of operations that cannot be determined, such as dividing 2 infinite values. Furthermore 0f and -0f are different, but == yields true:
# The int primitive
A primitive data type such as int holds values directly into the variable that is using it, meanwhile a variable that was declared using Integer holds a reference to the value.
(opens new window) : "The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int."
By default, int is a 32-bit signed integer. It can store a minimum value of -2 31 , and a maximum value of 2 31 — 1.
If you need to store a number outside of this range, long should be used instead. Exceeding the value range of int leads to an integer overflow, causing the value exceeding the range to be added to the opposite site of the range (positive becomes negative and vise versa). The value is ((value — MIN_VALUE) % RANGE) + MIN_VALUE , or ((value + 2147483648) % 4294967296) — 2147483648
The maximum and minimum values of int can be found at:
The default value of an int is 0
# Memory consumption of primitives vs. boxed primitives
| Primitive | Boxed Type | Memory Size of primitive / boxed |
|---|---|---|
| boolean | Boolean | 1 byte / 16 bytes |
| byte | Byte | 1 byte / 16 bytes |
| short | Short | 2 bytes / 16 bytes |
| char | Char | 2 bytes / 16 bytes |
| int | Integer | 4 bytes / 16 bytes |
| long | Long | 8 bytes / 16 bytes |
| float | Float | 4 bytes / 16 bytes |
| double | Double | 8 bytes / 16 bytes |
Boxed objects always require 8 bytes for type and memory management, and because the size of objects is always a multiple of 8, boxed types all require 16 bytes total. In addition, each usage of a boxed object entails storing a reference which accounts for another 4 or 8 bytes, depending on the JVM and JVM options.
In data-intensive operations, memory consumption can have a major impact on performance. Memory consumption grows even more when using arrays: a float[5] array will require only 32 bytes; whereas a Float[5] storing 5 distinct non-null values will require 112 bytes total (on 64 bit without compressed pointers, this increases to 152 bytes).
# Boxed value caches
The space overheads of the boxed types can be mitigated to a degree by the boxed value caches. Some of the boxed types implement a cache of instances. For example, by default, the Integer class will cache instances to represent numbers in the range -128 to +127 . This does not, however, reduce the additional cost arising from the additional memory indirection.
If you create an instance of a boxed type either by autoboxing or by calling the static valueOf(primitive) method, the runtime system will attempt to use a cached value. If your application uses a lot of values in the range that is cached, then this can substantially reduce the memory penalty of using boxed types. Certainly, if you are creating boxed value instances "by hand", it is better to use valueOf rather than new . (The new operation always creates a new instance.) If, however, the majority of your values are not in the cached range, it can be faster to call new and save the cache lookup.
# Converting Primitives
In Java, we can convert between integer values and floating-point values. Also, since every character corresponds to a number in the Unicode encoding, char types can be converted to and from the integer and floating-point types. boolean is the only primitive datatype that cannot be converted to or from any other primitive datatype.
There are two types of conversions: widening conversion and narrowing conversion.
A widening conversion is when a value of one datatype is converted to a value of another datatype that occupies more bits than the former. There is no issue of data loss in this case.
Correspondingly, A narrowing conversion is when a value of one datatype is converted to a value of another datatype that occupies fewer bits than the former. Data loss can occur in this case.
Java performs widening conversions automatically. But if you want to perform a narrowing conversion (if you are sure that no data loss will occur), then you can force Java to perform the conversion using a language construct known as a cast .
Widening Conversion:
Narrowing Conversion:
# The double primitive
A double is a double-precision 64-bit IEEE 754 floating point number.
Because of the way floating point numbers are stored, many numbers don’t have an exact representation.
While using double is fine for most applications, neither float nor double should be used to store precise numbers such as currency. Instead, the BigDecimal class should be used
The default value of a double is 0.0d
Note: Double.POSITIVE_INFINITY , Double.NEGATIVE_INFINITY , Double.NaN are double values. NaN stands for results of operations that cannot be determined, such as dividing 2 infinite values. Furthermore 0d and -0d are different, but == yields true:
# The long primitive
By default, long is a 64-bit signed integer (in Java 8, it can be either signed or unsigned). Signed, it can store a minimum value of -2 63 , and a maximum value of 2 63 — 1, and unsigned it can store a minimum value of 0 and a maximum value of 2 64 — 1
The maximum and minimum values of long can be found at:
The default value of a long is 0L
Note: letter "L" appended at the end of long literal is case insensitive, however it is good practice to use capital as it is easier to distinct from digit one:
Warning: Java caches Integer objects instances from the range -128 to 127. The reasoning is explained here: https://blogs.oracle.com/darcy/entry/boxing_and_caches_integer_valueof
The following results can be found:
To properly compare 2 Object Long values, use the following code(From Java 1.7 onward):
Comparing a primitive long to an Object long will not result in a false negative like comparing 2 objects with == does.
# The boolean primitive
A boolean can store one of two values, either true or false
The default value of a boolean is false
# The byte primitive
A byte is a 8-bit signed integer. It can store a minimum value of -2 7 (-128), and a maximum value of 2 7 — 1 (127)
The maximum and minimum values of byte can be found at:
The default value of a byte is 0
# Negative value representation
Java and most other languages store negative integral numbers in a representation called 2’s complement notation.
For a unique binary representation of a data type using n bits, values are encoded like this:
The least significant n-1 bits store a positive integral number x in integral representation. Most significant value stores a bit vith value s . The value repesented by those bits is
i.e. if the most significant bit is 1, then a value that is just by 1 larger than the number you could represent with the other bits ( 2<sup>n-2</sup> + 2<sup>n-3</sup> + . + 2<sup>1</sup> + 2<sup>0</sup> = 2<sup>n-1</sup> — 1 ) is subtracted allowing a unique binary representation for each value from — 2 n-1 (s = 1; x = 0) to 2 n-1 — 1 (s = 0; x = 2 n-1 — 1).
This also has the nice side effect, that you can add the binary representations as if they were positive binary numbers:
Example: taking the negative value of 0 ( byte ):
The result of negating 0 , is 11111111 . Adding 1 gives a value of 100000000 (9 bits). Because a byte can only store 8 bits, the leftmost value is truncated, and the result is 00000000
| Original | Process | Result |
|---|---|---|
| 0 (00000000) | Negate | -0 (11111111) |
| 11111111 | Add 1 to binary | 100000000 |
| 100000000 | Truncate to 8 bits | 00000000 (-0 equals 0) |
# The short primitive
A short is a 16-bit signed integer. It has a minimum value of -2 15 (-32,768), and a maximum value of 2 15 ‑1 (32,767)
The maximum and minimum values of short can be found at:
The default value of a short is 0
# Syntax
# Remarks
Java has 8 primitive data types, namely boolean , byte , short , char , int , long , float and double . (All other types are reference types. This includes all array types, and built-in object types / classes that have special significance in the Java language; e.g. String , Class and Throwable and its subclasses.)
The result of all operations (addition, subtraction, multiplication, etc) on a primitive type is at least an int , thus adding a short to a short produces an int , as does adding a byte to a byte , or a char to a char . If you want to assign the result of that back to a value of the same type, you must cast it. e.g.
Not casting the operation will result in a compile error.
This is due to the following part of the Java Language Spec, §2.11.1
A compiler encodes loads of literal values of types byte and short using Java Virtual Machine instructions that sign-extend those values to values of type int at compile-time or run-time. Loads of literal values of types boolean and char are encoded using instructions that zero-extend the literal to a value of type int at compile-time or run-time. [..]. Thus, most operations on values of actual types boolean , byte , char , and short are correctly performed by instructions operating on values of computational type int .
The reason behind this is also specified in that section:
Given the Java Virtual Machine’s one-byte opcode size, encoding types into opcodes places pressure on the design of its instruction set. If each typed instruction supported all of the Java Virtual Machine’s run-time data types, there would be more instructions than could be represented in a byte . [. ] Separate instructions can be used to convert between unsupported and supported data types as necessary.
Руководство по классу Java Integer
Изучить, какие еще есть методы класса Integer (изучать можно на сайте с официальной документацией), написать в комментариях, какой из изученных вами методов (без учета тех, которые приведены в статье) наиболее полезен по вашему мнению (будет использоваться вами наиболее часто). А также привести обоснование своего мнения.
P.S. Тут нет правильных ответов, но данная активность позволит лучше изучить класс.
Решить небольшую простенькую задачку для закрепления материала.
У нас есть два числа:
1100001001 — в двоичной системе счисления
33332 — в пятеричной системе счисления
Необходимо используя только методы класса Integer определить максимум среди двух данных чисел, а затем вывести разницу между максимальным и минимальным значением в троичной системе счисления.
Перевести максимально возможное значение Integer в восьмеричную систему счисления и вывести на экран количество цифр в полученном числе (количество считать программно).
max value of integer
In C, the integer (for 32 bit machine) is 32 bits, and it ranges from -32,768 to +32,767. In Java, the integer(long) is also 32 bits, but ranges from -2,147,483,648 to +2,147,483,647.
I do not understand how the range is different in Java, even though the number of bits is the same. Can someone explain this?
2 weeks ago, he had the chance to accept, so technically he's not away.
11 Answers 11
In C, the language itself does not determine the representation of certain datatypes. It can vary from machine to machine, on embedded systems the int can be 16 bit wide, though usually it is 32 bit.
The only requirement is that short int <= int <= long int by size. Also, there is a recommendation that int should represent the native capacity of the processor.
All types are signed. The unsigned modifier allows you to use the highest bit as part of the value (otherwise it is reserved for the sign bit).
Here’s a short table of the possible values for the possible data types:
In Java, the Java Language Specification determines the representation of the data types.
The order is: byte 8 bits, short 16 bits, int 32 bits, long 64 bits. All of these types are signed, there are no unsigned versions. However, bit manipulations treat the numbers as they were unsigned (that is, handling all bits correctly).
The character data type char is 16 bits wide, unsigned, and holds characters using UTF-16 encoding (however, it is possible to assign a char an arbitrary unsigned 16 bit integer that represents an invalid character codepoint)