It becomes interesting (not to say: confusing) if, for example, we convert the valid int value 0xCAFEBABE into a hex String and then back into an int: In all the above cases, the number to be parsed must be within the range Integer.MIN_VALUE (= -2 31 = -2,147,483,648) to Integer.MAX_VALUE (= 2 31-1 = 2,147,483,647). A hexadecimal number can be parsed as follows: The parameter radix specifies the base of the number system. Integer i = Integer.valueOf(s, radix) (→ JavaDoc).int i = Integer.parseInt(s, radix) (→ JavaDoc). To parse other number systems, the following overloaded methods are available: Integer.parseInt("1,000") // Thousands separator not allowed.Integer.parseInt("3.14") // Decimal point not allowed.Integer.parseInt(" 1") // Space not allowed.Integer.parseInt("") // Empty string not allowed.The following Strings are not allowed and result in NumberFormatExceptions: The String to convert must contain only digits, optionally with a plus or minus sign in front. The second method internally calls the first method and converts the result to an Integer object. Integer i = Integer.valueOf(s) (→ JavaDoc). int i = Integer.parseInt(s) (→ JavaDoc).Let's first look at the options to parse a String into an int (or Integer). You can find the source code for this article in my GitHub repository. Today you will learn what to consider in the opposite direction, i.e., when parsing a String to an int. In the previous article, I showed you that "" + i is the fastest way to convert an int into a String in Java.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |