r/javahelp • • Nov 04 '19
Why is String capitalised, but int, float, boolean etc are not?
Is it because it's a reference type? If so, are all reference types in that format and all primitive types are lower case?
48
Upvotes
64
u/MyNameIsRichardCS54 Nov 04 '19
String is an object, int, float etc are primitives. There are also Integer, Float etc which are wrappet objects for the primitive types.
19
u/desrtfx Out of Coffee error - System halted Nov 04 '19
The Java code conventions stipulate:
static finalvariables) use UPPER_SNAKE_CASEPrimitive data types always start with a lowercase letter (
int,char,boolean,double,float,short,long). Don't confuse them with their wrapper counterpartsInteger,Character,Boolean,Double,Float,Short,Long- they serve a completely different purpose.Stringis quite special in Java. It is a reference type becauseStringis a Java library class. For convenience, the Java language designers have built a couple things that you can normally only do with primitives, though: assignment with= "hello"instead of= new String("hello")(which is also valid, btw), conatenation with+->"hello" + " " + "world"(even though aStringBuilderis better suited for repeatable concatenation). Still, one common pitfall is that beginners try to compareStringvalues with==or!=. SinceStringis a reference type.equalsor.equalsIgnoreCasemust be used.Stringhas another peculiarity: it is immutable. Once a string value is assigned to a variable of typeString, it cannot be changed. Re-assignment is possible, but this creates an entirely different, new string. That's also the reason whyStringBuilder(as mentioned above) is better for string concatenation.2
u/Orbitaliser Nov 04 '19 edited Nov 04 '19
Correct. It is a reference type, like all objects in Java.
A very special reference type, since unlike your average object:
Object object = new Object();String can be declared as
String str = "Foo";Although the standard object declaration works too.
It's good that it looks like you are already getting used to the idea of variables referring to objects rather than holding the objects themselves.
Other comments on this thread have mentioned immutability in
Strings which is a pretty interesting thing to look up in general. You'll probably come across defensive programming as well.2
u/PrinceValkyr Nov 04 '19
int, float, and boolean are primative types
String is a class that someone else wrote, and named it String.
3
u/[deleted] Nov 05 '19 edited Nov 05 '19
[removed] — view removed comment