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

12.1k views Asked by At

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);
}
3

There are 3 answers

1
Abdelhak On

Java is a strongly typed programming language because every variable must be declared with a data type. A variable cannot start off life without knowing the range of values it can hold, and once it is declared, the data type of the variable cannot change.

Examples:

The following declaration is allowed because the variable has "hasDataType" is declared to be a boolean data type:

 boolean hasDataType;

For the rest of its life, hasDataType can only ever have a value of true or false.

And why char was converted in numeric in you example.

System.out.println(y+x);

You can take a look at this example

0
Malt On

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.

0
Michael Lloyd Lee mlk On

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

Because the JLS says so. In this case we are widening a primitive, a char can turn into an int. And then we can add two ints and output the result. You could then narrow the int back into a char if you wanted.

System.out.println((char) (y+x));