Witscale Test Center

10.3 Type conversion in primitives > 10.3.4 Primitive type conversion during a method call


10.3.4 Primitive type conversion during a method call

Another context in which the data types may be automatically changed is during the method call. If you pass a value of some data type as an argument to a method that expects a different data type, the type conversion may occur. For example, assume a method called calculateInterest()that expects a float argument. Following code snippet calls this method with an int argument as:

 


The above code will compile successfully. Java will implicitly convert the int value interestRate into a float value. Then it is passed to the method calculateInterest(). The rules of primitive conversion at the time of method call are same as the rules for the primitive assignments. The following rules summarize briefly, what you can and cannot do while passing primitives as method arguments.

 

1.       You can pass any non-boolean value to a method expecting any non-boolean variable. The type conversion takes place only if  you pass a narrower type argument.

For example, the method Math.sqrt() expects double value as argument. If you call it with argument of narrower data type such as int as:

 

int intNumber = 5;

double squareRoot = Math.sqrt(intNumber);    //Valid method call

 

Java will automatically convert the int value 5 into double value and then call the sqrt() method of java.lang.Math class.

 

2.       You cannot pass a non-boolean value to a method expecting a non-boolean argument if you pass a wider type argument.

For example, assume a method called calculateInterest()that expects a float argument. Following code snippet calls this method with an double argument as:


The above code will fail to compile. The method calculateInterest() expects float, but we are calling it with a wider datatype double. Since it cannot hold this wider data type in its argument variable, Java compiler will flag an error.

 

3.       You cannot pass a boolean value to a method expecting a non-boolean primitive variable. You cannot pass non-boolean a value to a method expecting a boolean primitive variable.

The method calculateInterest() expects float, but if we call it with a boolean value, say calculateInterest(true), the code will not compile. The boolean and rest of the non-boolean primitives are always incompatible and can never be converted to each other.