Java Convert String to intWe can convert String to an int in java using Integer.parseInt() method. To convert String into Integer, we can use Integer.valueOf() method which returns instance of Integer class. ScenarioIt is generally used if we have to perform mathematical operations on the string which contains a number. Whenever we receive data from TextField or TextArea, entered data is received as a string. If entered data is in number format, we need to convert the string to an int. To do so, we use Integer.parseInt() method. SignatureThe parseInt() is the static method of Integer class. The signature of parseInt() method is given below: Java String to int Example: Integer.parseInt()Let’s see the simple code to convert a string to an int in java. Let’s see the simple example of converting String to int in Java. Output: 200 Understanding String Concatenation Operator Output: 200100 300 Java String to Integer Example: Integer.valueOf()The Integer.valueOf() method converts String into Integer object. Let’s see the simple code to convert String to Integer in Java. Output: 300 NumberFormatException CaseIf you don’t have numbers in string literal, calling Integer.parseInt() or Integer.valueOf() methods throw NumberFormatException. Output: Exception in thread "main" java.lang.NumberFormatException: For input string: "hello" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.base/java.lang.Integer.parseInt(Integer.java:652) at java.base/java.lang.Integer.parseInt(Integer.java:770) at StringToIntegerExample3.main(StringToIntegerExample3.java:4) References |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263792.html