Skip to content
Fix Code Error

How do I convert a String to an int in Java?

March 13, 2021 by Code Error
Posted By: Anonymous

How can I convert a String to an int in Java?

My String contains only numbers, and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.

Solution

String myString = "1234";
int foo = Integer.parseInt(myString);

If you look at the Java documentation you’ll notice the "catch" is that this function can throw a NumberFormatException, which of course you have to handle:

int foo;
try {
   foo = Integer.parseInt(myString);
}
catch (NumberFormatException e)
{
   foo = 0;
}

(This treatment defaults a malformed number to 0, but you can do something else if you like.)

Alternatively, you can use an Ints method from the Guava library, which in combination with Java 8’s Optional, makes for a powerful and concise way to convert a string into an int:

import com.google.common.primitives.Ints;

int foo = Optional.ofNullable(myString)
 .map(Ints::tryParse)
 .orElse(0)
Answered By: Anonymous

Related Articles

  • AppCompat v7 r21 returning error in values.xml?
  • Interdependent properties in Vue.js
  • What does "Fatal error: Unexpectedly found nil while…
  • How do you specifically order ggplot2 x axis instead…
  • What is an IndexOutOfRangeException /…
  • How to convert number to words in java
  • Do you (really) write exception safe code?
  • Creating an appoint record for health professionals
  • Finding all possible combinations of numbers to…
  • How can I resolve Web Component Testing error?
  • How to remove white space characters from a string…
  • TLS 1.3 server socket with Java 11 and self-signed…
  • What is a NullReferenceException, and how do I fix it?
  • Converting String Array to an Integer Array
  • Integer.valueOf() vs. Integer.parseInt()
  • How to create range in Swift?
  • Checking if a variable is an integer in PHP
  • Adjusting y axis limits in ggplot2 with facet and…
  • Dynamically update values of a chartjs chart
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • Node.js Best Practice Exception Handling
  • How to unescape a Java string literal in Java?
  • Unable to run Robolectric and Espresso with a…
  • How can I prevent java.lang.NumberFormatException:…
  • C compile error: Id returned 1 exit status
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Change point shape in gig-lot only for certain observations
  • Backbone.js - Using new() in Model defaults -…
  • When I'm testing a web app by JUnit and Mockito I…
  • How can I pass a list as a command-line argument…
  • Smart way to truncate long strings
  • How to print binary tree diagram?
  • What's the difference between Instant and LocalDateTime?
  • How can I throw CHECKED exceptions from inside Java…
  • JavaScript gives NaN error on the page but variable…
  • Explanation on Integer.MAX_VALUE and…
  • Representing null in JSON
  • How do I return the response from an asynchronous call?
  • java IO Exception: Stream Closed
  • How to Remove Line Break in String
  • No function matches the given name and argument types
  • Eclipse will not start and I haven't changed anything
  • ClassNotFoundException:…
  • Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM
  • Examples of GoF Design Patterns in Java's core libraries
  • SQLException: No suitable Driver Found for…
  • What is the origin of foo and bar?
  • Neither BindingResult nor plain target object for…
  • SecurityException: Permission denied (missing…
  • Callback functions in C++
  • anaconda/conda - install a specific package version
  • Jetpack Compose and Hilt Conflict
  • Change column type in pandas
  • foobar.withgoogle.com task Please Pass the Coded…
  • What is a stack trace, and how can I use it to debug…
  • Backbone js collection of collections issue
  • Convert an integer to an array of digits
  • (Built-in) way in JavaScript to check if a string is…
  • how to use canvas in JavaScript flappy bird code
  • How to filter a RecyclerView with a SearchView
  • Easy interview question got harder: given numbers…
  • Difference between
  • Why catch and rethrow an exception in C#?
  • How can I update specific parts of a text file in java?
  • Regular expression to match numbers with or without…
  • dart-polymer update polymer dom elements
  • What does "Could not find or load main class" mean?
  • Programmatically Lighten or Darken a hex color (or…
  • Convert hex string to int
  • Gradle error: Execution failed for task…
  • What is a plain English explanation of "Big O" notation?
  • Getting Dropwizard Client And Jersey/HTTP I/O Error…
  • What is your most productive shortcut with Vim?
  • VueJs single file component not reading data/props/methods
  • Use of Jquery on scroll event
  • RegEx match open tags except XHTML self-contained tags
  • Validate that a string is a positive integer
  • Understanding checked vs unchecked exceptions in Java
  • Using enums in a spring entity
  • Extending the defaults of a Model superclass in Backbone.js
  • Can't access Eclipse marketplace
  • How to convert java.util.Date to java.sql.Date?
  • How to cast an Object to an int
  • Fastest way to iterate over all the chars in a String
  • how to group the unique data using array
  • Apache server keeps crashing, "caught SIGTERM,…
  • Good way to encapsulate Integer.parseInt()
  • Mock MQRFH2 header in JUnit Testing Error [MQRFH2…
  • Swift do-try-catch syntax
  • Using Event Aggregator to load a view with different…
  • Logging best practices
  • Removing special characters VBA Excel
  • How to handle users inputting invalid types into a scanner?
  • How do I install Java on Mac OSX allowing version switching?
  • How to download and save an image in Android
  • Linking of Page on same page with nextjs
  • How do Mockito matchers work?
  • The definitive guide to form-based website authentication
  • How should a model be structured in MVC?
  • Wait until all promises complete even if some rejected

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to check whether a string contains a substring in JavaScript?

Next Post:

How do I check out a remote Git branch?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error