Java program to print character at given index in a given string
Following program shows you how to print character at given index in a given string.
import java.util.Scanner;
public class StringOperations8 {
public static void main(String[] args) {
String input;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a string:");
input = in.nextLine();
int length = input.length();
System.out.println("Please enter an index between 0 to " + (length - 1));
int index = in.nextInt();
if (index < 0 || index >= length) {
System.out.println("Invalid input");
} else {
System.out.println("Character at given position is: " + input.charAt(index));
}
}
}
Output:
Please enter a string:
hello
Please enter an index between 0 to 4
1
Character at given position is: e