Java string character to int

Convert String to int in Java

Learn to convert a Java String to int value. Note that string can contain a normal decimal value or a different value in other bases or radix.

The Integer.parseInt() parses a String to a signed int value. This method is an overloaded method with the following arguments:

  • string: the string to be parsed.
  • radix: radix to be used while parsing.
  • beginIndex: beginning index, inclusive.
  • endIndex: ending index, exclusive.
public static int parseInt(string) throws NumberFormatException < . >public static int parseInt(string, int radix) throws NumberFormatException < . >parseInt(string, int beginIndex, int endIndex, int radix) throws NumberFormatException

In the following Java program, we are parsing the string “1001” using all three above-mentioned methods and verifying that output.

Assertions.assertEquals(1001, Integer.parseInt("1001")); Assertions.assertEquals(513, Integer.parseInt("1001", 8)); Assertions.assertEquals(1001, Integer.parseInt("amount=1001", 7, 11, 10));

1.3. Throws NumberFormatException

  • the argument string is null.
  • the argument string length is zero i.e. empty string.
  • the argument string is not a parsable integer in the specified radix. The default radix is 10.
Assertions.assertThrows(NumberFormatException.class, ()->< Integer.parseInt(null); >); Assertions.assertThrows(NumberFormatException.class, ()->< Integer.parseInt("abc"); >);

The Integer.valueOf() is very similar to parseInt() method – with only one difference that return type is Integer type instead of primitive int. In fact, if we look at the source code of valueOf() method, it internally calls parseInt() method.

Читайте также:  Питон лист в словарь

It is also overloaded in two forms. Notice the method return type is Integer.

public static Integer valueOf(String s) throws NumberFormatException public static Integer valueOf(String s, int radix) throws NumberFormatException

Both methods throw the NumberFormatException in all cases, similar to parseInt().

Assertions.assertEquals(1001, Integer.valueOf("1001")); Assertions.assertEquals(513, Integer.valueOf("1001", 8)); Assertions.assertThrows(NumberFormatException.class, ()->< Integer.valueOf("abc"); >);

The Integer.decode() is another useful method for String to int conversion but only for decimal, hexadecimal and octal numbers. Note that:

  • Decimal numbers should start with optional plus/minus sign i.e. +100, -2022, 334, 404.
  • Octal numbers should start with an optional plus/minus sign and then the suffix ‘0’ (Zero). For example, +o100, -o2022, o334, 0404.
  • Hex numbers should start with an optional plus/minus sign and then the suffix ‘0x’ or ‘0X’ (Zero and X). For example, +0x100, -0x2022, 0x334, 0x404.
public static Integer decode(String s) throws NumberFormatException

Let us see an example to understand it better.

Assertions.assertEquals(100, Integer.decode("+100")); Assertions.assertEquals(64, Integer.decode("+0100")); Assertions.assertEquals(256, Integer.decode("+0x100"));

In this quick Java tutorial, we learned to parse a string to int or Integer type. We also learned to parse the numbers in decimal, octal and hexadecimal formats.

Источник

Java String to Int – How to Convert a String to an Integer

Thanoshan MV

Thanoshan MV

Java String to Int – How to Convert a String to an Integer

String objects are represented as a string of characters.

If you have worked in Java Swing, it has components such as JTextField and JTextArea which we use to get our input from the GUI. It takes our input as a string.

If we want to make a simple calculator using Swing, we need to figure out how to convert a string to an integer. This leads us to the question – how can we convert a string to an integer?

In Java, we can use Integer.valueOf() and Integer.parseInt() to convert a string to an integer.

1. Use Integer.parseInt() to Convert a String to an Integer

This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.

So, every time we convert a string to an int, we need to take care of this exception by placing the code inside the try-catch block.

Let’s consider an example of converting a string to an int using Integer.parseInt() :

 String str = "25"; try < int number = Integer.parseInt(str); System.out.println(number); // output = 25 >catch (NumberFormatException ex)

Let’s try to break this code by inputting an invalid integer:

 String str = "25T"; try < int number = Integer.parseInt(str); System.out.println(number); >catch (NumberFormatException ex)

As you can see in the above code, we have tried to convert 25T to an integer. This is not a valid input. Therefore, it must throw a NumberFormatException.

Here’s the output of the above code:

java.lang.NumberFormatException: For input string: "25T" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at OOP.StringTest.main(StringTest.java:51)

Next, we will consider how to convert a string to an integer using the Integer.valueOf() method.

2. Use Integer.valueOf() to Convert a String to an Integer

This method returns the string as an integer object. If you look at the Java documentation, Integer.valueOf() returns an integer object which is equivalent to a new Integer(Integer.parseInt(s)) .

We will place our code inside the try-catch block when using this method. Let us consider an example using the Integer.valueOf() method:

 String str = "25"; try < Integer number = Integer.valueOf(str); System.out.println(number); // output = 25 >catch (NumberFormatException ex)

Now, let’s try to break the above code by inputting an invalid integer number:

 String str = "25TA"; try < Integer number = Integer.valueOf(str); System.out.println(number); >catch (NumberFormatException ex)

Similar to the previous example, the above code will throw an exception.

Here’s the output of the above code:

java.lang.NumberFormatException: For input string: "25TA" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.valueOf(Integer.java:766) at OOP.StringTest.main(StringTest.java:42)

We can also create a method to check if the passed-in string is numeric or not before using the above mentioned methods.

I have created a simple method for checking whether the passed-in string is numeric or not.

public class StringTest < public static void main(String[] args) < String str = "25"; String str1 = "25.06"; System.out.println(isNumeric(str)); System.out.println(isNumeric(str1)); >private static boolean isNumeric(String str) < return str != null && str.matches("[0-9.]+"); >>

The isNumeric() method takes a string as an argument. First it checks if it is null or not. After that we use the matches() method to check if it contains digits 0 to 9 and a period character.

This is a simple way to check numeric values. You can write or search Google for more advanced regular expressions to capture numerics depending on your use case.

It is a best practice to check if the passed-in string is numeric or not before trying to convert it to integer.

You can connect with me on Medium.

Happy Coding!

Источник

Char to Int in Java

Java Course - Mastering the Fundamentals

There are different ways to convert a character to its corresponding integer representation.

  • Assigning a character to an integer-type variable gives the ASCII value of the character.
  • Use Character.getNumericValue() method
  • Convert the character to a String using String.valueOf() method and use Integer.parseInt() method.
  • Subtract ‘0’ from the character.

How to convert char to int in Java?

Sometimes we need to perform operations on integer values, here in this case it may be possible that the int value is stored in a char data type. In this situation, we first need to convert the char value to its corresponding integer value and then do the required operation.

The primitive data type can be converted from char to int data type in java using several ways:-

  1. Using ASCII values: We can automatically convert a character to its ASCII value by using implicit typecasting.
  2. Character.getNumericValue(): We can convert char to int using getNumericValue() method of the Character class.
  3. Using parseInt() method with String.valueOf(): We can convert char to int in java by converting char to string using String.valueOf() and then converting string to int using Integer.parseInt() method.
  4. Subtracting with ‘0’: we can convert char to int by subtracting with 0 , this works on the concept of ASCII values.

Method 1: Using ASCII values

American Standard Code for Information Interchange is an encoding format used to store characters on a computer, it is a 7 — bit character set containing 128 characters.

In Java programming language we have implicit typecasting, i.e if we store the value of a smaller datatype to a variable of the larger datatype, then the value is automatically converted. This means that the variable is implicitly typecasted into a larger datatype variable.

Explanation:

  • So in this example variable first is implicitly typecasted to int datatype and then stored in second variable.
  • So now if we print the second variable it will print 53 . This is because we have assigned the char variable first to the int variable second and we get the ASCII value of 5 i.e. 53.

Example: 53-48 = 5

Below is the java program to convert char to int in java using the ASCII value:-

Method 2: Using Character.getNumericValue()

In Java, we have a method getNumericValue() inside the Character class. This method returns an int value which is the encoding of a Unicode character.

This method takes an argument of char datatype and returns the corresponding int value.

Method 3: parseInt() method with String.valueOf()

In java we can also convert from char to int java using the parseInt() and String.valueOf() methods.

  • The String.valueOf(): method converts a char datatype variable into a string datatype variable and,
  • Integer.parseInt(): method is used to convert string into an int datatype.

The method valueOf() belongs to String class and parseInt() method belongs to Integer class.

Explanation:

  • Here in this example, ch1 is first converted to string using String.valueOf() and then it is converted to int using Integer.parseInt() .
  • Similar operations are performed with ch2 character as well.

Method 4: Subtraction with ‘0’:

In Java we can also convert the numeric value stored in a char to int datatype by subtracting it with the character 0 (zero). This is based on the concept of ASCII values.

If we want to convert char to int, we will subtract ‘0’ from the character.

  • In the code above, ch1 which is equal to ‘5’ has an ASCII value of 53 .
  • And ASCII value of 0 is 48 so if we subtract 48 from 53 we get 5 which is the int value of num1.
  • So in background implicit type casting is being done and the we subtract it from ASCII value of 0 and hence getting the conversion from char to int.
  • Similar operations are performed in case of ch2 as well.

Conclusion:

  1. In this article, we discussed different methods to convert char to int in java.
  2. These methods are:
    • Using ASCII values
    • Character.getNumericValue()
    • char to int using parseInt() method with String.valueOf()
    • char to int by subtracting with 0
  3. When a character is subtracted from another character, internal typecasting is performed to convert the characters to their corresponding ASCII numbers. The result is the subtraction between their ASCII values.

Источник

Оцените статью