Java function overload

Can someone tell me why "int" is printed, as in the inner work.

class Test { void Method(int i) { System.out.println("int"); } void Method(String n) { System.out.println("string"); } public static void main(String [] a) { new Test().Method('c'); } } 
+4
source share
8 answers

The character c cast to int . It will not be passed to String .

More formally, from JLS §5.5 , an expanding conversion occurs from char to int , long , float , or double .

The reason that will never be considered String is that a char cannot be auto-boxed into String .

+9
source

'c' is a character according to its single quotes. Being a primitive, numeric (somewhat) type, it distinguishes an integer more easily than a string, since the latter must be explicit.

You can also change Method(int i) to print i and try different characters.

+1
source

char is actually a numeric type in Java . It is automatically converted to int when a callback is made, so the method prints an int .

From Oracle tutorials , we can read that:

The char data type is a single 16-bit Unicode character. It has a minimum value of '\ u0000' (or 0) and a maximum value of '\ uffff' (or 65,535 inclusive).

+1
source

Passing a variable with single quotes is considered char . Characters are converted to int variables.

If you want to pass it as a String , just use double quotes.

 new Test().Method("c"); 

specific transformations for primitive types are called expanding primitive transformations:

byte for short, int, long, float or double

short for int, long, float or double

char for int, long, float or double

int for long, float or double

long swim or double

float to double

You can read more here: JLS §5.1.2

+1
source

char is a primitive type , and its value is added to int , and String is an object .

On the other hand, there is a function in java called autoboxing, where some primitive types are assigned to objects when they are suitable (for example, from int to Integer , boolean to boolean ), but this does not work for char . char gets autoboxed up to Character .

0
source

When you pass 'c' , it is assumed to be char ; if you try to pass "c" , it will be considered as string .

0
source

'c' is a char type, not a string. 'c' can be compared to (int) 'c'

0
source

In Java, characters are represented as numbers. In particular, Java represents a character by Unicode code. If I am not mistaken, the character "c" is number 98 in the Unicode specification.

When you call Method('c') , the program has two method signing options: one where 'c' is int and the other is String . Since there is a number at the bottom of c, it is passed to int and treated as 98. Characters are not passed to Strings .

0
source

Source: https://habr.com/ru/post/1490493/


All Articles