Question

This question is been manipulated from exam labs

public class B{

      public static void main(String args[]){
        byte g =10;
          Byte x = new Byte(g);
          B p= new B();
          p.doStuff(x);
                      p.doStuff(g);
    }
      void dostuff(Number y){
          System.out.println("C"); 
      }
      void doStuff(short t){
          System.out.println("X");}

      }

Output : XC

In above program , i dont understant why its giving "C" as output?

its giving X because Byte--> byte-->short;

but in case of , byte g=10; it should again pass through same method and give "X" as output.

public class B{

          public static void main(String args[]){
          byte b1=12;
          Byte B1=new Byte(b1);

          capture(b1);
          capture(B1);

        }

        static void capture(short x){
          System.out.print("A");
        }


        static void capture(Number x){
          System.out.print("G");
        }
      }

output : AG

Here , also i understand why its A , because short is bigger than byte so it gives A

But , for other output its should be again A , because B1 is Byte ---> byte(Autoboxing) --->pass through short (Widdening). Why its G?

Was it helpful?

Solution

Don't take this for granted, but I think it's because a Byte is a Number, so it doesn't have to do any autoboxing if it chooses that version. Also, if it still chose the other one, there would be no way at all to call the Number version. Therefore, it makes more sense to have such calls call the Number version, which is exactly what java does.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top