Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between single quotes and double quotes in java?

Tags:

java

I have

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

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

The first one prints 2 3 while the second prints 37 Can any of guys explain why it is printing 37???

like image 863
prasad Avatar asked Feb 09 '23 03:02

prasad


2 Answers

Quoting Java Language Specification for Additive Operators:

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

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

For Numeric Types:

Binary numeric promotion is performed on the operands (§5.6.2)

Binary Numeric Promotion:

[...] Otherwise, both operands are converted to type int.

So, 2+" "+3 is 2 + " ", which is a string concatenation, and String + 3 is also a string concatenation, hence 2 + " " + 3 is "2" + " " + "3" which means "2 3".

2+' '+3 is 2 + ' ', and the space literal is a char, so it is converted to int (32), and 2 + 32 + 3 is 37.


If the literals had been variables, it would actually be like this, where the assignment to a variable is only used to illustrate the type of the intermediate result:

// 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);

Both append() and println() are overloaded, so they are not all the same method.

Since they are literals, and not variables, the compiler will do it at compile-time, and you really get this (try disassembling a .class file to see for yourself):

System.out.println("2 3");
System.out.println(37);
like image 57
Andreas Avatar answered Feb 11 '23 17:02

Andreas


' '= 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
like image 44
Rustam Avatar answered Feb 11 '23 16:02

Rustam