Regarding Increment of Character Variable

Satyam Bansal :

The below code doesn't work, the compiler says 'Possible Lossy Conversion from int to char'

public class Main
{
    public static void main(String[] args) {
        char ch;
        ch = 65;
        ch=ch+1;
        System.out.println(ch);
    }
}

then why does the below code works without any error :

public class Main
{
    public static void main(String[] args) {
        char ch;
        ch = 65;
        ch+=1;
        System.out.println(ch);
    }
}

While the only difference in both of the codes is a mere 'ch=ch+1' and 'ch+=1' ?

Mena :

In java the size of a char variable is: 2 bytes, While the size of an int variable is: 4 bytes.

N.B: A byte is composed of 8 bits, which can hold a number value up to 256.

In the first code snippet, when you do (ch +1) the compiler thinks the 1 is an int value by default, thus regarding the final value as an int too. Then the compiler tries to put the final value in ch which is a char... ops.. it is trying to fit a value represented by 4 bytes into a variable having a size of 2 bytes!

This problem can be fixed if you do like this: Ch =(char)(ch+1)

In the second snippet, you are directly incrementing the variable ch, whatever its size is. Thus you don't run in the problem of trying to fit an int value in a char variable.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=414669&siteId=1