Java: Get the contents of a given string as a character array
Write a Java program to get the contents of a given string as a character array.
Sample Solution:
Java Code:
// Define a public class named Exercise17.
public class Exercise17 {
// Define the main method.
public static void main(String[] args) {
// Declare and initialize a string variable.
String str = "This is a sample string.";
// Create a character array to hold copied characters.
// Copy characters 4 through 10 from the 'str' string to the 'arr' array.
// Start filling the 'arr' array from position 2.
char[] arr = new char[] { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' };
str.getChars(4, 10, arr, 2);
// Display the contents of the character array.
System.out.println("The char array equals \"" +
arr + "\"");
}
}
Sample Output:
The char array equals "[C@2a139a55"
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to get the contents of a given string as a byte array.
Next: Write a Java program to create a unique identifier of a given 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