Can a variable String accept integer value as well. Or can we concat integer with a string ?
Example:
public class TestString1 {
public static void main(String[] args) {
String str = "420";
str += 42;
System.out.print(str);
}
}
I was expecting compilation error over here because String was getting concatenated with an integer.
JLS documentation on String concatination operator(+)-
15.18.1 String Concatenation Operator +
If only one operand expression is of type String, then string
conversion is performed on the other operand to produce a string at
run time. The result is a reference to a String object (newly created,
unless the expression is a compile-time constant expression
(§15.28))that is the concatenation of the two operand strings. The
characters of the left-hand operand precede the characters of the
right-hand operand in the newly created string. If an operand of type
String is null, then the string "null" is used instead of that operand
That is why String + int does not produce any error. And it prints 42042
None of the other answers have explained what's actually being executed here.
Your code will be converted to something like:
String str = "420";
// str += 42;
StringBuilder sb = new StringBuilder(str);
sb.append(42); // which internally does something similar to String.valueOf()
str = sb.toString();
System.out.print(str);
Anything that is given in double quotes is String and + is for concatenating string with an any value(int value).
So the integer value will be appended to the string.
Here
String str = "420";
str += 42; // 42 will be appended to 420 and result will be 42042
Adding an int to a String appends the int to the string, thus converting the int into a string.
x=20 y=10
I am showing the Order of precedence below from Higher to Low:
B - Bracket
O - Power
DM - Division and Multiplication
AS - Addition and Substraction
This works from Left to Right if the Operators are of Same precedence
Now
System.out.println("printing: " + x + y);
"printing: " : Is a String"
"+" : Is the only overloaded operator in Java which will concatenate Number to String. As we have 2 "+" operator here, and x+y falls after the "printing:" + as already taken place, Its considering x and y as Strings too.
So the output is 2010.
System.out.println("printing: " + x * y);
Here the
"*": Has higher precedence than +
So its x*y first then printing: +
So the output is 200
Do it like this if you want 200 as output in first case:
System.out.println("printing: "+ (x+y));
The Order of precedence of Bracket is higher to Addition.
Related
When adding 'a' + 'b' it produces 195. Is the output datatype char or int?
The result of adding Java chars, shorts, or bytes is an int:
Java Language Specification on Binary Numeric Promotion:
If any of the operands is of a reference type, unboxing conversion
(§5.1.8) is performed. Then:
If either operand is of type double, the
other is converted to double.
Otherwise, if either operand is of type
float, the other is converted to float.
Otherwise, if either operand
is of type long, the other is converted to long.
Otherwise, both
operands are converted to type int.
But note what it says about compound assignment operators (like +=):
The result of the binary operation is converted to the type of the left-hand variable ... and the result of the conversion is stored into the variable.
For example:
char x = 1, y = 2;
x = x + y; // compile error: "possible loss of precision (found int, required char)"
x = (char)(x + y); // explicit cast back to char; OK
x += y; // compound operation-assignment; also OK
One way you can find out the type of the result, in general, is to cast it to an Object and ask it what class it is:
System.out.println(((Object)('a' + 'b')).getClass());
// outputs: class java.lang.Integer
If you're interested in performance, note that the Java bytecode doesn't even have dedicated instructions for arithmetic with the smaller data types. For example, for adding, there are instructions iadd (for ints), ladd (for longs), fadd (for floats), dadd (for doubles), and that's it. To simulate x += y with the smaller types, the compiler will use iadd and then zero the upper bytes of the int using an instruction like i2c ("int to char"). If the native CPU has dedicated instructions for 1-byte or 2-byte data, it's up to the Java virtual machine to optimize for that at run time.
If you want to concatenate characters as a String rather than interpreting them as a numeric type, there are lots of ways to do that. The easiest is adding an empty String to the expression, because adding a char and a String results in a String. All of these expressions result in the String "ab":
'a' + "" + 'b'
"" + 'a' + 'b' (this works because "" + 'a' is evaluated first; if the "" were at the end instead you would get "195")
new String(new char[] { 'a', 'b' })
new StringBuilder().append('a').append('b').toString()
String.format("%c%c", 'a', 'b')
Binary arithmetic operations on char and byte (and short) promote to int -- JLS 5.6.2.
You may wish to learn the following expressions about char.
char c='A';
int i=c+1;
System.out.println("i = "+i);
This is perfectly valid in Java and returns 66, the corresponding value of the character (Unicode) of c+1.
String temp="";
temp+=c;
System.out.println("temp = "+temp);
This is too valid in Java and the String type variable temp automatically accepts c of type char and produces temp=A on the console.
All the following statements are also valid in Java!
Integer intType=new Integer(c);
System.out.println("intType = "+intType);
Double doubleType=new Double(c);
System.out.println("doubleType = "+doubleType);
Float floatType=new Float(c);
System.out.println("floatType = "+floatType);
BigDecimal decimalType=new BigDecimal(c);
System.out.println("decimalType = "+decimalType);
Long longType=new Long(c);
System.out.println("longType = "+longType);
Although c is a type of char, it can be supplied with no error in the respective constructors and all of the above statements are treated as valid statements. They produce the following outputs respectively.
intType = 65
doubleType = 65.0
floatType = 65.0
decimalType = 65
longType =65
char is a primitive numeric integral type and as such is subject to all the rules of these beasts including conversions and promotions. You'll want to read up on this, and the JLS is one of the best sources for this: Conversions and Promotions. In particular, read the short bit on "5.1.2 Widening Primitive Conversion".
The Java compiler can interpret it as either one.
Check it by writing a program and looking for compiler errors:
public static void main(String[] args) {
int result1 = 'a' + 'b';
char result2 = 'a' + 'b';
}
If it's a char, then the first line will give me an error and the second one will not.
If it's an int, then the opposite will happen.
I compiled it and I got..... NO ERRORS. So Java accepts both.
However, when I printed them, I got:
int: 195
char: Ã
What happens is that when you do:
char result2 = 'a' + 'b'
an implicit conversion is performed (a "primitive narrowing conversion" from int to char).
According to the binary promotion rules, if neither of the operands is double, float or long, both are promoted to int. However, I strongly advice against treating char type as numeric, that kind of defeats its purpose.
While you have the correct answer already (referenced in the JLS), here's a bit of code to verify that you get an int when adding two chars.
public class CharAdditionTest
{
public static void main(String args[])
{
char a = 'a';
char b = 'b';
Object obj = a + b;
System.out.println(obj.getClass().getName());
}
}
The output is
java.lang.Integer
char is represented as Unicode values and where Unicode values are represented by \u followed by Hexadecimal values.
As any arithmetic operation on char values promoted to int , so the result of 'a' + 'b' is calculated as
1.) Apply the Unicode values on corresponding char using Unicode Table
2.) Apply the Hexadecimal to Decimal conversion and then perform the operation on Decimal values.
char Unicode Decimal
a 0061 97
b 0062 98 +
195
Unicode To Decimal Converter
Example
0061
(0*163) + (0*162) + (6*161) +
(1*160)
(0*4096) + (0*256) + (6*16) + (1*1)
0 + 0 + 96 + 1 = 97
0062
(0*163) + (0*162) + (6*161) +
(2*160)
(0*4096) + (0*256) + (6*16) + (2*1)
0 + 0 + 96 + 2 = 98
Hence 97 + 98 = 195
Example 2
char Unicode Decimal
Ջ 054b 1355
À 00c0 192
--------
1547 +
1163 -
7 /
260160 *
11 %
While Boann's answer is correct, there is a complication that applies to the case of constant expressions when they appear in assignment contexts.
Consider the following examples:
char x = 'a' + 'b'; // OK
char y = 'a';
char z = y + 'b'; // Compilation error
What is going on? They mean the same thing don't they? And why is it legal to assign an int to a char in the first example?
When a constant expression appears in an assignment context, the Java compiler computes the value of the expression and sees if it is in the range of the type that you are assigning to. If it is, then an implicit narrowing primitive conversion is applied.
In the first example, 'a' + 'b' is a constant expression, and its
value will fit in a char, so the compiler allows the implicit narrowing of the int expression result to a char.
In the second example, y is a variable so y + 'b' is NOT a
constant expression. So even though Blind Freddy can see that the
value will fit, the compiler does NOT allow any implicit narrowing, and you get a compilation error saying that an int cannot be assigned to a char.
There are some other caveats on when an implicit narrowing primitive conversion is allowed in this context; see JLS 5.2 and JLS 15.28 for the full details.
The latter explains in detail the requirements for a constant expression. It may not be what you may think. (For example, just declaring y as final doesn't help.)
How to connect char number with char number?
My code is:
String room = "901";
// I want to a new String "01" so i do this
String roomNum = room.charAt(1) + room.charAt(2); // it's error
String roomNum = h.charAt(0).concat(h.charAt(1)); // error too
When I use String.valueOf() it gives me an ASCII.
String room = "901";
//I want to a new String "01":
Use:
room.subString(1);
String#subString(int) returns substring starting with int and ending with the last character.
For more subString overloads, have a look at String API.
If you want to concatenate two chars, you can do:
String room = "901";
char a = room.charAt(1);
char b = room.charAt(2);
String result = String.valueOf(a).concat(String.valueOf(b));
Otherwise, String roomNum = 'a'+'b'; will not compile, as the result of adding Java chars, shorts, or bytes is an int.
Beware, that char represents an Unicode Character (in Java, 16-bits each). So, each char value, under the hood, is encoded by numeric value, which is stored as a hexadecimal, decimal or other radix-system number. This is the main reason, why arithmetic operation on char value promotes to int.
While using substring will solve the problem (as in the answer of #Giorgi Tsiklauri), this doesn't point to the real hidden question posted that is:
Why a concatenation between chars is not the same of a concatenation of two strings of size 1 ?
That happens because the + symbol doesn't work as a concatenation in this context.
When you apply the + operator on chars a conversion to int is done before the operation. This operation is called Binary Numeric Promotion. From the second point in the JLS:
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
If either operand is of type double, the other is converted to double.
Otherwise, if either operand is of type float, the other is converted to float.
Otherwise, if either operand is of type long, the other is converted to long.
Otherwise, both operands are converted to type int.
So if you want to sum the string value of the 0 char and the string value of the 1 char you explicitly need to convert them in string as follow:
String room = "901";
String roomNumber = String.valueof(room.charAt(1)) + String.valueof(room.charAt(2));
If you do that the + operator is considered a concatenation between strings and not as a sum between int.
For example I want to concatanate char a ='A' and int b = 5 into string = "A5".
String string = a + b; doesn't work.
You may want to use StringBuilder, where you can append any type of primitives :
char a ='A';
int b = 5;
StringBuilder sb = new StringBuilder();
sb.append(a);
sb.append(b);
String result = sb.toString();
The easiest way for me is to precede the String with an empty String.
String str = "" + 'a' + 10;
The conversion goes from left to right so you start out with a String.
If you do it this way,
String str = 'a' + 10 + "";
you will get a String value of "107" since the numeric addition is done before the conversion to a String.
One way to convert most primitive values to String is to utilize the overloaded method in the String class valueOf():
public static void main(String[] args)
{
char a = 'A';
int b = 5;
String str = String.valueOf(a) + b; //Can do either of these two lines, will work the same
String str2 = a + String.valueOf(b);
System.out.println(str);
System.out.println(str2);
}
You only need to convert one of the values into String, because appending them afterward will automatically convert the other into a String.
This method will work on both char, and int in this scenario, but will also work on long, double, float and boolean as well. This is identical to calling Integer.toString(int i) or Character.toString(i) etc... but it is convenient to be able to use the same overloaded method for each case instead of requiring to call methods from different classes.
To all the answers already given I provide one that explain why "it doesn´t work" as you expect. A string is nothing but an immutable collection of char. A char itself is nothing but a (signed) integer and thus can implicitely converted to such. Thus when you write char+ int an integer-operation occurs, in your case A + 5 which results in 70, because ASCII-code for A is 65.
Last but not least String s = 70 surely does not compile, because a number can´t be converted to a string.
So you have to tell the compiler that you do not want an integer-operation, but a string-concatenation, which is by turning one of the operands into a string already:
String s = 'A'.toString() + 5
or
String s = 'A' + 5.toString()
The code is
String veggie = "eggplant";
int length = veggie.length();
char zeroeth = veggie.charAt(0);
char third = veggie.charAt(4);
String caps = veggie.toUpperCase();
System.out.println(veggie + " " + caps);
System.out.println(zeroeth + " " + third + " " + length);
System.out.println(zeroeth + third + length);
The output reads:
eggplant EGGPLANT
e 1 8
217
This doesn't make sense to me. Referencing a charAt outputs numbers instead of characters. I was expecting it to output the characters. What did I do wrong?
The second line should actually be:
e l 8
(note that the second value is a lower-case L, not a 1) which probably doesn't violate your expections. Although your variable is confusingly called third despite it being the fifth character in the string.
That just leaves the third line. The type of the expression
zeroeth + third + length
is int... you're performing an arithmetic addition. There's no implicit conversion to String involved, so instead, there's binary numeric promotion from each operand to int. It's effectively:
System.out.println((int) zeroeth + (int) third + (int) length);
It's summing the UTF-16 code units involved in 'e', 'l' and 8 (the length).
If you want string conversions to be involved, then you could use:
System.out.println(String.valueOf(zeroeth) + third + length);
Only the first addition needs to be a string concatenation... after that, it flows due to associativity. (i.e. x + y + z is (x + y) + z; if the type of x + y is String, then the second addition also becomes a string concatention.)
The compiler interprets all variables as values rather than a string.
Try System.out.println("" + zeroeth + third + length);
This line is doing integer arithmetic:
System.out.println(zeroeth + third + length);
In other words, it is adding the unicode values of each character (i.e. e is 101, l is 108, 8 is 8). To do String concatenation, you can add an empty String to the front:
System.out.println("" + zeroeth + third + length);
Since it is evaluated left-to-right, it will first do String concatenation (not addition). It will continue to do this for third and length. Adding "" at the end won't work, because addition will occur first.
You can use the method of the wrapper class Character to display the string values of char variables:
System.out.println(Character.toString(zeroeth) + Character.toString(third) + length);
This way, you always work with String values and there are no possibilities for the numeric values of the chars to be displayed or added and you don't need to concatenate with empty strings ("") to convert the char variables to String values.
When adding 'a' + 'b' it produces 195. Is the output datatype char or int?
The result of adding Java chars, shorts, or bytes is an int:
Java Language Specification on Binary Numeric Promotion:
If any of the operands is of a reference type, unboxing conversion
(§5.1.8) is performed. Then:
If either operand is of type double, the
other is converted to double.
Otherwise, if either operand is of type
float, the other is converted to float.
Otherwise, if either operand
is of type long, the other is converted to long.
Otherwise, both
operands are converted to type int.
But note what it says about compound assignment operators (like +=):
The result of the binary operation is converted to the type of the left-hand variable ... and the result of the conversion is stored into the variable.
For example:
char x = 1, y = 2;
x = x + y; // compile error: "possible loss of precision (found int, required char)"
x = (char)(x + y); // explicit cast back to char; OK
x += y; // compound operation-assignment; also OK
One way you can find out the type of the result, in general, is to cast it to an Object and ask it what class it is:
System.out.println(((Object)('a' + 'b')).getClass());
// outputs: class java.lang.Integer
If you're interested in performance, note that the Java bytecode doesn't even have dedicated instructions for arithmetic with the smaller data types. For example, for adding, there are instructions iadd (for ints), ladd (for longs), fadd (for floats), dadd (for doubles), and that's it. To simulate x += y with the smaller types, the compiler will use iadd and then zero the upper bytes of the int using an instruction like i2c ("int to char"). If the native CPU has dedicated instructions for 1-byte or 2-byte data, it's up to the Java virtual machine to optimize for that at run time.
If you want to concatenate characters as a String rather than interpreting them as a numeric type, there are lots of ways to do that. The easiest is adding an empty String to the expression, because adding a char and a String results in a String. All of these expressions result in the String "ab":
'a' + "" + 'b'
"" + 'a' + 'b' (this works because "" + 'a' is evaluated first; if the "" were at the end instead you would get "195")
new String(new char[] { 'a', 'b' })
new StringBuilder().append('a').append('b').toString()
String.format("%c%c", 'a', 'b')
Binary arithmetic operations on char and byte (and short) promote to int -- JLS 5.6.2.
You may wish to learn the following expressions about char.
char c='A';
int i=c+1;
System.out.println("i = "+i);
This is perfectly valid in Java and returns 66, the corresponding value of the character (Unicode) of c+1.
String temp="";
temp+=c;
System.out.println("temp = "+temp);
This is too valid in Java and the String type variable temp automatically accepts c of type char and produces temp=A on the console.
All the following statements are also valid in Java!
Integer intType=new Integer(c);
System.out.println("intType = "+intType);
Double doubleType=new Double(c);
System.out.println("doubleType = "+doubleType);
Float floatType=new Float(c);
System.out.println("floatType = "+floatType);
BigDecimal decimalType=new BigDecimal(c);
System.out.println("decimalType = "+decimalType);
Long longType=new Long(c);
System.out.println("longType = "+longType);
Although c is a type of char, it can be supplied with no error in the respective constructors and all of the above statements are treated as valid statements. They produce the following outputs respectively.
intType = 65
doubleType = 65.0
floatType = 65.0
decimalType = 65
longType =65
char is a primitive numeric integral type and as such is subject to all the rules of these beasts including conversions and promotions. You'll want to read up on this, and the JLS is one of the best sources for this: Conversions and Promotions. In particular, read the short bit on "5.1.2 Widening Primitive Conversion".
The Java compiler can interpret it as either one.
Check it by writing a program and looking for compiler errors:
public static void main(String[] args) {
int result1 = 'a' + 'b';
char result2 = 'a' + 'b';
}
If it's a char, then the first line will give me an error and the second one will not.
If it's an int, then the opposite will happen.
I compiled it and I got..... NO ERRORS. So Java accepts both.
However, when I printed them, I got:
int: 195
char: Ã
What happens is that when you do:
char result2 = 'a' + 'b'
an implicit conversion is performed (a "primitive narrowing conversion" from int to char).
According to the binary promotion rules, if neither of the operands is double, float or long, both are promoted to int. However, I strongly advice against treating char type as numeric, that kind of defeats its purpose.
While you have the correct answer already (referenced in the JLS), here's a bit of code to verify that you get an int when adding two chars.
public class CharAdditionTest
{
public static void main(String args[])
{
char a = 'a';
char b = 'b';
Object obj = a + b;
System.out.println(obj.getClass().getName());
}
}
The output is
java.lang.Integer
char is represented as Unicode values and where Unicode values are represented by \u followed by Hexadecimal values.
As any arithmetic operation on char values promoted to int , so the result of 'a' + 'b' is calculated as
1.) Apply the Unicode values on corresponding char using Unicode Table
2.) Apply the Hexadecimal to Decimal conversion and then perform the operation on Decimal values.
char Unicode Decimal
a 0061 97
b 0062 98 +
195
Unicode To Decimal Converter
Example
0061
(0*163) + (0*162) + (6*161) +
(1*160)
(0*4096) + (0*256) + (6*16) + (1*1)
0 + 0 + 96 + 1 = 97
0062
(0*163) + (0*162) + (6*161) +
(2*160)
(0*4096) + (0*256) + (6*16) + (2*1)
0 + 0 + 96 + 2 = 98
Hence 97 + 98 = 195
Example 2
char Unicode Decimal
Ջ 054b 1355
À 00c0 192
--------
1547 +
1163 -
7 /
260160 *
11 %
While Boann's answer is correct, there is a complication that applies to the case of constant expressions when they appear in assignment contexts.
Consider the following examples:
char x = 'a' + 'b'; // OK
char y = 'a';
char z = y + 'b'; // Compilation error
What is going on? They mean the same thing don't they? And why is it legal to assign an int to a char in the first example?
When a constant expression appears in an assignment context, the Java compiler computes the value of the expression and sees if it is in the range of the type that you are assigning to. If it is, then an implicit narrowing primitive conversion is applied.
In the first example, 'a' + 'b' is a constant expression, and its
value will fit in a char, so the compiler allows the implicit narrowing of the int expression result to a char.
In the second example, y is a variable so y + 'b' is NOT a
constant expression. So even though Blind Freddy can see that the
value will fit, the compiler does NOT allow any implicit narrowing, and you get a compilation error saying that an int cannot be assigned to a char.
There are some other caveats on when an implicit narrowing primitive conversion is allowed in this context; see JLS 5.2 and JLS 15.28 for the full details.
The latter explains in detail the requirements for a constant expression. It may not be what you may think. (For example, just declaring y as final doesn't help.)