Re: trying to figure things out about chars
JT wrote:
I have a very simple program which won't compile.
/**
*
*/
package data;
import java.lang.Character;
public class MyStringsAndChars {
public static void main(String[] args) {
char c = 'Y';
char c1 = c.toLowerCase();
}
}
Of course the obvious problem is that the compiler can't tell what I
mean by c.toLowerCase();
[...]
Can anyone tell me what I did wrong? How do I use the toLowerCase
method of the java.lang.char package to convert a character to lower case?
A `char' is a "primitive," like an `int' or a `double'.
Primitives have no methods; only classes have methods.
The class that has the method you are trying to use is
named Character, and you can use the method like this:
char c1 = Character.toLowerCase(c);
There are two things to observe about this call. First,
you must name the class explicitly; it cannot be inferred
from `c' because `c' is not a reference to an object. Second,
you pass `c' as an argument value; you can't pass it implicitly
with `c.something' because `c' is not a reference to an object.
If you look a little deeper you'll find that toLowerCase()
is a `static' method of the class Character, meaning that it
is not associated with any particular instance of Character.
(Indeed, you'll find that it's not even possible to create an
instance of Character in the first place!) Since toLowerCase()
is not tied to an object instance, it has no `this' to operate
on -- that's another reason you pass `c' as an argument.
You could use toLowerCase() as shown above, but in your
situation this is unnecessary because you've already converted
the entire original String to lower case:
> String palindrome = "Dott saw I was Tod".toLowerCase();
Despite the similarity of names, this is not the same method
as the one you're having trouble with. This one is an "instance"
(non-`static') method of the class String, and operates on a String
object that it can refer to as `this'. The other is a `static'
method of the class Character, with no notion of `this'.
--
Eric Sosman
esosman@acm-dot-org.invalid