Java <- StackOverflow top 71

1: How do I convert a String to an int in Java? (score 5767039 in 2018)

Question

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.

Answer accepted (score 3924)

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:

Answer 2 (score 647)

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.

Answer 3 (score 233)

Well, a very important point to consider is that the Integer parser throws NumberFormatException as stated in Javadoc.

It is important to handle this exception when trying to get integer values from split arguments or dynamically parsing something.

2: How do I declare and initialize an array in Java? (score 4290819 in 2017)

Question

How do I declare and initialize an array in Java?

Answer accepted (score 2539)

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:

The third way of initializing is useful when you declare the array first and then initialize it. The cast is necessary here.

Answer 2 (score 259)

There are two types of array.

One Dimensional 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.

Multidimensional array
Declaration

Or

Or

Initialization

Or

Ragged Array (or Non-rectangular Array)

So here we are defining columns explicitly.
Another Way:

For Accessing:

Alternatively:

Ragged arrays are multidimensional arrays.
For explanation see multidimensional array detail at the official java tutorials

Answer 3 (score 122)

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.

3: How do I generate random integers within a specific range in Java? (score 3879757 in 2019)

Question

How do I generate a random int value in a specific range?

I have tried the following, but those do not work:

Attempt 1:

Attempt 2:

Answer 2 (score 3665)

In Java 1.7 or later, the standard way to do this is as follows:

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:

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.

Answer 3 (score 1393)

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]:

4: How to split a string in Java (score 3688160 in 2018)

Question

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?

Answer accepted (score 2767)

Just use the appropriate method: String#split().

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().

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 ?&lt;= group on the pattern.

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.

If you’d like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of split() method.

Answer 2 (score 72)

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:

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