+ 2

[SOLVED]simple string as input unexpected out put🧐🧐

may anybody tell me what's going on here? why its output is number????

11th Jun 2020, 6:11 AM
hamid
hamid - avatar
9 odpowiedzi
+ 2
hamid Generally charAt returns character but when you add two or more characters It's gives result as number. Actually It's adding ASCII value. That's why you are getting result in number. If you want to concat two character just add this " " between the characters like: System.out.println(input.charAt(2) + "" + input.charAt(1)); // it will give String result
11th Jun 2020, 6:57 AM
A͢J
A͢J - avatar
+ 2
AJ Anant thanks again for helping me.
11th Jun 2020, 10:38 AM
hamid
hamid - avatar
+ 1
or System.out.println("" +input.charAt(2) +input.charAt(1));
11th Jun 2020, 8:27 AM
zemiak
+ 1
thanks 👍👍
11th Jun 2020, 9:26 AM
hamid
hamid - avatar
+ 1
AJ Anant I got my answer but just wanna know what does "" do here?
11th Jun 2020, 10:00 AM
hamid
hamid - avatar
+ 1
hamid "" use to concat two or more String or you can use to convert number in string like int n = 10; String x = n + "" //now it will be string.
11th Jun 2020, 10:09 AM
A͢J
A͢J - avatar
+ 1
"" this is empty String, you can use not empty String too like "here is char 2 and 1" + ....
11th Jun 2020, 4:46 PM
zemiak
+ 1
hamid the problem here is the compiler does not know that you dont want to do a math-addition of the asciivalue of the 2 chars and a concatenation instead. char's are nothing more than a numbervalue under the hood and he treats it that way. Note char is primitive and String is a referencedatatype(Object). The mix of lowlvl and highlvllanguage concepts can be confusing in the beginning indeed. Anyway keep going things will make more sense when you advance on your journey.
13th Jun 2020, 12:44 AM
Chris
- 1
Salom
12th Jun 2020, 6:52 PM
Mardon