{"id":4077,"date":"2018-04-20T08:51:28","date_gmt":"2018-04-20T12:51:28","guid":{"rendered":"http:\/\/springframework.guru\/?p=4077"},"modified":"2019-06-16T03:17:51","modified_gmt":"2019-06-16T07:17:51","slug":"java-string-to-int","status":"publish","type":"post","link":"https:\/\/springframework.guru\/java-string-to-int\/","title":{"rendered":"Java String to Int"},"content":{"rendered":"<p>A common requirement while programming in Java is to convert <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">String<\/code> to <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">int<\/code>. UI inputs in Web-based HTML, JSP, or Thymeleaf templates are transferred to backend Java applications as strings. It is the application developer\u2019s responsibility to perform any <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">String<\/code> to <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">int<\/code> conversions to fulfill business logic, such as calculating discounts, storing age, and so on.<\/p>\n<p>In this post, I&#8217;ll discuss how to convert String in Java to int.<\/p>\n<h2>The Integer.parseInt Method<\/h2>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Integer.parseInt()<\/code> method takes as input a <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">String<\/code> and returns an <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">int<\/code> value.<\/p>\n<p>The code to use this method is.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">public int convertWithParseInt(String str){\r\n    int num = Integer.parseInt(str);\r\n    return num;\r\n}\r\n<\/pre>\n<p>Here is the test code in <a href=\"http:\/\/springframework.guru\/unit-testing-junit-part-1\/\" target=\"_blank\" rel=\"noopener noreferrer\">JUnit<\/a>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">package springframework.guru;\r\n\r\nimport org.junit.After;\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\nimport static org.junit.Assert.assertEquals;\r\n\r\npublic class StringToIntConverterTest {\r\n\r\n    private StringToIntConverter stringToIntConverter;\r\n    String str;\r\n\r\n    @Before\r\n    public void setUp(){\r\n        str = \"369\";\r\n        stringToIntConverter=new StringToIntConverter();\r\n    }\r\n    @After\r\n   public void tearDown(){\r\n        str = null;\r\n    }\r\n\r\n    @Test\r\n    public void convertWithParseInt() {\r\n        int val= stringToIntConverter.convertWithParseInt(str);\r\n        System.out.println(val);\r\n        assertEquals(val, 369);\r\n\r\n    }\r\n\r\n}\r\n<\/pre>\n<p>The output on running the test in InteliJ is this.<\/p>\n<p><a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ParseInt.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-4078 size-full\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ParseInt.png\" alt=\"Test Output converting string to int in Java\" width=\"729\" height=\"159\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ParseInt.png 729w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ParseInt-300x65.png 300w\" sizes=\"(max-width: 729px) 100vw, 729px\" \/><\/a><\/p>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Integer<\/code> class also provides an overloaded <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">parseInt()<\/code> method that additionally accepts the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Radix\" target=\"_blank\" rel=\"noopener noreferrer\">radix<\/a> (base) to be used while parsing.<\/p>\n<p>Here is the code to use the overloaded method..<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">public int convertWithParseIntWithRadix(String str, int radix){\r\n    int num = Integer.parseInt(str, radix);\r\n    return num;\r\n}\r\n<\/pre>\n<p>Here is the test code.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">@Test\r\npublic void convertWithParseIntWithRadix() {\r\n    int val= stringToIntConverter.convertWithParseIntWithRadix(\"1010110\", 2);\r\n    System.out.println(val);\r\n    assertEquals(val, 86);\r\n}<\/pre>\n<p>The output on running the test in InteliJ is this.<br \/>\n<a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ParseInt_With_Radix.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-4079 size-full\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ParseInt_With_Radix.png\" alt=\"Java string to int using radix (base)\" width=\"729\" height=\"162\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ParseInt_With_Radix.png 729w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ParseInt_With_Radix-300x67.png 300w\" sizes=\"(max-width: 729px) 100vw, 729px\" \/><\/a><\/p>\n<h2>Handling Parsing Exception<\/h2>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">parseInt()<\/code> method throws a <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">NumberFormatException<\/code> if the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">String<\/code> does not contain a parsable <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">int<\/code>.<\/p>\n<p>Here is a sample code to handle the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">NumberFormatException<\/code> gracefully.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">public static final int DEFAULT_DEFAULT_PARSED_INT = 0;\r\npublic int tryConvertWithParseInt(String str){\r\n    try {\r\n        int number = Integer.parseInt(str);\r\n        return number;\r\n    }\r\n    catch(NumberFormatException e){\r\n        return DEFAULT_DEFAULT_PARSED_INT;\r\n    }\r\n}<\/pre>\n<p>This code returns a default <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">int<\/code> value whenever a <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">NumberFormatException<\/code> is thrown by the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">parseInt()<\/code> method.<\/p>\n<p>Here is the JUnit test code.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">@Test\r\npublic void tryConvertWithParseInt() {\r\n    int valA = stringToIntConverter.tryConvertWithParseInt(str);\r\n    int valB = stringToIntConverter.tryConvertWithParseInt(\"abc\");\r\n    System.out.println(valA);\r\n    assertEquals(valA, 369);\r\n    System.out.println(valB);\r\n    assertEquals(valB, 0);\r\n\r\n}<\/pre>\n<p>The test output is this.<br \/>\n<a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ParseInt_With_Exception_Handling.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-4080 size-full\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ParseInt_With_Exception_Handling.png\" alt=\"Java string to int output\" width=\"729\" height=\"195\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ParseInt_With_Exception_Handling.png 729w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ParseInt_With_Exception_Handling-300x80.png 300w\" sizes=\"(max-width: 729px) 100vw, 729px\" \/><\/a><\/p>\n<h2>The Integer.valueOf Method<\/h2>\n<p>The Integer class also comes with the static <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">valueOf()<\/code> method to convert <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">String<\/code> to <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">int<\/code>. The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">valueOf()<\/code> method interprets the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">String<\/code> exactly as if it were given to <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">parseInt()<\/code>. In fact, the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">valueOf()<\/code> method internally uses the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">parseInt()<\/code> method.<\/p>\n<p>However, <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">valueOf()<\/code> returns a new <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Integer<\/code> object whereas <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">parseInt()<\/code> returns a primitive <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">int<\/code>.<\/p>\n<p>The code to parse <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">String<\/code> using the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">valueOf()<\/code> method is this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">public Integer convertWithValueOf(String str){\r\n    try {\r\n        Integer num = Integer.valueOf(str);\r\n        return num;\r\n    }\r\n    catch(NumberFormatException e){\r\n        return DEFAULT_PARSED_INT;\r\n    }\r\n}<\/pre>\n<p>Here is the JUnit test code.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">@Test\r\npublic void convertWithValueOf() {\r\n     int val= stringToIntConverter.convertWithValueOf(str);\r\n     System.out.println(val);\r\n     assertEquals(val, 369);\r\n }\r\n<\/pre>\n<p>The test output is this.<\/p>\n<p><a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ValueOf.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-4083 size-full\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ValueOf.png\" alt=\"Java string to integer output\" width=\"940\" height=\"197\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ValueOf.png 940w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ValueOf-300x63.png 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/01\/Test_Output_ValueOf-768x161.png 768w\" sizes=\"(max-width: 940px) 100vw, 940px\" \/><\/a><\/p>\n<p><strong>Note<\/strong>: Similar to parseInt(), the valueOf() method also have an overloaded version that accepts an additional radix value.<\/p>\n<h1>Conclusion<\/h1>\n<p>Considering Java is a strongly typed language and often interfaces with systems that do not have the type system of Java, converting from a string value to an int value in Java is very common task.\u00a0As you can see Java provides a number of different ways to convert a string value to an integer value.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A common requirement while programming in Java is to convert String to int. UI inputs in Web-based HTML, JSP, or Thymeleaf templates are transferred to backend Java applications as strings. It is the application developer\u2019s responsibility to perform any String to int conversions to fulfill business logic, such as calculating discounts, storing age, and so [&hellip;]<a href=\"https:\/\/springframework.guru\/java-string-to-int\/\" class=\"df-link-excerpt\">Continue reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":4592,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_lmt_disableupdate":"","_lmt_disable":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2}},"categories":[20],"tags":[27,198],"class_list":["post-4077","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java","tag-string-to-int"],"jetpack_publicize_connections":[],"aioseo_notices":[],"modified_by":"Simanta","jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/springframework.guru\/wp-content\/uploads\/2015\/03\/Banner560x292_07web.jpg","jetpack_shortlink":"https:\/\/wp.me\/p5BZrZ-13L","_links":{"self":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/4077"}],"collection":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/comments?post=4077"}],"version-history":[{"count":9,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/4077\/revisions"}],"predecessor-version":[{"id":5587,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/4077\/revisions\/5587"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media\/4592"}],"wp:attachment":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media?parent=4077"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/categories?post=4077"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/tags?post=4077"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}