the original question is like this.
public class test {
public static void main(String[] args){
int i = '1' + '2' + '3' + "";
System.out.println(i);
}
}
and this gives me an error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from String to int
then I changed the code like this:
public class test {
public static void main(String[] args){
int i = '1' + '2' + '3';
System.out.println(i);
}
}
the out put is 150.
but when I write my code like this:
public class test {
public static void main(String[] args){
System.out.println('a'+'b'+'c'+"");
}
}
the output become 294.
I wonder why.
The main difference between the two is that print() retains the cursor in the same line after printing the argument, while println() moves the cursor to the next line.
Java System. out. println() is used to print an argument that is passed to it.
The s1 is in the string pool whereas s2 is created in heap memory. Hence s1==s2 will return false.
In Java, System. out. println() is a statement which prints the argument passed to it. The println() method display results on the monitor. Usually, a method is invoked by objectname.
You can verify the values here for a,b and c (or any other character).
Edit : To explain why the last one output the correct value instead of throwing an error, you first sum all the values as explained before, then convert it to a String adding "" to the sum of the ASCII values of the chars. However, the println method expect a String which is why it does not throw any error.
The first one would work if you would do Integer.parseInt('1' + '2' + '3' + "");
When you do this
int i = '1' + '2' + '3';
the JVM sums the ASCII codes of the given numbers. The result is 150.
When you add the empty String
, you are trying to sum an int
/char
with a String
. This is not possible. You can implicitly convert char
to int
and vice versa because they are primitive types. You cannot do this with String
objects because they are not primitives but references. That's why you get an error.
When you do the println
the primitive values are firstly summed and the automatically boxed into reference type so the sum is boxed into a Character
object. The empty String
is converted to a Character
and then is added to the first one. So the result is a Character
object that has an ASCII code 294. Then the toString
method of the Character
is called because that's what the println(Object)
method does. And the result is 294
I hope this will help you to understand what is happening :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With