java - 错误 : incompatible types: possible lossy conversion from int to short. 我不知道为什么会收到此错误消息

标签 java

public class Demo 
{
    public static void main(String[] args) 
    {
       int a=10,b=20;
       short c = (a<b)?a:b;
       System.out.println(c);
    }
}

这是我的程序,我遇到以下错误,为什么我没有得到

"Demo.java:6: error: incompatible types: possible lossy conversion from int to short
short c = (a<b)?a:b;
1 error" 

我写了带有变量声明的“final”,它工作正常。但为什么会这样呢?

public class Demo 
{
    public static void main(String[] args) 
    {
        final int a=10,b=20;
        short c = (a<b)?a:b;
        System.out.println(c);
    }
}

最佳答案

要回答您的问题,您基本上是向下转换 int 数据类型为short Java 中 Not Acceptable 情况。为了详细描述,下面是详细描述:-

案例 1:-

public class Demo 
{
    public static void main(String[] args) 
    {
       int a=10,b=20;
       short c = (a<b)?a:b;
       System.out.println(c);
    }
}

在这种情况下,您只是将数据类型从int向下转换short,这是抛出

error: incompatible types: possible lossy conversion from int to short

案例 2:-

public class Demo 
{
    public static void main(String[] args) 
    {
        final int a=10,b=20;
        short c = (a<b)?a:b;
        System.out.println(c);
    }
}

In this scenario, since you have declared your variables viz. a & b as final. As a result, both the values becomes CONSTANT for variable c. It means for the variable c, the values of a & b won't get changed & it has been finalized to 20 which is in range of short data type (-32,768 to 32,767). Therefore, you won't get any error unless & until you keep the value within the range.

真实测试用例:-

public class Demo 
{
    public static void main(String[] args) 
    {
        final int a=32768,b=32788;
        short c = (a<b)?a:b;
        System.out.println(c);
    }
}

编译这个类,看看它的神奇之处!您将再次遇到相同的错误。

For your further understanding, please refer here to get a clear picture in general.

这个故事的寓意:- 只是不要贬低你的数据类型!!

关于java - 错误 : incompatible types: possible lossy conversion from int to short. 我不知道为什么会收到此错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53774145/

相关文章:

java - 每次运行 SQL 语句时更改 Mocked ResultSet 值

java - 如何从 @Advice.OnMethodExit 中的 premain 方法获取 arg?

java - Gremlin:Blazegraph Remote

Java <> 运算符说明

java - 如何在Android中的上一个按钮上设置选中的单选按钮?

java - hibernate MySQLSyntaxErrorException : Unknown database "..."

java - JOptionPane 如何改变标题框的颜色

java - 为什么这个带有有界通配符的 Java 通用代码无法编译?

java - 检查Elasticsearch文档是否存在给定值的最有效方法

java - 在 LibGDX(eclipse) 中逐字符读取文件?