Java String Manupulation

Why does the statement below gives error

       char rep=(str.charAt(len-1))-1;
       str.replace(str.charAt(len-1),rep);
       error: possible loss of precision

when the following code works correctly

class test
{
    public static void main(String arg[])
    {
        char x='A';
        x=x+1;
        System.out.println(x);
    }
}

Answer

You are trying to do downcasting(int --> char),which is not implicit.You will have to cast it explicitly.

Below code will not compile correctly.

        char x='A';
        x=x+1;// can not convert from int to char implicitly.

Change it to

        char x = 'A';
        x+=1;// it will automatically cast to char(implicit)

Similar change your below line of code,you will have to cast it to char.

   char rep=(char)((str.charAt(len-1))-1);

Leave a Reply

Your email address will not be published. Required fields are marked *