BufBills
BufBills

Reputation: 8103

Is an array of char equivalent to String in Java?

Is an array of char equivalent to String in Java?

I saw this:

Q3. Why String has length() method?

The backup data structure of a String is a char array. There is no need to define a field that is not necessary for every application. Unlike C, an Array of characters is not a String in Java.

(source)

But it does not explain it clearly.

Upvotes: 0

Views: 163

Answers (3)

Durandal
Durandal

Reputation: 20059

The type java.lang.String provides a standardized API and also guarantees that the value of an existing String object cannot be changed; aka it is immutable. There is no need to know how the String class actually stores the string value (and it has, in fact undergone various changes in how its actually implemented over the years - while there is actually a char[] under the hood; that is just one choice of implementation and could be exchanged for anything else without changing the visible functionality of the String class).

Whereas a char[] array is just a low level primitive data structure, the values at any index of the array can be changed at any time. There's also no specialized API provided by char[] (e.g. no subString-method etc). A character array just provides raw storage space with very little semantics enforced.

So, aside the fact that both can represent a sequence of characters, they have not the same purpose and they are certainly no interchangable or the same.

Upvotes: 4

Chong Tang
Chong Tang

Reputation: 2146

They are absolutely NOT same.

A string in Java has data type String. And an array of chars has data type of "array of chars".

Like Makoto said, String is immutable, but array is not. So we construct a String with StringBuilder usually.

Upvotes: 0

Makoto
Makoto

Reputation: 106389

An array of characters is not a String, for one distinct reason: arrays are mutable, whereas a String is explicitly not. It's also the case that the array backing a String isn't null-terminated.

It is most certainly backed by a char[], but that doesn't mean that the two objects are equivalent.

Upvotes: 5

Related Questions