If Java is Strongly typed then why does this code compile?

George picture George · Nov 27, 2015 · Viewed 9.5k times · Source

My understanding of strongly typed was that the language wouldn't make implicit type conversions. However, this code converts the char to it's ascii value and then uses that value.

static char x = 'j';
static int y = 7;

public static void main(String[] args){
    System.out.println(y+x);
}

Answer

Malt picture Malt · Nov 27, 2015

This has little to do with strong or weak typing. Your code is an example of an implicit cast between two strongly typed variables - a char and int.

Your System.out.println(y+x) is actually compiled to System.out.println(y+(int)x); so System.out.println(int arg0) is invoked.

The cast (int)x is what converts the character to its ascii value simply because Java stores chars as UTF-16 values.