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 IndexOutOfBoundsExcept
Use the substring method, as follows:
int n = 8;
String s = "Hello, World!";
System.out.println(s.substring(0,n);
If n is greater than the length of the string, this will throw an exception, as one commenter has pointed out. one simple solution is to wrap all this in the condition if(s.length()else clause, you can choose whether you just want to print/return the whole String or handle it another way.