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
.
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:
(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:
For example, here are two ways:
There is a slight difference between these methods:
valueOf
returns a new or cached instance of java.lang.Integer
parseInt
returns primitive int
.
The same is for all cases: Short.valueOf
/parseShort
, Long.valueOf
/parseLong
, etc.
Well, a very important point to consider is that the Integer parser throws NumberFormatException as stated in Javadoc.
int foo;
String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
try {
foo = Integer.parseInt(StringThatCouldBeANumberOrNot);
} catch (NumberFormatException e) {
//Will Throw exception!
//do something! anything to handle the exception.
}
try {
foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);
} catch (NumberFormatException e) {
//No problem this time, but still it is good practice to care about exceptions.
//Never trust user input :)
//Do something! Anything to handle the exception.
}
It is important to handle this exception when trying to get integer values from split arguments or dynamically parsing something.
How do I declare and initialize an array in Java?
You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).
For primitive types:
For classes, for example String
, it’s the same:
String[] myStringArray = new String[3];
String[] myStringArray = {"a", "b", "c"};
String[] myStringArray = new String[]{"a", "b", "c"};
The third way of initializing is useful when you declare the array first and then initialize it. The cast is necessary here.
There are two types of array.
Syntax for default values:
Or (less preferred)
Syntax with values given (variable/field initialization):
Or (less preferred)
Note: For convenience int[] num is preferable because it clearly tells that you are talking here about array. Otherwise no difference. Not at all.
Or
Or
Or
So here we are defining columns explicitly.
Another Way:
Alternatively:
Ragged arrays are multidimensional arrays.
For explanation see multidimensional array detail at the official java tutorials
Type[] variableName = new Type[capacity];
Type[] variableName = {comma-delimited values};
Type variableName[] = new Type[capacity];
Type variableName[] = {comma-delimited values};
is also valid, but I prefer the brackets after the type, because it’s easier to see that the variable’s type is actually an array.
How do I generate a random int
value in a specific range?
I have tried the following, but those do not work:
Attempt 1:
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Attempt 2:
In Java 1.7 or later, the standard way to do this is as follows:
import java.util.concurrent.ThreadLocalRandom;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize a java.util.Random instance, which can be a source of confusion and error if used inappropriately.
However, conversely there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar. In those situations, the pre-Java 1.7 technique shown below can be used.
Before Java 1.7, the standard way to do this is as follows:
import java.util.Random;
/**
* Returns a pseudo-random number between min and max, inclusive.
* The difference between min and max can be at most
* <code>Integer.MAX_VALUE - 1</code>.
*
* @param min Minimum value
* @param max Maximum value. Must be greater than min.
* @return Integer between min and max, inclusive.
* @see java.util.Random#nextInt(int)
*/
public static int randInt(int min, int max) {
// NOTE: This will (intentionally) not run as written so that folks
// copy-pasting have to think about how to initialize their
// Random instance. Initialization of the Random instance is outside
// the main scope of the question, but some decent options are to have
// a field that is initialized once and then re-used as needed or to
// use ThreadLocalRandom (if using at least Java 1.7).
//
// In particular, do NOT do 'Random rand = new Random()' here or you
// will get not very good / not very random results.
Random rand;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
See the relevant JavaDoc. In practice, the java.util.Random class is often preferable to java.lang.Math.random().
In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.
Note that this approach is more biased and less efficient than a nextInt
approach, https://stackoverflow.com/a/738651/360211
One standard pattern for accomplishing this is:
The Java Math library function Math.random() generates a double value in the range [0,1)
. Notice this range does not include the 1.
In order to get a specific range of values first, you need to multiply by the magnitude of the range of values you want covered.
This returns a value in the range [0,Max-Min)
, where ‘Max-Min’ is not included.
For example, if you want [5,10)
, you need to cover five integer values so you use
This would return a value in the range [0,5)
, where 5 is not included.
Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.
You now will get a value in the range [Min,Max)
. Following our example, that means [5,10)
:
But, this still doesn’t include Max
and you are getting a double value. In order to get the Max
value included, you need to add 1 to your range parameter (Max - Min)
and then truncate the decimal part by casting to an int. This is accomplished via:
And there you have it. A random integer value in the range [Min,Max]
, or per the example [5,10]
:
I have a string, "004-034556"
, that I want to split into two strings:
That means the first string will contain the characters before '-'
, and the second string will contain the characters after '-'
. I also want to check if the string has '-'
in it. If not, I will throw an exception. How can I do this?
Just use the appropriate method: String#split()
.
String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
Note that this takes a regular expression, so remember to escape special characters if necessary.
there are 12 characters with special meanings: the backslash\
, the caret^
, the dollar sign$
, the period or dot.
, the vertical bar or pipe symbol|
, the question mark?
, the asterisk or star*
, the plus sign+
, the opening parenthesis(
, the closing parenthesis)
, and the opening square bracket[
, the opening curly brace{
, These special characters are often called “metacharacters”.
So, if you want to split on e.g. period/dot .
which means “any character” in regex, use either backslash \
to escape the individual special character like so split("\\.")
, or use character class []
to represent literal character(s) like so split("[.]")
, or use Pattern#quote()
to escape the entire string like so split(Pattern.quote("."))
.
To test beforehand if the string contains certain character(s), just use String#contains()
.
if (string.contains("-")) {
// Split it.
} else {
throw new IllegalArgumentException("String " + string + " does not contain -");
}
Note, this does not take a regular expression. For that, use String#matches()
instead.
If you’d like to retain the split character in the resulting parts, then make use of positive lookaround. In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing ?<=
group on the pattern.
String string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556
In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing ?=
group on the pattern.
String string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556
If you’d like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of split()
method.
An alternative to processing the string directly would be to use a regular expression with capturing groups. This has the advantage that it makes it straightforward to imply more sophisticated constraints on the input. For example, the following splits the string into two parts, and ensures that both consist only of digits:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class SplitExample
{
private static Pattern twopart = Pattern.compile("(\\d+)-(\\d+)");
public static void checkString(String s)
{
Matcher m = twopart.matcher(s);
if (m.matches()) {
System.out.println(s + " matches; first part is " + m.group(1) +
", second part is " + m.group(2) + ".");
} else {
System.out.println(s + " does not match.");
}
}
public static void main(String[] args) {
checkString("123-4567");
checkString("foo-bar");
checkString("123-");
checkString("-4567");
checkString("123-4567-890");
}
}
As the pattern is fixed in this instance, it can be compiled in advance and stored as a static member (initialised at class load time in the example). The regular expression is:
The parentheses denote the capturing groups; the string that matched that part of the regexp can be accessed by the Match.group() method, as shown. The