491

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

4
  • 2
    @Pontus - I disagree. For the input "abcd", the OP wants the output "Abcd". It seems pretty clear, although the question could have been better.
    – Kobi
    Oct 11, 2010 at 8:26
  • stackoverflow.com/questions/1892765/…
    – jmj
    Oct 11, 2010 at 9:06
  • character is a primitive data type in Java. You cannot dereference a primitive data type with dot(.) operator. You have to substring the first character by name.substring(0,1); Dec 18, 2018 at 5:00
  • Warning: In Turkic Alphabet the lowcase character i have two different upcase-letters, depending of the word that is meant. See en.wikipedia.org/wiki/Dotted_and_dotless_I
    – Grim
    Jan 6, 2021 at 5:55

59 Answers 59

1
2
2
public static String capitalizer(final String texto) {

    // split words
    String[] palavras = texto.split(" ");
    StringBuilder sb = new StringBuilder();

    // list of word exceptions
    List<String> excessoes = new ArrayList<String>(Arrays.asList("de", "da", "das", "do", "dos", "na", "nas", "no", "nos", "a", "e", "o", "em", "com"));

    for (String palavra : palavras) {

        if (excessoes.contains(palavra.toLowerCase()))
            sb.append(palavra.toLowerCase()).append(" ");
        else
            sb.append(Character.toUpperCase(palavra.charAt(0))).append(palavra.substring(1).toLowerCase()).append(" ");
    }
    return sb.toString().trim();
}
2

You can use the following code:

public static String capitalizeString(String string) {

    if (string == null || string.trim().isEmpty()) {
        return string;
    }
    char c[] = string.trim().toLowerCase().toCharArray();
    c[0] = Character.toUpperCase(c[0]);

    return new String(c);

}

example test with JUnit:

@Test
public void capitalizeStringUpperCaseTest() {

    String string = "HELLO WORLD  ";

    string = capitalizeString(string);

    assertThat(string, is("Hello world"));
}

@Test
public void capitalizeStringLowerCaseTest() {

    String string = "hello world  ";

    string = capitalizeString(string);

    assertThat(string, is("Hello world"));
}
2
System.out.println(Character.toString(A.charAt(0)).toUpperCase()+A.substring(1));

P.S = a is a string.

1
  • 2
    Alternately (using str instead of A which looks like a class name): str.substring(0,1).toUpperCase()+str.substring(1);
    – Paul
    Feb 13, 2021 at 21:29
2

Yet another example, how you can make the first letter of the user input capitalized:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String string = br.readLine();
// handle supplementary characters
IntStream.concat(
        IntStream.of(string.codePointAt(0))
                .map(Character::toUpperCase), string.codePoints().skip(1)
)
.forEach(cp -> System.out.print(Character.toChars(cp)));
0
2

Since you first get Char from your original string. You cant use String properties on char so just use to upper first and then use charAt

String s1 = name.toUppercase().charAt(0);
2
  • 1
    You can't convert from char to String this way. Your answer would result in an additional type mismatch. Additional because of assigning InputStreamReader to BufferedReader won't work. I suggest to look at the other answers.
    – Alex_M
    Feb 9, 2022 at 22:38
  • Suggest using Character.toUpperCase() after charAt() because in this case you are capitalizing a single character instead of capitalizing the entire string and only using the first character, offering better performance. Feb 12 at 2:02
2

You can use substrings for simple hacks ;).

String name;
    
String s1 = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());

System.out.println(s1));
1

Many of the answers are very helpful so I used them to create a method to turn any string to a title (first character capitalized):

static String toTitle (String s) {
      String s1 = s.substring(0,1).toUpperCase();
      String sTitle = s1 + s.substring(1);
      return sTitle;
 }
1

Just reworked Jorgesys code and added few checks because of few cases related to String length. Don't do for null reference check in my case.

 public static String capitalizeFirstLetter(@NonNull String customText){
        int count = customText.length();
        if (count == 0) {
            return customText;
        }
        if (count == 1) {
            return customText.toUpperCase();
        }
        return customText.substring(0, 1).toUpperCase() + customText.substring(1).toLowerCase();
    }
1

To capitalize first character of each word in a string ,

first you need to get each words of that string & for this split string where any space is there using split method as below and store each words in an Array. Then create an empty string. After that by using substring() method get the first character & remaining character of corresponding word and store them in two different variables.

Then by using toUpperCase() method capitalize the first character and add the remaianing characters as below to that empty string.

public class Test {  
     public static void main(String[] args)
     {
         String str= "my name is khan";        // string
         String words[]=str.split("\\s");      // split each words of above string
         String capitalizedWord = "";         // create an empty string

         for(String w:words)
         {  
              String first = w.substring(0,1);    // get first character of each word
              String f_after = w.substring(1);    // get remaining character of corresponding word
              capitalizedWord += first.toUpperCase() + f_after+ " ";  // capitalize first character and add the remaining to the empty string and continue
         }
         System.out.println(capitalizedWord);    // print the result
     }
}
0
1

The code i have posted will remove underscore(_) symbol and extra spaces from String and also it will capitalize first letter of every new word in String

private String capitalize(String txt){ 
  List<String> finalTxt=new ArrayList<>();

  if(txt.contains("_")){
       txt=txt.replace("_"," ");
  }

  if(txt.contains(" ") && txt.length()>1){
       String[] tSS=txt.split(" ");
       for(String tSSV:tSS){ finalTxt.add(capitalize(tSSV)); }  
  }

  if(finalTxt.size()>0){
       txt="";
       for(String s:finalTxt){ txt+=s+" "; }
  }

  if(txt.endsWith(" ") && txt.length()>1){
       txt=txt.substring(0, (txt.length()-1));
       return txt;
  }

  txt = txt.substring(0,1).toUpperCase() + txt.substring(1).toLowerCase();
  return txt;
}
0
1

One of the answers was 95% correct, but it failed on my unitTest @Ameen Maheen's solution was nearly perfect. Except that before the input gets converted to String array, you have to trim the input. So the perfect one:

private String convertStringToName(String name) {
        name = name.trim();
        String[] words = name.split(" ");
        StringBuilder sb = new StringBuilder();
        if (words[0].length() > 0) {
            sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
            for (int i = 1; i < words.length; i++) {
                sb.append(" ");
                sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
            }
        }
        return sb.toString();
    }
1
  • This looks like the most simple solution!!
    – J. Doe
    May 6, 2021 at 13:39
1

Given answers is for capitalize the first letter of one word only. use following code to capitalize a whole string.

public static void main(String[] args) {
    String str = "this is a random string";
    StringBuilder capitalizedString = new StringBuilder();
    String[] splited = str.trim().split("\\s+");

    for (String string : splited) {         
        String s1 = string.substring(0, 1).toUpperCase();
        String nameCapitalized = s1 + string.substring(1);

        capitalizedString.append(nameCapitalized);
        capitalizedString.append(" ");
    }
    System.out.println(capitalizedString.toString().trim());
}

output : This Is A Random String

1

Use replace method.

String newWord = word.replace(String.valueOf(word.charAt(0)), String.valueOf(word.charAt(0)).toUpperCase());
0

Following example also capitalizes words after special characters such as [/-]

  public static String capitalize(String text) {
    char[] stringArray = text.trim().toCharArray();
    boolean wordStarted = false;
    for( int i = 0; i < stringArray.length; i++) {
      char ch = stringArray[i];
      if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '\'') {
        if( !wordStarted ) {
          stringArray[i] = Character.toUpperCase(stringArray[i]);
          wordStarted = true;
        } 
      } else {
        wordStarted = false;
      }
    }
    return new String(stringArray);
  }

Example:
capitalize("that's a beautiful/wonderful life we have.We really-do")

Output:
That's A Beautiful/Wonderful Life We Have.We Really-Do
0

thanks I have read some of the comments and I came with the following

public static void main(String args[]) 
{
String myName = "nasser";
String newName = myName.toUpperCase().charAt(0) +  myName.substring(1);
System.out.println(newName );
}

I hope its helps good luck

0
0

The answer from Ameen Mahheen is good but if we have some string with double space, like "hello world" then sb.append gets IndexOutOfBounds Exception. Right thing to do is teste before this line, doing:

private String capitalizer(String word){
        String[] words = word.split(" ");
        StringBuilder sb = new StringBuilder();
        if (words[0].length() > 0) {
            sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
            for (int i = 1; i < words.length; i++) {
                sb.append(" ");
                if (words[i].length() > 0) sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
            }
        }
        return  sb.toString();
    }
0

You may try this

/**
 * capitilizeFirst(null)  -> ""
 * capitilizeFirst("")    -> ""
 * capitilizeFirst("   ") -> ""
 * capitilizeFirst(" df") -> "Df"
 * capitilizeFirst("AS")  -> "As"
 *
 * @param str input string
 * @return String with the first letter capitalized
 */
public String capitilizeFirst(String str)
{
    // assumptions that input parameter is not null is legal, as we use this function in map chain
    Function<String, String> capFirst = (String s) -> {
        String result = ""; // <-- accumulator

        try { result += s.substring(0, 1).toUpperCase(); }
        catch (Throwable e) {}
        try { result += s.substring(1).toLowerCase(); }
        catch (Throwable e) {}

        return result;
    };

    return Optional.ofNullable(str)
            .map(String::trim)
            .map(capFirst)
            .orElse("");
}
0

You can use Class WordUtils.

Suppose your String is "current address" then use

****strong textWordutils.capitaliz(String); output : Current Address

Refer: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html

0
class CapitalizeWords
{
    public static void main(String[] args) 
    {
        String input ="welcome to kashmiri geeks...";

        System.out.println(input);

        String[] str = input.split(" ");

        for(int i=0; i< str.length; i++)
        {
            str[i] = (str[i]).substring(0,1).toUpperCase() + (str[i]).substring(1);
        }

        for(int i=0;i<str.length;i++)
        {
            System.out.print(str[i]+" ");
        }


    }
}
0
String s = "first second third fourth";

        int j = 0;
        for (int i = 0; i < s.length(); i++) {

            if ((s.substring(j, i).endsWith(" "))) {

                String s2 = s.substring(j, i);
                System.out.println(Character.toUpperCase(s.charAt(j))+s2.substring(1));
                j = i;
            }
        }
        System.out.println(Character.toUpperCase(s.charAt(j))+s.substring(j+1));
0

One approach.

String input = "someТекст$T%$4čřЭ"; //Enter your text.
if (input == null || input.isEmpty()) {
    return "";
}

char [] chars = input.toCharArray();
chars[0] = chars[0].toUpperCase();
String res = new String(chars);
return res;

The drawback of this method is that if inputString is long, you will have three objects of such length. The same as you do

String s1 = input.substring(1).toUpperCase();
String s2 = input.substring(1, lenght);
String res = s1 + s2;

Or even

//check if not null.
StringBuilder buf = new StringBuilder(input);
char ch = buf.getCharAt(0).toUpperCase();
buf.setCharAt(0, ch);
return buf.toString();
0

This code to capitalize each word in text!

public String capitalizeText(String name) {
    String[] s = name.trim().toLowerCase().split("\\s+");
    name = "";
    for (String i : s){
        if(i.equals("")) return name; // or return anything you want
        name+= i.substring(0, 1).toUpperCase() + i.substring(1) + " "; // uppercase first char in words
    }
    return name.trim();
}
0
import java.util.*;
public class Program
{
    public static void main(String[] args) 
      {
        Scanner sc=new Scanner(System.in);
        String s1=sc.nextLine();
        String[] s2=s1.split(" ");//***split text into words***
        ArrayList<String> l = new ArrayList<String>();//***list***
        for(String w: s2)
        l.add(w.substring(0,1).toUpperCase()+w.substring(1)); 
        //***converting 1st letter to capital and adding to list***
        StringBuilder sb = new StringBuilder();//***i used StringBuilder to convert words to text*** 
        for (String s : l)
          {
             sb.append(s);
             sb.append(" ");
          }
      System.out.println(sb.toString());//***to print output***
      }
}

i have used split function to split the string into words then again i took list to get the first letter capital in that words and then i took string builder to print the output in string format with spaces in it

0

To capitalize the first letter of the input string, we first split the string on space and then use the collection transformation procedure provided by map

<T, R> Array<out T>.map(

   transform: (T) -> R

): List<R>

to transform, each split string to first in lowercase then capitalize the first letter. This map transformation will return a list that needs to convert into a string by using joinToString function.

KOTLIN

fun main() {
    
    /*
     * Program that first convert all uper case into lower case then 
     * convert fist letter into uppercase
     */
    
    val str = "aLi AzAZ alam"
    val calStr = str.split(" ").map{it.toLowerCase().capitalize()}
    println(calStr.joinToString(separator = " "))
}

OUTPUT

output of above code

1
  • 1
    The question refered to Java, not Kotlin. Java does not have that capitalize() method (yet).
    – Spindizzy
    Oct 14, 2021 at 12:08
0

Here is solution from my side, with all the conditions check.

   import java.util.Objects;

public class CapitalizeFirstCharacter {

    public static void main(String[] args) {

        System.out.println(capitailzeFirstCharacterOfString("jwala")); //supply input string here
    }

    private static String capitailzeFirstCharacterOfString(String strToCapitalize) {

        if (Objects.nonNull(strToCapitalize) && !strToCapitalize.isEmpty()) {
            return strToCapitalize.substring(0, 1).toUpperCase() + strToCapitalize.substring(1);
        } else {
            return "Null or Empty value of string supplied";

        }

    }

}
-1

Those who search capitalize first letter of a name here..

public static String capitaliseName(String name) {
    String collect[] = name.split(" ");
    String returnName = "";
    for (int i = 0; i < collect.length; i++) {
        collect[i] = collect[i].trim().toLowerCase();
        if (collect[i].isEmpty() == false) {
            returnName = returnName + collect[i].substring(0, 1).toUpperCase() + collect[i].substring(1) + " ";
        }
    }
    return returnName.trim();
}

usase: capitaliseName("saurav khan");

output: Saurav Khan

-1
  • character char can't store in String.
  • char and String can't concatenate.
  • String.valueOf() use to convert char to String

Input

india

Code

String name = "india";
char s1 = name.charAt(0).toUppercase()); // output: 'I'
System.out.println(String.valueOf(s1) + name.substring(1)); // output: "I"+ "ndia";

Output

India
1
  • 1
    char does not have toUppercase method
    – Mugen
    Jul 13, 2022 at 15:09
-1

To avoid exceptions (IndexOutOfBoundsException or NullPointerException when using substring(0, 1) for an empty or null string), you can use regex ("^.") (since Java 9):

    try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
        String name = reader.readLine();

        name = Pattern.compile("^.")    // regex for the first character of a string
                .matcher(name)
                .replaceFirst(matchResult -> matchResult.group().toUpperCase());

        System.out.println(name);
    } catch(IOException ignore) {}
-2

Try this, it worked for me.

public static String capitalizeName(String name) {
    String fullName = "";
    String names[] = name.split(" ");
    for (String n: names) {
        fullName = fullName + n.substring(0, 1).toUpperCase() + n.toLowerCase().substring(1, n.length()) + " ";
    }
    return fullName;
}
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.