问题
In Java, when one declares a string variable the word "String" is capitalized, yet it isn't in any of the other types I've run across (e.g. "int" or "double"). Why is this? Was it just some weird arbitrary decision by the designers?
回答1:
Why does is declaration of a string variable in Java capitalized?
The String
type is capitalized because it is a class, like Object
, not a primitive type like boolean
or int
(the other types you probably ran across).
As a class, the String
follows the Naming Convention for Java proposed by Sun. In short, that coding style dictates that UpperCamelCase be used for classes ("Class names should be nouns, in mixed case with the first letter of each internal word capitalized") and lowerCamelCase be used for instances and methods.
What's the basic difference between String
and the primitive types?
As an object, a String
has some advantages, like properties and methods that can be called directly to them (like the famous length()
, replace()
and split()
). None of the primitive types have that.
What about wrapper classes?
The other primitive types have equivalent wrapper classes, like Integer
for int
and Boolean
for boolean
. They will allow you additional functions.
Since Java 1.5, the conversion from an int
to an Integer
is made almost seamlessly. This is called autoboxing.
回答2:
Strings are objects, similar to any that you can create, yet the reside in the top of the classes in Java. Really a string is just an array of characters, and this is commonly how they are used in lower level programming languages.
回答3:
Because String
is the class java.lang.String
, while int
, double
, boolean
, etc. are primitives. The first letter in the name of a class should be capitalized by convention.
来源:https://stackoverflow.com/questions/16702781/why-is-declaration-of-a-string-variable-in-java-capitalized