I got the following code from quiz factory of solo learn and it gives output of 43" | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

I got the following code from quiz factory of solo learn and it gives output of 43"

Why it gives output 43" I don't no about 43 and " I think it (ie. " ) may because of error in code But what about 43 Plz help me to learn .... https://code.sololearn.com/cRgG1d05gYHT/?ref=app

12th Jan 2019, 12:09 PM
KAAMIL AHAMADH S
KAAMIL AHAMADH S - avatar
3 Answers
+ 5
Interesting. Very interesting... http://www.asciitable.com/mobile/ The ASCII value of horizontal tab is 9, and double quote is 34. Adding them up results in the value of 43. That's mystery no.1 solved. So what's the difference between: s += c+d; and str += d; str += c; you may ask. Well, from observation, s += c+d causes c to be added to d first before RHS is added to LHS and assigned to LHS. This results in the ASCII sum 43 (9+34) to be appended to string s, and printed. Doing str += d, str += c separately causes the characters to be appended to str, i.e. A horizontal tab and a double quote. The tab is invisible, so only the double quote shows. Voilà. That was very fun!
12th Jan 2019, 12:38 PM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Sum between chars, in java, is not what you think. Chars going converted to int (eg. them ascci value), summed then an int is returned. Now, the '\t' char has ascii code 9 while '"' char has ascii code 34. In line 6 you have: s+=c+d; This is same like: s= s + (c + d) =>> s = "" + ('\t' + '"') ==> s= "" + (9 + 34) ==> s= "" + 43 thats equals to make 43 like string then s will be "43". Lets go to anlyze next 2 lines: str+=d; str+=c; Because str="" you will end up with: str= "" + '"' ==> str="\"" (note that is a String) str= "\"" + '\t' ==> str= "\"\t" then, after those line, you will have: s= "43" str= "\"\t" then, the s+""+str, is equals to: "43"+""+"\"\t" ==> "43\"\t" and visualized like 43"
12th Jan 2019, 12:42 PM
KrOW
KrOW - avatar
+ 1
If I recall right but don't quote me on this, in java if you add 2 chars it will return an int, same happens when adding shorts or bytes. c+d are both chars thus it will return an int which is then stored in the string s. for example: this code will return 195: char a = 'a', b = 'b'; string str = ""; //Doesn't have to be a string, it could be an int too since it returns an int str += a + b; System.out.print(str); Hope this helps!
12th Jan 2019, 12:55 PM
Joery De Loose
Joery De Loose - avatar