Java question...

gopunk

Lifer
Jul 7, 2001
29,239
2
0
why do methods for the Character class such as getNumericValue and isDigit require an input of a character? isn't there already a character, the one that instantiates the Character class? i guess i just don't see why we would have to type something like (where c is a Character):

c.isDigit(c);

to check if c is a digit, intead of just typing:

c.isDigit();

am i missing something here?

thanks :)
 

manly

Lifer
Jan 25, 2000
11,744
2,706
136
Those methods are static. You would normally invoke them in a static context, i.e.

Character.isDigit(someChar)

While it's possible to do c.isDigit(someChar) as you suggested, that style would obscure the code (because you're invoking a static method, but in a style that implies an instance method). The benefit of the utility method being static is that it can operate on any number of chars you pass in without having to instantiate Character instances.

In fact, when a class contains only static utility methods, it is best that it NOT be possible to instantiate the class. For example, java.lang.Math and java.util.Collections both have private constructors.
 

gopunk

Lifer
Jul 7, 2001
29,239
2
0
Originally posted by: manly
Those methods are static. You would normally invoke them in a static context, i.e.

Character.isDigit(someChar)

While it's possible to do c.isDigit(someChar) as you suggested, that style would obscure the code (because you're invoking a static method, but in a style that implies an instance method). The benefit of the utility method being static is that it can operate on any number of chars you pass in without having to instantiate Character instances.

In fact, when a class contains only static utility methods, it is best that it NOT be possible to instantiate the class. For example, java.lang.Math and java.util.Collections both have private constructors.

ah.... okay. i was confused because i tried it with just isDigit(c) and it didn't work, so i thought i had to instantiate the class. cool. thanks :)
 

manly

Lifer
Jan 25, 2000
11,744
2,706
136
Originally posted by: gopunk

ah.... okay. i was confused because i tried it with just isDigit(c) and it didn't work, so i thought i had to instantiate the class. cool. thanks :)
Actually, c.isDigit(someChar) would work, but it's highly confusing. When you've instantiated a Character c and call static methods on the instance, the value of c is irrelevant. What is important is the value of argument someChar that is passed in. So in short, always call static methods using the class name to clarify your intent.