+ 2
[SOLVED]simple string as input unexpected out put🧐🧐
may anybody tell me what's going on here? why its output is number????
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
+ 2
AJ Anant
thanks again for helping me.
+ 1
or
System.out.println("" +input.charAt(2) +input.charAt(1));
+ 1
thanks 👍👍
+ 1
AJ Anant
I got my answer but just wanna know what does "" do here?
+ 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.
+ 1
"" this is empty String, you can use not empty String too like "here is char 2 and 1" + ....
+ 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.
- 1
Salom