Issue
Why is it only done like
char c = 'A';
Character.toLowerCase(c);
and not..
char c = 'A';
c.toLowerCase();
I find this very confusing and don't know where I can find more information about why this happens or why it's necessary.
Solution
tl;dr
char type is a primitive, and primitives do not have methods.
Furthermore, char is obsolete. Use code point integer numbers instead when working with individual characters.
Character.toString(
Character.toLowerCase( // Takes a code point integer number.
"A".codePointAt( 0 ) // Annoying zero-based index numbering.
) // Returns another code point integer number.
) // Returns a `String` containing a single character.
a
Primitive versus Object
You said:
I find this very confusing
You need to learn the difference between the two categories of types in Java:
- primitive
- object
You said:
where I can find more information
See the Java Tutorial provided by Oracle free of cost. See Primitive Data Types and What is an Object?.
And search Stack Overflow for "java primitive".
Only objects have methods
The char type is a primitive. So it has no methods. Only objects have methods.
The Character class provides a static method toLowerCase which takes a char primitive value as its argument.
You asked:
why it's necessary
Primitives are not object-oriented. Primitives were originally included in Java to make porting of C code easier, an ability considered quite important back in those days.
char is obsolete
You should know that the char type has been obsolete since Java 2, and legacy since Java 5. As a 16-bit value, char is physically incapable of representing most characters — essentially broken.
Code point
Instead, use code point integer numbers.
The code point for LATIN CAPITAL LETTER A is 65 decimal, 41 hexadecimal.
Get the code point of a character.
int codePoint = "A".codePointAt( 0 ) ;
Get a String containing the character for a code point.
String s = Character.toString( codePoint ) ;
To get lowercase version of a character being represented by its code point.
int lowerCaseCodePoint = Character.toLowerCase( codePoint ) ;
String lowerCaseLetter = Character.toString( lowerCaseCodePoint ) ;
Dump to console.
System.out.println( "codePoint: " + codePoint ) ;
System.out.println( "s: " + s ) ;
System.out.println( "lowerCaseCodePoint: " + lowerCaseCodePoint ) ;
System.out.println( "lowerCaseLetter: " + lowerCaseLetter ) ;
See this code run live at IdeOne.com.
codePoint: 65
s: A
lowerCaseCodePoint: 97
lowerCaseLetter: a
Answered By - Basil Bourque Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.