In Java, is a String an array of chars?

12,645

Solution 1

Strings are immutable objects representing a character sequence (CharSequence is one of the interfaces implemented by String). Main difference to char arrays and collections of chars: String cannot be modified, it's not possible (ignoring reflection) to add/remove/replace characters.

Internally they are represented by a char array with an offset and length (this allows to create lightweight substrings, using the same char arrays).

Example: ['F','o','o','H','e','l','l','o',' ','W','o','r','l','d'], offset=3, count=5 = "Hello".

Solution 2

strings are object of class String and it's not a Collection as well. It is implemented on top of char array. You can see it in the below code snippet:

public final class String implements 
        java.io.Serializable, Comparable<String>, CharSequence
    {           
    private final char value[];

Solution 3

No, it's not a collection in that it does not implement the Collection<E> interface.

Conceptually, it is an immutable sequence of characters (and implements the CharSequence interface).

Internally, the String class is likely to use an array of chars, although I am pretty sure the spec does not mandate that.

Solution 4

No it's not an Array or a Collection. However there is a convenient method if you need a char array and you have a String - namely String.toCharArray(); you could use it like this

    // Prints the String "Hello, World!" as a char[].
    System.out.println(Arrays.toString("Hello, World!".toCharArray()));

Solution 5

No, a String is an immutable string of characters, and the class extends Object directly and does not implement any of the Collection interfaces. Really, that's the basic answer.

However, there's a lot going on under the covers in the runtime--there's a whole collection of cached strings held by the JVM and in its most primitive representation, yeah, a String is basically an array of characters (meaning it's a bunch of memory addresses pointing to representations of characters). Still, once you go below the definition of String as it's defined as a class, you can keep going until you get to the point that you're just talking about organized combinations of ones and zeroes.

I'm guessing here, but I imagine you posed the question because you're studying this and an instructor said something about a String being an array of characters. While technically correct, that's really confusing because the two concepts exists at completely different levels of abstraction.

Share:
12,645
juju
Author by

juju

We'll get there, if there is there.

Updated on June 09, 2022

Comments

  • juju
    juju almost 2 years

    I want to know, if a String is a collection. I have read around but am still quite confused.