[java] 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

This question is related to java string capitalize

The answer is



One approach.

String input = "some?????$T%$4cr?"; //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();

TO get First letter capital and other wants to small you can use below code. I have done through substring function.

String currentGender="mAlE";
    currentGender=currentGender.substring(0,1).toUpperCase()+currentGender.substring(1).toLowerCase();

Here substring(0,1).toUpperCase() convert first letter capital and substring(1).toLowercase() convert all remaining letter into a small case.

OUTPUT:

Male


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)));

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


System.out.println(Character.toString(A.charAt(0)).toUpperCase()+A.substring(1));

P.S = a is a string.


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

The shorter/faster version code to capitalize the first letter of a String is:

String name  = "stackoverflow"; 
name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();

the value of name is "Stackoverflow"


Existing answers are either

  • incorrect: they think that char is a separate character (code point), while it is a UTF-16 word which can be a half of a surrogate pair, or
  • use libraries which is not bad itself but requires adding dependencies to your project, or
  • use Java 8 Streams which is perfectly valid but not always possible.

Let's look at surrogate characters (every such character consist of two UTF-16 words — Java chars) and can have upper and lowercase variants:

IntStream.rangeClosed(0x01_0000, 0x10_FFFF)
    .filter(ch -> Character.toUpperCase(ch) != Character.toLowerCase(ch))
    .forEach(ch -> System.out.print(new String(new int[] { ch }, 0, 1)));

Many of them may look like 'tofu' (?) for you but they are mostly valid characters of rare scripts and some typefaces support them.

For example, let's look at Deseret Small Letter Long I (), U+10428, "\uD801\uDC28":

System.out.println("U+" + Integer.toHexString(
        "\uD801\uDC28".codePointAt(0)
)); // U+10428

System.out.println("U+" + Integer.toHexString(
        Character.toTitleCase("\uD801\uDC28".codePointAt(0))
)); // U+10400 — ok! capitalized character is another code point

System.out.println("U+" + Integer.toHexString(new String(new char[] {
        Character.toTitleCase("\uD801\uDC28".charAt(0)), "\uD801\uDC28".charAt(1)
}).codePointAt(0))); // U+10428 — oops! — cannot capitalize an unpaired surrogate

So, a code point can be capitalized even in cases when char cannot be. Considering this, let's write a correct (and Java 1.5 compatible!) capitalizer:

@Contract("null -> null")
public static CharSequence capitalize(CharSequence input) {
    int length;
    if (input == null || (length = input.length()) == 0) return input;

    return new StringBuilder(length)
            .appendCodePoint(Character.toTitleCase(Character.codePointAt(input, 0)))
            .append(input, Character.offsetByCodePoints(input, 0, 1), length);
}

And check whether it works:

public static void main(String[] args) {
    // ASCII
    System.out.println(capitalize("whatever")); // w -> W

    // UTF-16, no surrogate
    System.out.println(capitalize("???-??")); // ? -> ?

    // UTF-16 with surrogate pairs
    System.out.println(capitalize("\uD801\uDC28")); //  -> 
}

See also:



If Input is UpperCase ,then Use following :

str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();

If Input is LowerCase ,then Use following :

str.substring(0, 1).toUpperCase() + str.substring(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;
 }

In Android Studio

Add this dependency to your build.gradle (Module: app)

dependencies {
    ...
    compile 'org.apache.commons:commons-lang3:3.1'
    ...
}

Now you can use

String string = "STRING WITH ALL CAPPS AND SPACES";

string = string.toLowerCase(); // Make all lowercase if you have caps

someTextView.setText(WordUtils.capitalize(string));

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("");
}

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();
}

Below solution will work.

String A = "stackOverflow";
String ACaps = A.toUpperCase().charAt(0)+A.substring(1,A.length());
//Will print StackOverflow

You can't use toUpperCase() on primitive char , but you can make entire String to Uppercase first then take the first char, then to append to the substring as shown above.


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();
    }

if you use SPRING:

import static org.springframework.util.StringUtils.capitalize;
...


    return capitalize(name);

IMPLEMENTATION: https://github.com/spring-projects/spring-framework/blob/64440a5f04a17b3728234afaa89f57766768decb/spring-core/src/main/java/org/springframework/util/StringUtils.java#L535-L555

REF: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/StringUtils.html#capitalize-java.lang.String-


NOTE: If you already have Apache Common Lang dependency, then consider using their StringUtils.capitalize as other answers suggest.


Use replace method.

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

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();
}

Have a look at ACL WordUtils.

WordUtils.capitalize("your string") == "Your String"

How to upper case every first letter of word in a string?


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"));
}

try this one

What this method does is that, Consider the word "hello world" this method turn it into "Hello World" capitalize the beginning of each word .

 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(" ");
                sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
            }
        }
        return  sb.toString();

    }

Current answers are either incorrect or over-complicate this simple task. After doing some research, here are two approaches I come up with:

1. String's substring() Method

public static String capitalize(String str) {
    if(str== null || str.isEmpty()) {
        return str;
    }

    return str.substring(0, 1).toUpperCase() + str.substring(1);
}

Examples:

System.out.println(capitalize("java")); // Java
System.out.println(capitalize("beTa")); // BeTa
System.out.println(capitalize(null)); // null

2. Apache Commons Lang

The Apache Commons Lang library provides StringUtils the class for this purpose:

System.out.println(StringUtils.capitalize("apache commons")); // Apache commons
System.out.println(StringUtils.capitalize("heLLO")); // HeLLO
System.out.println(StringUtils.uncapitalize(null)); // null

Don't forget to add the following dependency to your pom.xml file:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

This is just to show you, that you were not that wrong.

BufferedReader br = new InputstreamReader(System.in);
// Assuming name is not blank
String name = br.readLine(); 

//No more error telling that you cant convert char to string
String s1 = (""+name.charAt(0)).toUppercase());
// Or, as Carlos prefers. See the comments to this post.
String s1 = Character.toString(name.charAt(0)).toUppercase());

System.out.println(s1+name.substring(1));

Note: This is not at all the best way to do it. This is just to show the OP that it can be done using charAt() as well. ;)


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));

Use Apache's common library. Free your brain from these stuffs and avoid Null Pointer & Index Out Of Bound Exceptions

Step 1:

Import apache's common lang library by putting this in build.gradle dependencies

compile 'org.apache.commons:commons-lang3:3.6'

Step 2:

If you are sure that your string is all lower case, or all you need is to initialize the first letter, directly call

StringUtils.capitalize(yourString);

If you want to make sure that only the first letter is capitalized, like doing this for an enum, call toLowerCase() first and keep in mind that it will throw NullPointerException if the input string is null.

StringUtils.capitalize(YourEnum.STUFF.name().toLowerCase());
StringUtils.capitalize(yourString.toLowerCase());

Here are more samples provided by apache. it's exception free

StringUtils.capitalize(null)  = null
StringUtils.capitalize("")    = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"

Note:

WordUtils is also included in this library, but is deprecated. Please do not use that.


You can also try this:

 String s1 = br.readLine();
 char[] chars = s1.toCharArray();
 chars[0] = Character.toUpperCase(chars[0]);
 s1= new String(chars);
 System.out.println(s1);

This is better(optimized) than with using substring. (but not to worry on small string)


Java:

simply a helper method for capitalizing every string.

public static String capitalize(String str)
{
    if(str == null) return str;
    return str.substring(0, 1).toUpperCase() + str.substring(1);
}

After that simply call str = capitalize(str)


Kotlin:

str.capitalize()

What about WordUtils.capitalizeFully()?

import org.apache.commons.lang3.text.WordUtils;

public class Main {

    public static void main(String[] args) {

        final String str1 = "HELLO WORLD";
        System.out.println(capitalizeFirstLetter(str1)); // output: Hello World

        final String str2 = "Hello WORLD";
        System.out.println(capitalizeFirstLetter(str2)); // output: Hello World

        final String str3 = "hello world";
        System.out.println(capitalizeFirstLetter(str3)); // output: Hello World

        final String str4 = "heLLo wORld";
        System.out.println(capitalizeFirstLetter(str4)); // output: Hello World
    }

    private static String capitalizeFirstLetter(String str) {
        return WordUtils.capitalizeFully(str);
    }
}

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();
    }

public void capitalizeFirstLetter(JTextField textField) {

    try {

        if (!textField.getText().isEmpty()) {
            StringBuilder b = new StringBuilder(textField.getText());
            int i = 0;
            do {
                b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase());
                i = b.indexOf(" ", i) + 1;
            } while (i > 0 && i < b.length());
            textField.setText(b.toString());
        }

    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
    }
}

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
     }
}

This will work

char[] array = value.toCharArray();

array[0] = Character.toUpperCase(array[0]);

String result = new String(array);

String str1 = "hello";
str1.substring(0, 1).toUpperCase()+str1.substring(1);

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


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;
}

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]+" ");
        }


    }
}

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;
}


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


Set the string to lower case, then set the first Letter to upper like this:

    userName = userName.toLowerCase();

then to capitalise the first letter:

    userName = userName.substring(0, 1).toUpperCase() + userName.substring(1).toLowerCase();

substring is just getting a piece of a larger string, then we are combining them back together.


Use this utility method to get all first letter in capital.

String captializeAllFirstLetter(String name) 
{
    char[] array = name.toCharArray();
    array[0] = Character.toUpperCase(array[0]);

    for (int i = 1; i < array.length; i++) {
        if (Character.isWhitespace(array[i - 1])) {
            array[i] = Character.toUpperCase(array[i]);
        }
    }

    return new String(array);
}

Using commons.lang.StringUtils the best answer is:

public static String capitalize(String str) {  
    int strLen;  
    return str != null && (strLen = str.length()) != 0 ? (new StringBuffer(strLen)).append(Character.toTitleCase(str.charAt(0))).append(str.substring(1)).toString() : str;  
}

I find it brilliant since it wraps the string with a StringBuffer. You can manipulate the StringBuffer as you wish and though using the same instance.


IT WILL WORK 101%

public class UpperCase {

    public static void main(String [] args) {

        String name;

        System.out.print("INPUT: ");
        Scanner scan = new Scanner(System.in);
        name  = scan.next();

        String upperCase = name.substring(0, 1).toUpperCase() + name.substring(1);
        System.out.println("OUTPUT: " + upperCase); 

    }

}

You can use substring() to do this.

But there are two different cases:

Case 1

If the String you are capitalizing is meant to be human-readable, you should also specify the default locale:

String firstLetterCapitalized = 
    myString.substring(0, 1).toUpperCase(Locale.getDefault()) + myString.substring(1);

Case 2

If the String you are capitalizing is meant to be machine-readable, avoid using Locale.getDefault() because the string that is returned will be inconsistent across different regions, and in this case always specify the same locale (for example, toUpperCase(Locale.ENGLISH)). This will ensure that the strings you are using for internal processing are consistent, which will help you avoid difficult-to-find bugs.

Note: You do not have to specify Locale.getDefault() for toLowerCase(), as this is done automatically.


You can use the following code:

public static void main(String[] args) {

    capitalizeFirstLetter("java");
    capitalizeFirstLetter("java developer");
}

public static void capitalizeFirstLetter(String text) {

    StringBuilder str = new StringBuilder();

    String[] tokens = text.split("\\s");// Can be space,comma or hyphen

    for (String token : tokens) {
        str.append(Character.toUpperCase(token.charAt(0))).append(token.substring(1)).append(" ");
    }
    str.toString().trim(); // Trim trailing space

    System.out.println(str);

}

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


Shortest too:

String message = "my message";    
message = Character.toUpperCase(message.charAt(0)) + message.substring(1);
System.out.println(message)    // Will output: My message

Worked for me.


Here is my detailed article on the topic for all possible options Capitalize First Letter of String in Android

Method to Capitalize First Letter of String in Java

public static String capitalizeString(String str) {
        String retStr = str;
        try { // We can face index out of bound exception if the string is null
            retStr = str.substring(0, 1).toUpperCase() + str.substring(1);
        }catch (Exception e){}
        return retStr;
}

Method to Capitalize First Letter of String in KOTLIN

fun capitalizeString(str: String): String {
        var retStr = str
        try { // We can face index out of bound exception if the string is null
            retStr = str.substring(0, 1).toUpperCase() + str.substring(1)
        } catch (e: Exception) {
        }
        return retStr
}

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


What you want to do is probably this:

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

(converts first char to uppercase and adds the remainder of the original string)

Also, you create an input stream reader, but never read any line. Thus name will always be null.

This should work:

BufferedReader br = new InputstreamReader(System.in);
String name = br.readLine();
String s1 = name.substring(0, 1).toUpperCase() + name.substring(1);

Simple solution! doesn't require any external library, it can handle empty or one letter string.

private String capitalizeFirstLetter(@NonNull  String str){
        return str.length() == 0 ? str
                : str.length() == 1 ? str.toUpperCase()
                : str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}

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


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();
    }

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);
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to capitalize

Capitalize the first letter of string in AngularJs python capitalize first letter only Capitalize first letter. MySQL Regular expression for checking if capital letters are found consecutively in a string? How to capitalize the first letter of a String in Java? How can I capitalize the first letter of each word in a string? How do I make the first letter of a string uppercase in JavaScript? How do I capitalize first letter of first name and last name in C#?