Cast to char while toggline string case without using inbuilt functions

Here is the program i have written for converting case of string. However i am getting a compilation error as i have commented in the following program. Can you please explain to me in context of my code, what i am doing wrong?

public class Togg 
{
public static void main(String args[])
{
    String small="nayanjindalrocks";
    char a[]=new char[small.length()];
    int i;
    for(i=0;i<a.length;i++)
    {
        a[i]=small.charAt(i);
        if(a[i]>='A'&&a[i]<='Z')
        {
        a[i]=a[i]+32; // Type mismatch: cannot convert from int to char (Add cast to char)
        }
        else
        {
            a[i]=a[i]-32; // Type mismatch: cannot convert from int to char (Add cast to char)
        }
    }
    String news=new String(a);
    System.out.print(news);
}
}
Jon Skeet
people
quotationmark

As the compiler says, you're trying to assign an int value (the result of a[i] + 32 for example to a char variable (a[i]). The "surprise" part here is that the result of a[i] + 32 is a char... but it's only a surprise if you don't look at JLS 15.18.2, which specifies the + operator for numeric types, and which specifies that binary numeric promotion is applied first. In this case, a[i] is implicitly promoted to int before the addition is performed.

Options:

  • Add the cast, e.g.

    a[i] = (char) (a[i] + 32);
    
  • Use += or -= which performs the cast implicitly

    a[i] += 32;
    

people

See more on this question at Stackoverflow