aks24
aks24

Reputation: 11

Middle char to upper case in java

StringBuffer strbuff=new StringBuffer("Hello students");
char ch=strb.charAt(9).toUpperCase();

It's not working - I want to convert the character at 10 location toUppercase(). How can I do this?

Upvotes: 1

Views: 1871

Answers (5)

anubhava
anubhava

Reputation: 784878

toUpperCase() is method of String/Character class, it cannot be applied to a native char type.

PS: Note that strbuff.charAt(9) will return you a char and to covert that to upper case you will need to call Character.toUpperCase(char) like this:

This should work instead:

StringBuffer strbuff=new StringBuffer("Hello students");
char ch=Character.toUpperCase(strbuff.charAt(9));
System.out.println(ch); // D

If you want to set this back in StringBuffer:

strbuff.setCharAt(9, ch);

Upvotes: 7

user2837260
user2837260

Reputation: 181

char ch=strb.charAt(9).toUpperCase();

REPLACE THIS BY

char ch=Character.toUpperCase(strbuff.charAt(9));

Upvotes: 2

qqilihq
qqilihq

Reputation: 11454

I assue you want to modify your string:

StringBuffer strbuff=new StringBuffer("Hello students");
strbuff.setCharAt(9, Character.toUpperCase(strbuff.charAt(9)));

Hint 1: In case you are on a current Java version, use StringBuilder, unless you need Thread-safety.

Hint 2: You cannot invoke a method on a char because it is a primitive type, that is why you use the static Character#toUpperCase method.

Upvotes: 4

Shashank Kadne
Shashank Kadne

Reputation: 8101

This is what you need I guess,

char ch=Character.toUpperCase(strbuff.charAt(9));

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336078

Your StringBuffer is named strbuff, but you're accessing an (undefined) strb on the second line.

And even if that was just a typo, the second line does nothing but create a new variable ch, but it doesn't use that to construct a new string.

Upvotes: 1

Related Questions