Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte typecasting

Tags:

java

It is a basic question, but I couldn't get a the proper answer. I am thinking it is because of primitive types auto type casting

Why would the below statement invokes the print(int x) method and not print (char x) method.

public class Overloading {

    public static void main(String args[])
    {
        byte b='x';
        print(b);
    }

    public static void print(int x)
    {
        System.out.println("Inside int Print "+x);
    }


    public static void print(char x)
    {
        System.out.println("Inside char Print "+x);
    }

    public static void print(float x)
    {
        System.out.println("Inside float Print "+x);
    }


}
like image 968
Joe2013 Avatar asked Feb 17 '23 22:02

Joe2013


1 Answers

The conversion that may be used for this method invocation conversion is a widening primitive conversion :

byte to short, int, long, float, or double

short to int, long, float, or double

char to int, long, float, or double

int to long, float, or double

long to float or double

float to double

You see there is no byte to char path. This isn't a priority matter : if you remove the function taking an int as parameter, your code won't compile.

like image 93
Denys Séguret Avatar answered Feb 27 '23 03:02

Denys Séguret