How do I get the first n characters of a string without checking the size or going out of bounds?

antony.trupe picture antony.trupe · Oct 18, 2009 · Viewed 265.8k times · Source

How do I get up to the first n characters of a string in Java without doing a size check first (inline is acceptable) or risking an IndexOutOfBoundsException?

Answer

Stephen C picture Stephen C · Oct 18, 2009

Here's a neat solution:

String upToNCharacters = s.substring(0, Math.min(s.length(), n));

Opinion: while this solution is "neat", I think it is actually less readable than a solution that uses if / else in the obvious way. If the reader hasn't seen this trick, he/she has to think harder to understand the code. IMO, the code's meaning is more obvious in the if / else version. For a cleaner / more readable solution, see @paxdiablo's answer.