Capitalize a String in Java

An example on making the characters after the space capital if they are not, in Java. Here is a logic that i've written and that's what i can do. Still more efficient logics are appreciated in the comments. Thanks and go ahead. The [main logic] will also work in any programming language.

Let's capitalize!

import java.util.*;
class CapitalizeString

public static void main(String args[])

// Create Scanner object for taking input from the user

Scanner s=new Scanner(;

// Read a string from the user and store it in st

String st=s.nextLine();

// Convert string to char array

char[] c=st.toCharArray();

// Loop till end of the char array

for(int i=0;i<c.length;i++)

// If char at index i is a space, then..
if((c[i]==' '))

// If the character after space is a small alphabet i.e. ascii values of a-z are from 97-122



At that position put capital of that alphabet,
ascii values of A-Z are 65-90, so for every
particular small and capital alphabet there is a difference of 32
Also typecast to char from int.





// Make even the first letter capital
else if(i==0)

// The same as above, but for the current char [first char]






// Show it to the user

System.out.println("Capitalized: "+new String(c));



I think every thing is clear as every statement is explained above, so it will be useful for the future reference too. Go ahead with the output.


gowtham gutha
Capitalized: Gowtham Gutha

Note: No problem if spaces occur, they do not change. If you have any try trimming the spaces by calling st.trim() here and then convert it to char[]. The code might look like this.

Change, char c[]=st.toCharArray(); to

char c[]=st.trim().toCharArray();

Posted by at on

Tags: String Handling,