Wednesday, August 5, 2015

[Java][Resolved] Type mismatch: cannot convert from int to short

Incorrect sample:
public class static1{
    public static void main(String[] args){
        short s1 = 1;
        s1 = s1 + 1;
        System.out.println(s1);
    }
}

s1 +1 would return int, int can’t assign to short. Solution is converting the operation result from int type to short before assign to s1.

Correction:
public class static1{
    public static void main(String[] args){
        short s1 = 1;
        s1 = (short) (s1 + 1);
        System.out.println(s1);
    }
}

Remark :
It’s also work:
public class static1{
    public static void main(String[] args){
        short s1 = 1;
        s1 += s1;
        System.out.println(s1);
    }
}


Reference:
http://way2java.com/casting-operations/java-int-to-short/
http://619lucky.blogspot.hk/2010/08/java.html

No comments :

Post a Comment