Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capitalize the first letter of a String in Java?

I am using Java to get a String input from the user. I am trying to make the first letter of this input capitalized.

I tried this:

String name;  BufferedReader br = new InputStreamReader(System.in);  String s1 = name.charAt(0).toUppercase());  System.out.println(s1 + name.substring(1)); 

which led to these compiler errors:

  • Type mismatch: cannot convert from InputStreamReader to BufferedReader

  • Cannot invoke toUppercase() on the primitive type char

like image 748
sumithra Avatar asked Oct 11 '10 08:10

sumithra


People also ask

How do you capitalize the first letter of a string?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.

How do you uppercase a string in Java?

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

How do you capitalize the first and last letter in Java?

You simply need to take part after first and before last letter and add it to your upper-versions of first and last characters.


1 Answers

String str = "java"; String cap = str.substring(0, 1).toUpperCase() + str.substring(1); // cap = "Java" 

With your example:

public static void main(String[] args) throws IOException {     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));     // Actually use the Reader     String name = br.readLine();     // Don't mistake String object with a Character object     String s1 = name.substring(0, 1).toUpperCase();     String nameCapitalized = s1 + name.substring(1);     System.out.println(nameCapitalized); } 
like image 176
Rekin Avatar answered Oct 08 '22 13:10

Rekin