How to Check If a String is an Integer in Java

How to Check If a String is an Integer in Java
Coming up next: How to Iterate Set in Java

You're on a roll. Keep up the good work!

Take Quiz Watch Next Lesson
 Replay
Your next lesson will play in 10 seconds
  • 0:02 Java Strings
  • 1:25 Try/Catch
  • 4:19 Lesson Summary
Add to Add to Add to

Want to watch this again later?

Log in or sign up to add this lesson to a Custom Course.

Log in or Sign up

Timeline
Autoplay
Autoplay
Speed

Recommended Lessons and Courses for You

Lesson Transcript
Instructor: Martin Gibbs

Martin has 16 years experience in Human Resources Information Systems and has a PhD in Information Technology Management. He is an adjunct professor of computer science and computer programming.

Strings in Java are powerful because they can hold text, numbers, or any other characters. Sometimes, we need to know if the string is a number. This lesson will show you how to do this correctly.

Java Strings

Java Strings are great when you want to work with a wide variety of data in a single data type. They can hold text, integers, decimals, and doubles. But what if you want to check a given string to see if it is an integer, or if a string array contains an integer?

There are a few methods to accomplish this. We'll start with the parseInt function, which takes a string and tries to change it to an integer. Let's take a look at a basic example. For example, the following code creates a string that is a number, then uses parseInt to display the value.


String tester = new String("871");
System.out.println(Integer.parseInt(tester));


The output would be 871. Remember, any integer is a whole number that can be positive, negative, or zero. Virtually any integer will pass the test. However, numbers beyond the range (such as 8589934592) won't pass. A decimal or fraction will also fail the test.

What if the string was not an integer? Technically, we could use parseInt to check and see if a string is an integer. But if the value was not an integer, Java would throw a very nasty error message. Let's say the string was Jane Eyre, and we tried the previous code. An error like this would display:

Java Exception Error

Try/Catch

Whenever we're dealing with different data types, we need to make sure we have some code that can catch the exceptions. To do this we use the try and catch blocks around our test.

Thus, the next example is a little more complex. In our main section, we will set up a string as an array of strings, with some strings and some integers. We also have a second function called checkMe, which performs the actual check. We will again use parseInt, but with a little different twist.

First, let's take a look at the code that checks if the string has any integers. The function checkMe accepts one parameter (a string), then uses the parseInt function and returns TRUE if the value really is an integer. If parseInt fails, it will throw an exception. We catch any exceptions in the catch block and do nothing. We could show an error there, but it's not necessary. The last piece of code passes back the check. Is it valid or not? Is it an integer or not?


public static boolean checkMe(String s) {
  boolean amIValid = false;
  try {
   Integer.parseInt(s);
   // s is a valid integer!
   amIValid = true;
  } catch (NumberFormatException e) {
   //sorry, not an integer
   // we just move on, but you could have code here
  }
  return invalid;
}


To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 200 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create An Account
Support