Java Java Objects Delivering the MVP Validating and Normalizing User Input

Brendan Passey
Brendan Passey
999 Points

I'm noticing a trend with String methods

I've noticed that with seemingly all of the string methods I use I am able to call the method directly off the string object it's self, often without having to pass in an argument. eg example.toLowerCase(); Where as when working with chars and ints I have to call the method off the wrapper class Integer or Character then pass the object I want to work with in as an argument eg Character.isLetter(guess);

I have also noticed that string is the only type that uses an upper case first letter when declaring objects and I suspect it has a lot to do with this. I remember Craig touched on this very early on saying something like "String is different to the other types as it's the only one we don't really use the primitive type for" or something like that but didn't go into it as it was way above my head at the time.

Am I talking any sense? I'm the kind of guy who generally doesn't like moving on and leaving some things unlearned till a later time. Can someone explain why String is unique in this way or is it way above my current learning?

2 Answers

saykin
saykin
9,820 Points

Someone more experienced probably has a better and/or simpler explanation, but since String variables itself are objects, you can call it's helper methods just by using the variable it self. This is because String is just a sequence of the primitive char put together for us.

While int, char, boolean and etc (primitive types) aren't considered Objects which is why you have to pass on the variable to the wrapper Class to process whatever you want to process.

I hope this made it a bit more clear.

Brendan Passey
Brendan Passey
999 Points

Great answer, makes a lot of sense.

Brendan Passey
Brendan Passey
999 Points

I've had a click moment, thanks a lot. Can I infer that String has no primitive type as it is just a bunch of chars linked together in an object for me?

saykin
saykin
9,820 Points

You could say that. There's some info on why it isn't one, but it mostly comes down to efficiency (CPU's are made to handle the primitive data types nativley) and how String can vary in size while primitives has a max value they can be. Example, int can be a max value of 2,147,483,647.