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đ€đ€
5 Respostas
+ 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
+ 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.
+ 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
+ 2
Bahhađ§ Thanks for the awesome explanation!
+ 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