w3resource

Java: Get the contents of a given string as a character array


17. Get Char Array from String

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:

Flowchart: Java String  Exercises - Get the contents of a given string as a character array


For more Practice: Solve these Related Problems:

  • Write a Java program to convert a string to a character array and then sort the array alphabetically.
  • Write a Java program to convert a string to a char array and count the frequency of each character.
  • Write a Java program to convert a string to a char array and then reverse the array in place.
  • Write a Java program to convert a string to a character array and then replace every vowel with a specific character.

Go to:


PREV : Get Byte Array from String.
NEXT : Generate Hash from String.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.