Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is the code I’ve my doubts on: 

http://rendera.heroku.com/usercode/eae2b0f40cf503b36ee346f5c511b0e29fc82f9e

 

It works fine for /,*,-. But when I use x+y, it gives faulty output. For example: 2+2=22, 5+7=57

 

Can anyone tell me what’s wrong here? 

1 Answer

0 votes
by (19.7k points)

This happens when one or both of the variables is String which results in string concatenation. 

Check the code below:

'2' + 2 === '22';  // true

2 + 2 === 4;  // true

The arithmetic operators like / * -  performs a toNumber conversion on the string(s).

'3' * '5' === 15;  // true

In order to convert a string to a number : use the unary + operator.

+'2' + 2 === 4;  // true

(or)

+x + +y

Interested in Java? Check out this Java Certification by Intellipaat.    

Related questions

0 votes
1 answer
asked Apr 23, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
0 votes
1 answer
asked Apr 4, 2021 in Java by Jake (7k points)
0 votes
1 answer
0 votes
1 answer
asked Mar 3, 2021 in Java by sheela_singh (9.5k points)

Browse Categories

...