11

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?

Esteemator
  • 107
  • 7
Raiden Worley
  • 394
  • 1
  • 4
  • 14
  • 2
    Can you list all the types you've run across? Your statement would only be true if you'd *only* ever used the primitive types (and unconventionally named types outside the JRE). – Jon Skeet May 22 '13 at 22:47
  • I really only have used primitives. Although I didn't know that `double` is a primitive. – Raiden Worley May 22 '13 at 23:32

3 Answers3

16

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.

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
3

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.

Hirsh
  • 186
  • 1
  • 8
1

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.

gparyani
  • 1,958
  • 3
  • 26
  • 39
zw324
  • 26,764
  • 16
  • 85
  • 118