Why a different output in these two loops? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why a different output in these two loops?

// why without () around n+"" in this loop "hi" is printed 100 times?: int n = 100; for (int i = 1; i <= n+"".length(); i++) { System.out.println("hi"); } // and with () around n+"" in this loop "hi" is printed 3 times: int n = 100; for (int i = 1; i <= (n+"").length(); i++) { System.out.println("hi"); } // why isn't n evaluated as a string in the first loop?

18th Jul 2019, 11:47 PM
Mind To Machine 💻🕆
Mind To Machine 💻🕆 - avatar
4 Answers
+ 2
The first one is evaluated like this n + ("".length()), the length of empty string is 0 so it's like 100 + 0. Well, you know how it's evaluated in the second one
18th Jul 2019, 11:52 PM
Agent_I
Agent_I - avatar
+ 2
It seems that method invocation has a higher precedence than addition. Would that be right Agent_I ?
19th Jul 2019, 2:23 AM
Sonic
Sonic - avatar
+ 2
Sonic Certainly, the dot operator is evaluated before the addition
19th Jul 2019, 2:28 AM
Agent_I
Agent_I - avatar
0
oh 😅, thank you Agent_I 😊
19th Jul 2019, 12:03 AM
Mind To Machine 💻🕆
Mind To Machine 💻🕆 - avatar