Ujjwal
Ujjwal

Reputation: 1

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

I know this error occurs when we try downcasting values but in my code I am not able to figure ooout where have I downcasted the values.

class TestClass {
    public static void main(String args[] ) throws Exception {
        TestDemo obj=new TestDemo();
        TestDemo2 obj1= new TestDemo2();
        obj.show(5);
        obj1.show("helloworld");
    }
}
class TestDemo{
    public void show(short N){
        System.out.println(N*2);
    }  
}
class TestDemo2{
    public Void show(String S){
        System.out.println(S);
    }
}

Upvotes: 0

Views: 256

Answers (4)

Zash
Zash

Reputation: 19

Try changing the short N, in public void show(short N) from test Demo to int.

Upvotes: 1

SHUBHAM AGRAWAL
SHUBHAM AGRAWAL

Reputation: 63

This error is occurring due to obj.show(5).

Two fixes`you can do any:

    class TestClass {
    public static void main(String args[] ) throws Exception {
        TestDemo obj=new TestDemo();
        TestDemo2 obj1= new TestDemo2();
        obj.show((short)5);
        obj1.show("helloworld");
    }
}
class TestDemo{
    public void show(short i){
        
        System.out.println(i*2);
    }  
}
class TestDemo2{
    public void show(String S){
        System.out.println(S);
    }
}

Second Version

    class TestClass {
    public static void main(String args[] ) throws Exception {
        TestDemo obj=new TestDemo();
        TestDemo2 obj1= new TestDemo2();
        obj.show(5);
        obj1.show("helloworld");
    }
}
class TestDemo{
    public void show(int i){
        
        System.out.println(i*2);
    }  
}
class TestDemo2{
    public void show(String S){
        System.out.println(S);
    }
}

Upvotes: 3

Rishabh Sharma
Rishabh Sharma

Reputation: 862

Number 5 is treated by default as integer which is passed to method with short argument.

obj.show((short)5);

Also for future reference, java errors as well as exceptions are very detailed, giving you the exact line number where the issue occurred. That should help you identify the code segment where the issue is.

Upvotes: 0

Buzzet
Buzzet

Reputation: 763

try to cast the int first.

obj.show((short)5);

Upvotes: 0

Related Questions