Home > Blockchain >  Why does System.out.println('a' == 97.0) give true
Why does System.out.println('a' == 97.0) give true

Time:05-22

I know that '==' operator checks for if they exists in the same memory location in Java, but why, whrn I am comparing char and double data types, Java is giving me true? Are they not different data types? And why it is not giving me a compile-time error, because according to the docs:

If we apply == for object types then, there should be compatibility between arguments types (either child to parent or parent to child or same type). Otherwise, we will get a compile-time error.

CodePudding user response:

I know that '==' operator ches for if they exists in the same memory location in Java...

Not with primitives, only with reference types (objects). There are three sections for ==/!= in the Java Language Specificiation:

  1. Numerical Equality Operators == and !=
  2. Boolean Equality Operators == and !=
  3. Reference Equality Operators == and !=

double and char are both numeric, so you refer to the first one. It describes the steps it goes through (conversion if necessary, promotion if necessary, value set conversion if necessary, unboxing if necessary) to take a char and a double and convert them so it can compare them numerically.

CodePudding user response:

In Java, char and double are primitives, which are compared by value using ==, not by memory location, that is only for objects (reference types).

When you do 'a' == 97.0, it is a comparison between char and double. char is an unsigned integer, and when compared to a double, char undergoes a widening conversion to double. The character 'a' corresponds to the numeric value 97, so when converted to double, it is 97.0. And given 97.0 == 97.0 is true, that is the result of the expression.

See also in the Java Language Specification:

  • 15.21.1. Numerical Equality Operators == and !=

    If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6).

  • 5.6. Numeric Contexts

    Numeric promotion determines the promoted type of all the expressions in a numeric context. The promoted type is chosen such that each expression can be converted to the promoted type, and, in the case of an arithmetic operation, the operation is defined for values of the promoted type. The order of expressions in a numeric context is not significant for numeric promotion. The rules are as follows:

    1. [..]

    2. Next, widening primitive conversion (§5.1.2) and narrowing primitive conversion (§5.1.3) are applied to some expressions, according to the following rules:

      • If any expression is of type double, then the promoted type is double, and other expressions that are not of type double undergo widening primitive conversion to double.
  •  Tags:  
  • java
  • Related