0

Why this happens only in java why it doesn't happen in c,python or cpp?

Question: I have made same codes in c,cpp,java and in python and all have different outputs??I have posted code see and tell me 🤔🤔 Java System.out.println("2+2="+2+2); Output:=>2+2=22 C printf("2+2="+2+2); Output:=>Error Cpp cout<<"2+2="+2+2; Output:=>no output Python: print("2+2="+str(2+2)) Output:=>2+2=4 https://code.sololearn.com/c5V1j3KOMhe6/?ref=app https://code.sololearn.com/c1pbSZr5TWr3/?ref=app https://code.sololearn.com/c6XYEv73EF08/?ref=app https://code.sololearn.com/c6g1iK5TQu2F/?ref=app WHY THIS HAPPENS TELL ME WITH FULL EXPLANATION🤔🤔

6th Mar 2021, 3:23 PM
Anurag Kumar
Anurag Kumar - avatar
5 Réponses
+ 4
🌟ᴀɴᴜʀᴀɢ[STUDY 📚]🌟 In Java when you add numbers with String then it becomes string. So here "2+2=" + 2 + 2 will be 2+2=22 but if you add numbers within parenthesis then it add numbers. For example System.out.println("2+2="+(2+2)); In this case result will be 2+2=4
6th Mar 2021, 3:58 PM
A͢J
A͢J - avatar
+ 4
in C/C++, "string" + n . n being a number, is just a pointer arithmetic. you get no output because 2+2 exceeds the length of "2+2=" to understand better change 2+2 to a smaller number. example: cout << "2+2=" + 1 ; outputs: +2= it's like saying print the characters from str[1] to the end. to do string concatenation in c/c++ convert the int into a string.
6th Mar 2021, 3:32 PM
Bahhaⵣ
Bahhaⵣ - avatar
+ 3
JAVA ----- When you add an integer to a string, a new String object is created using in the SCP (String Constant Pool). Since the resultant object is a string, there is no error. This is generally discouraged as the creation of a new string object is costly (memory wise) Unfortunately, I'm not sure about the case in C or Cpp
6th Mar 2021, 3:30 PM
Soumik
Soumik - avatar
+ 2
Bahha🐧 Thanks for the awesome explanation!
6th Mar 2021, 3:38 PM
Soumik
Soumik - avatar
+ 1
Thanks ♨ Soumik 🎶 I Am AJ ! For better explanation I can't understand because I come from python,html,css and js so I couldn't understand it comes in community challenge so I ask
7th Mar 2021, 5:46 AM
Anurag Kumar
Anurag Kumar - avatar