I've been going through Sun Microsystem's Java Tutorial and got some questions while reading the following:
I/O from the Command Line: The Console Object
"Second, readPassword returns a character array, not a String, so the password can be overwritten, removing it from memory as soon as it is no longer needed."
My questions are:
1) With regard to other data types, such as value data types(int, float, boolean etc), and reference types(user-defined objects, etc), how are arrays and Strings in Java different?
2) Can you elaborate on the above statement about character array and String?
P.S:
Clarification to Q1: What I wanted to ask on Q1 was more about what arrays and Strings are as data-types in Java… With their object-like attributes, I get easily confused when someone claims that Strings and Arrays are not objects in a strict sense…
Best Answer
At a practical level, the main difference between
String
andchar[]
is that the instances of the former are immutable, and instances of the latter are mutable. And of course, the String API offers a wide range of useful methods string manipulation methods.So lets talk about the linguistic similarities and differences.
First and foremost, (notwithstanding what you may have heard) strings and array instances in Java are both objects. According to the Java Language Specification:
... where the class of a string is
java.lang.String
.The linguistic distinction between arrays and other object types is that the type of an array is not a normal Java class. For example:
But all array types are (direct) subtypes of
java.lang.Object
, which means that you can (for example) assign an array to a variable of typeObject
, and invoke methods in the Object API. (And there are some interesting things that you can do with these methods to demonstrate the "object-ness" of an array ... but I digress)So what about strings? As mentioned above, a "string" is a normal object which is an instance of the class
java.lang.String
. There is nothing unusual about this class from a linguistic perspective. It is declared as "final" so that you cannot declare subtypes, but that is not unusual.The thing that makes
String
a bit special compared with other classes is that the Java language provides some linguistic constructs to support strings:String
literal syntax for obtaining strings whose content can be determined at compile time.String
concatenation.switch
statement supports switching onString
values.concat
method, that string literals are "interned".By the way, the answer that said that all string instances are held in a string pool is incorrect. Strings are only put in the pool when they interned, and this only happens automatically for string literals and for strings whose values can be calculated at compile-time. (You can force a string instance to be interned by calling the
String.intern()
method, but this is bit expensive, and not generally a good idea.)