Cat cat = new Cat(); int a = 5; String text = cat + a + "The cat is " + cat + a;
The program won't compile! .also, I can't understand what the Codegym say "If we add a cat to a number, there is no automatic string conversion" can you explain for me? Thank you
You must be signed in to leave a comment
1 June 2021, 16:23
Try this code:The output is: 9 The cat is 54 This is because the equation, to the right of the '=' processes first. This equation starts with an int, '5', so the computer thinks the entire line is an int. It takes the next input of 4 and adds it to 5, which is 9. It then takes the next input of " The cat is ", which is a String, and converts the equation from an int to a String. Now it grabs the next input, which is 5, and because the result so far is a String it converts the 5 to a String and adds the 2 Strings together. Now the last input is 4, and because the total result is a String it converts that to a String and adds the two Strings together. Now try this, where we start with a String. What do you think the output will be? Try to figure it out before running it to see if you get it correct. In your code the equation starts with a Cat and tries to add 'a', which is an int, to that. The computer does not know how to add a Cat and an int together which is where the error is occurring.
2 June 2021, 06:51
Thank you so much Guadalupe Gagnon, I am very glad to find the best explanation and understand it. Now we can say in short:( "Once it encounters the String, it considers the rest of the expression as of a String, based on the precedence order of the expression").