Difference between single quotes and double quotes in java?

I have

  • System.out.println(2+" "+3);

  • System.out.println(2+' '+3);

The first prints 2 3, and the second prints 37. Can any of the guys explain why he prints 37 ???

+4
source share
7 answers

' '= 32 in ascii.

a:) System.out.println(2+" "+3); // string concatenation

b:) System.out.println(2+' '+3);  // 2+ 32(32 ascii valur for space)+3 so 37
+3
source

Setting the Java Language Specification for Additive Operators :

If the type is any operand of an operator + String, then the operation is a string concatenation.

Otherwise, the type of each of the operands of the operator +must be a type that is convertible (Section 5.1.8) to a primitive numeric type

For numeric types :

On operands, a binary digital action is performed (§5.6.2)

:

[...] int.

, 2+" "+3 - 2 + " ", , String + 3 , 2 + " " + 3 is "2" + " " + "3", "2 3".

2+' '+3 2 + ' ', char, int (32), 2 + 32 + 3 37.


, , :

// String concatenation
String s = new StringBuilder().append(2).append(" ").append(3).toString();
System.out.println(s);

// Numeric addition
int n = 2 + (int)' ' + 3;
System.out.println(n);

append() println() , .

, , , ( .class, ):

System.out.println("2 3");
System.out.println(37);
+3

. - . 32. , 2 3 , .

+1

, 2+ ' ' +3 ' ' char not a string, b) ASCII, 2 + ASCII value of Space + 3 37, ASCII a space 32.

0

, . , '' , char. char , .

0

, , - , Java . char '' String "" true: .

0

System.out.println java.lang.String, java , java.lang.String.

System.out.println(2+" "+3); , java , int (2), " ", , a String, int (3). Java String " " , . , , , System.out.println(2+" "+3); ,

System.out.println(Integer.toString(2)+" "+Integer.toString(3));

System.out.println(2+' '+3); , java ' ' - , , java, char - java : java - - java int (2), (+), a char ( ) - , short, (+) int (3). 32, ,

System.out.println(Integer.toString(2+32+3));

Of course, the debate that continues behind the scenes is even more difficult than I could describe here. Why don't you try:

    System.out.println("The answer is "+(3+" "+2));
    System.out.println("The answer is "+(3+2));
    System.out.println("The answer is "+(3+' '+2));

or even

System.out.println('a' + 'b' + 'c');
0
source

Source: https://habr.com/ru/post/1606033/


All Articles