Menu

#2 String-Methods should create new objects only if nessecary

open
nobody
None
5
2004-03-30
2004-03-30
Anonymous
No

public static String capitalize( final String input )
{
final char[] chars = input.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
return new String(chars);
}

==>

public static String capitalize( final String input )
{
if ( input == null || input.length() == 0 )
return input;

char firstChar = input.charAt( 0 );
char upperFirstChar = Character.toUpperCase(
firstChar );

if ( firstChar == upperFirstChar )
return input;

StringBuffer sb = new StringBuffer( input.length() );
sb.append( input );
sb.setCharAt( 0, upperFirstChar );

return sb.toString();
}

Discussion


Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.