1

why Jshell is considering r , s as string when used without brackets ?

PS C:\Users\saiko\OneDrive\Learning\java> Jshell                                                                                                                                             
|  Welcome to JShell -- Version 11.0.6
|  For an introduction type: /help intro

jshell> int p = 10;  int q =20; int r=5; int s=10;
p ==> 10
q ==> 20
r ==> 5
s ==> 10

jshell> if( (p+q) > (r+s) ) System.out.println( p+q+" is greater than  "+r+s );
30 is greater than  510

jshell> if( (p+q) > (r+s) ) System.out.println( (p+q) +" is greater than  "+ (r+s) );
30 is greater than  15

jshell>

1 Answers1

0

As said in the comments and in the Java tutorials:

All binary operators except for the assignment operators are evaluated from left to right

In the expression p+q+" is greater than "+r+s, the first evaluation is p+q results in an int, then p+q+" is greater than " results in String, and all subsequent evaluation results also to a String.

This is why you obtain:

30 is greater than  510
Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240