Java: Get the character at the given index within the String
Write a Java program to get the character at the given index within the string.
Visualal Presentation:
Sample Solution:
Java Code:
// Define a public class named Exercise1.
public class Exercise1 {
// Define the main method.
public static void main(String[] args) {
// Declare and initialize a string variable "str" with the value "Java Exercises!".
String str = "Java Exercises!";
// Print the original string.
System.out.println("Original String = " + str);
// Get the character at positions 0 and 10.
int index1 = str.charAt(0); // Get the ASCII value of the character at position 0.
int index2 = str.charAt(10); // Get the ASCII value of the character at position 10.
// Print out the results.
System.out.println("The character at position 0 is " +
(char)index1); // Print the character at position 0 by converting ASCII value to char.
System.out.println("The character at position 10 is " +
(char)index2); // Print the character at position 10 by converting ASCII value to char.
}
}
Sample Output:
Original String = Java Exercises! The character at position 0 is J The character at position 10 is i
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to retrieve the character at a given index from a string, and display a custom message if the index is out of range.
- Write a Java program to extract the first, middle, and last characters of a user-provided string without using helper methods.
- Write a Java program to select a character from a string at an index generated randomly within its valid range.
- Write a Java program to print characters located at indices corresponding to Fibonacci numbers from the given string.
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Java string Exercises.
Next: Write a Java program to get the character at the given index within the String.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics