EDIT as @KevinO pointed out, determining whether the name length or 4 is smaller solves issues that would cause exceptions. I updated to incorporate this input.
Depends on how you're trying to print it. You can use a for
loop and iterate starting at the 1st index of your String name
like so:
String name = "John";
for(int i = 1; i < Math.min(name.length(), 4); i++){
System.out.print(name.charAt(i));
}
Sample Run:
run:
ohn
BUILD SUCCESSFUL (total time: 0 seconds)
You could print out theCharacter
one at a time like:
System.out.print(name.charAt(1)); //print character at index 1
System.out.print(name.charAt(2)); //print character at index 2
System.out.print(name.charAt(3)); //print character at index 3
This might be unsafe because you're not sure if the name will in be in fact at least 4 Characters
long.
Sample run:
run:
ohn
BUILD SUCCESSFUL (total time: 0 seconds)
Or perhaps the easiest way which is also safe, you could print it out using String.substring()
which takes in a range, like so:
System.out.println(name.substring(1, Math.min(name.length(), 4)));
This results in:
run:
ohn
BUILD SUCCESSFUL (total time: 0 seconds)