Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java Character.toUpperCase/toLowerCase has no Locale parameter like String.toUpperCase/toLowerCase

I am wondering that why Character.toUpperCase/toLowerCase has no Locale parameter like String.toUpperCase/toLowerCase.

I have to first uppercase of a text that can be in Any language. I have 2 solutions:

  1. Use Character.toUpperCase

    String text = "stack overflow";
    StringBuilder sb = new StringBuilder(text);   
    
    sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); // No Locale parameter here.
    
    String out = sb.toString(); //Out: Stack overflow
    
  2. Use String.toUpperCase

    Locale myLocale = new Locale(locateId);
    
    String text = "stack overflow";
    String text1 = text.substring(0,1).toUpperCase(myLocale );
    String text2 = text.substring(1);
    
    String out = text1 + text2; // Out: Stack overflow
    

For my Locale. Both way has the same result.

My question is:

  • Since the text can be in any language. Which way should I use?

  • Why Character.toUpperCase/toLowerCase has no Locale parameter because there is not much difference between Character.toUpperCase/toLowerCase and String.toUpperCase/toLowerCase because String is array of Characters.

like image 593
Loc Avatar asked Oct 22 '14 18:10

Loc


People also ask

What does character toUpperCase do in java?

Java String toUpperCase() Method The toUpperCase() method converts a string to upper case letters. Note: The toLowerCase() method converts a string to lower case letters.

Does toUpperCase work on characters?

toUpperCase() can be used to map the characters into uppercase. There are various benefits of String case mapping as compared to Character case mapping. String case mapping can be used to perform local-sensitive mappings, context-sensitive mappings whereas the Character case mapping cannot be used.

What is toUpperCase Locale root?

toUpperCase(Locale locale) method converts all of the characters in this String to upper case using the rules of the given Locale.

What is toLowerCase Locale root?

Java String: toLowerCase() Method The toLowerCase() method converts all of the characters in this String to lower case using the rules of the default locale. This is equivalent to calling toLowerCase(Locale.


1 Answers

As the Javadoc says:

In general, String.toUpperCase() should be used to map characters to uppercase. String case mapping methods have several benefits over Character case mapping methods. String case mapping methods can perform locale-sensitive mappings, context-sensitive mappings, and 1:M character mappings, whereas the Character case mapping methods cannot.

So use String.toUppercase()

like image 150
dkatzel Avatar answered Oct 09 '22 23:10

dkatzel