Difference between String.valueOf(int i) and printing only i - java

See the below code snippet:
int count = 0;
String query = "getQuery";
String query1 = "getQuery";
final String PARAMETER = "param";
query += "&" + PARAMETER + "=" + String.valueOf(count);
query1 += "&" + PARAMETER + "=" + count;
System.out.println("Cast to String=>"+query);
System.out.println("Without casting=>"+query1);
Got the both output exactly same. So I am wondering why this has been used when we can get the same result by using only count.
I got some link but did not found exactly same confusion.

This is well explained in the JLS - 15.18.1. String Concatenation Operator +:
If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
You should note the following:
The + operator is syntactically left-associative, no matter whether it
is determined by type analysis to represent string concatenation or
numeric addition. In some cases care is required to get the desired
result.
If you write 1 + 2 + " fiddlers" the result will be
3 fiddlers
However, writing "fiddlers " + 1 + 2 yields:
fiddlers 12

Java compiler plays a little trick when it sees operator + applied to a String and a non-string: it null-checks the object, calls toString() on it, and then performs string concatenation.
That is what's happening when you write this:
query1 += "&" + PARAMETER + "=" + count;
// ^^^ ^^^^^^^^^ ^^^
You can certainly do this when the default conversion to String is what you want.
However, if you do this
String s = count; // <<== Error
the compiler is not going to compile this, because there is no concatenation. In this situation you would want to use valueOf:
String s = String.valueOf(count); // <<== Compiles fine

String.valueOf(int) actually calls Integer.toString().
So, it is used to convert an int to a String elegantly. As, doing i+"" is IMNSHO, not quite elegant.
Moreover, when you print any number directly, it actually calls the toString() method of its Wrapper class, and the prints the string.

Related

The purpose of double quotes ("") with integer concatenation

I just started the "Head First Java" book. There is an exercise that is tripping me up due to the double quotes ("") with no space in the code below. I think I figured it out, but it doesn't look like the book explains it and I would like to make sure I am correct moving forward.
Is the purpose of the double quotes ("") in the code below to concatenate the two integers (x and y) and prevent the + operator from performing addition for the output? That's what it seems.
The OUTPUT for the code below is: 00 11 21 32 42.
I deleted the double quotes and the output gives me: 0 2 3 5 6.
class Test
{
public static void main (String[] args)
{
int x = 0;
int y = 0;
while ( x < 5)
{
y = x - y;
System.out.print(x + "" + y + " ");
x = x + 1;
}
}
}
To answer your direct question: you are correct that the "" is there to turn the + into a concatenation, rather than addition. But I'll give a few more details as to what's going on here.
It's perhaps a little bad of the authors of the book to use this without explaining, since this appears to be a key thing in the exercise (even a brief footnote saying "this is just an easy way to convert to a String"); but it's one of those things most Java programmers wouldn't even think about needing to explain, so easy to miss; or, perhaps they did explain it earlier, and you just missed it, because of the throw-away nature of the explanation. No accusations; it's just what it is.
We're trying to evaluate the expression x + "" + y + " " in order to print it. Because + is left-associative, this is evaluated as
((x + "") + y) + " "
So, in terms of the effect of including "", the question is how the subexpression x + "" will be evaluated. If the "" had been omitted, it would be evaluated as
(x + y) + " "
There is no separate operator for "numeric addition" and "string concatenation" in Java: both use +. So, Java uses a simple rule to decide between the two:
If the type of either operand of a + operator is String, then the operation is string concatenation.
As such, x + "" is string concatenation, but x + y would be numeric addition.
If you look into the specifics of string concatenation:
If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
So this is saying that the int in int + String has to be converted to a string, in order to concatenate it with another string, which is pretty reasonable. And this string conversion is done using:
If T is byte, short, or int, then use new Integer(x).
...
the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments
("as if" is just wiggle room to say you don't actually have to invoke new Integer(x) - implementations could use Integer.toString(x), or some other method, instead).
Then, concatenation is defined as:
The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.
Given that "" has no characters, it is trivially true that someString + "" will have the same characters as someString (*).
So, int + "" (or "" + int) is simply a syntactic trick to convert the int to a String. There is no other effect of doing this. It's just less verbose to write this than Integer.toString(x) or new Integer(x).toString().
It's also worth pointing out that it would work the same had it been "" + x + y + " ". But that's perhaps less clear to the human eye that the x and y won't be added.
(*) The slight detail here is that concatenation results in a new string (unless the two operands are constant expressions, in which case the concatenation is done at compile time), i.e. someString + "" != someString, even though (someString + "").equals(someString).
Is the purpose of the double quotes ("") in the code below to
concatenate the two integers (x and y) and prevent the + operator from
performing addition for the output?
That's exactly what it is. The alternative would be something like
print(String.valueOf(x) + String.valueOf(y) + " ")
which is a lot less readable. The String type can be forced also in the beginning, as in "" + x + y + " ", just as long as we're dealing with Strings before we start to use the + operator.

Why do we print variable values like this?

I want to know why we concatenate a dummy string with a variable while printing its value.
Eg.
system.out.print(var + " ");
Concatenation with an empty string is a technique some developers use to convert any value to a string. It's unnecessary with System.out.print as that accepts any value anyway. I prefer using String.valueOf anyway:
String text = String.valueOf(variable);
This is clearer in terms of the purpose being converting a value to a string, rather than concatenation.
However, in the case you've given, it's possible that the developer wasn't just using concatenation for that purpose - but actually to get the extra space. For example:
int var1 = 1, var2 = 2, var3 = 3;
System.out.print(var1 + " ");
System.out.print(var2 + " ");
System.out.print(var3 + " ");
Those will all print on the same line:
1 2 3
Other options include:
Using a StringBuilder to build up the string before printing it
Putting it all into a single System.out.print call: System.out.print(var1 + " " + var2 + " " + var3);
Using printf instead: System.out.printf("%d %d %d", var1, var2, var3);
Extremely sorry. The question was l1.setText(var+" "); and it is done because a text field cannot take an integer value, so we concatenate a dummy string at the end of it, so the integer value in var can be printed.
Thank you all for helping me out!

String n = new String( char + int) adds but should concatenate

I have the following code for a class:
public class sqrt
{
public sqrt()
{
char start = 'H';
int second = 3110;
char third = 'w';
byte fourth = 0;
char fifth = 'r';
int sixth = 1;
char seventh = 'd';
float eighth = 2.0f;
boolean ninth = true;
String output = new String(start + second + " " + third + fourth +
fifth + sixth + seventh + " " + eighth + " " + ninth);
System.out.println(output);
}
}
The required output is:
H3110 w0r1d 2.0 true
However, this outputs the following:
3182 w0r1d 2.0 true
I can only assume this is because it sees the numerical (ASCII) value of char 'H' and adding it to int 3110.
My question is:
Shouldn't new String() convert each item within to a string and concatenate them?
If I change the output to:
String output = start + second + " " + third + fourth +
fifth + sixth + seventh + " " + eighth +
" " + ninth;
It does the same thing, and adds the value of char and int together before concatenating the rest.
I know I can overcome this by adding a "" + before start, and I suppose that explains why it is seeing the ASCII value of char 'H' (because it looks at the next value, sees it's an int, and goes from there?), but I'm confused as to why the new String() isn't working as intended.
PS, I want to write better questions, and I know I am still a bit of a beginner here, so any advice in that regard would be appreciated as well. PMs are more than welcome, if anyone is willing to take the time to help.
PPS, If I figure out why this is, I will post the answer myself, but I am really trying to learn this, and I'm just very confused.
I can only assume this is because it sees the numerical (ASCII) value of char 'H' and adding it to int 3110.
That's perfectly correct.
Shouldn't new String() convert each item within to a string and concatenate them?
The String constructor has no control over this, because the expression start + second + " " + ... is evaluated before.
The concise approach here is to use a StringBuilder. It has methods to accept all primitive types and arbitrary objects.
String output = new StringBuilder().append(start).append(second).append(' ')
.append(third).append(fourth).append(fifth).append(sixth).appends(seventh)
.append(' ').append(eighth).append(' ').append(ninth).toString();
or
StringBuilder builder = new StringBuilder();
builder.append(first);
builder.append(second);
builder.append(' ');
builder.append(third);
builder.append(fourth);
builder.append(firth);
builder.append(sixth);
builder.append(seventh);
builder.append(' ');
builder.append(eighth);
builder.append(ninth);
String output = builder.toString();
Shouldn't new String() convert each item within to a string and concatenate them?
new String() has nothing to do with it. First we evaluate the expression. Then we pass the value of the expression to the String constructor.
So first of all we're adding a char to an int; this is integer addition. Then the result of that (3112) is converted to string so it can be concatenated to the string " ". Thereafter at least one operand is a String therefore concatenation applies.
I'm confused as to why the new String() isn't working as intended.
It's working as intended, which is to initialize a new String object representing the data passed to it.
Shouldn't new String() convert each item within to a string and
concatenate them?
Currently, you're using this overload of the String constructor which states:
Initializes a newly created String object so that it represents the
same sequence of characters as the argument; in other words, the newly
created string is a copy of the argument string.
Essentially, as the string you passed to the String constructor is 3182 w0r1d 2.0 true the new string object is a copy of that. Nothing else is performed.
you can use the code below since characters cannot be changed to string inherently
so:
String output = new String(String.valueOf(start) + second + " " + third + fourth +
fifth + sixth + seventh + " " + eighth + " " + ninth);

What happens if you remove the space between the + and ++ operators?

EDIT 1
DISCLAIMER: I know that +++ is not really an operator but the + and ++ operators without a space. I also know that there's no reason to use this; this question is just out of curiosity.
So, I'm interested to see if the space between + and ++var is required in Java.
Here is my test code:
int i = 0;
System.out.println(i);
i = i +++i;
System.out.println(i);
This prints out:
0
1
which works as I would expect, just as if there were a space between the first and second +.
Then, I tried it with string concatenation:
String s1 = "s " + ++i;
System.out.println(s1);
// String s2 = "s " +++i;
This prints out:
s 2
But if the third line is uncommented, the code does not compile, with the error:
Problem3.java:13: unexpected type
required: variable
found : value
String s2 = "s " +++i;
^
Problem3.java:13: operator + cannot be applied to <any>,int
String s2 = "s " +++i;
^
What's causing the difference in behavior between string concatenation and integer addition?
EDIT 2
As discussed in Abhijit's follow-up question, the rule that people have mentioned (the larger token ++ be parsed first, before the shorter token ++) is discussed in this presentation where it appears to be called the Munchy Munchy rule.
There is no +++ operator. What you have there is a postfix ++ operator followed by an infix + operator. That is a compilation error because postfix ++ can only be applied to a variable, and "s " isn't a variable.
Since you really mean an infix + operator followed by a prefix ++ operator, you need to put the space in between the operators.
Actually, you should do it ANYWAY. +++ is a crime against readability!!!
Compiler generates longest possible tokens when parsing source, so when it encounters +++, it takes it as ++ +.
So the code of
a +++ b
Will always be same as
(a++) + b
The triple plus is not an operator itself, it is two operators combined:
What the triple plus acutually does is:
a+++1 == a++ + 1;
What you are trying to do is ++ a String, which is undefined.
Never ever use +++ without spaces in your code; hardly anyone will know what it does (without consulting web). Moreover, after a week or so, you will not know what it actually does yourself.
+++ isn't an operator by itself.
i = i +++i; results in a pre-increment value of i, then adding it to the value of i and storing it in i.
With the String, + doesn't mean addition, so you're attempting to concatenate the string and the integer together.

why does java starts treating everything as a String once it has encountered a string in System out statement?

i am learning java and practicing it daily,i wrote the following code and wondered about the output
class test
{
public static void main(String args[])
{
System.out.println(1+2+ " = " +10+2);
}
}
here the output was 3=102,and wondered about the following "Java starts treating everything as a String once it has encountered a string in System out statement"
can anyone explain this ?i m confused why does it accept it as string?
Java parses program text without regard to the types of expression. As motivation, consider if they were fields written after the method in the class. So, as string concatenation and addition share the same operator, we have
1+2+ " = " +10+2
is equivalent to
((((1+2)+ " = ") +10)+2)
Folding constants, we have
(((3+ " = ") +10)+2)
(("3 = " +10)+2)
("3 = 10"+2)
"3 = 102"
"Java starts treating everything as a String once it has encountered a
string in System.out statement"
It's completely wrong. System.out is a static instance of the class PrintStream.
PrintStream has many overloaded versions of the println() method and the one in your example accepts String as parameter. You are using + operator and it's for concatenation of Strings unless the operands are both numbers.
System.out.println(3+5+"."); // println(String) is invoked.
System.out.println(3+5); // println(int) is invoked.
+ with String becomes String concatenation operator and not a addition operator.
1 + 2 + 10 + 2 will be equal to 15 as a simple addition
while
1 + 2 + "+" + 10 + 2 will be treated as
1. 1 + 2 output will be 3 as it is a simple addition
2. 3 + = (String) output will be 3= because it is String concatenation
3. 3= (String) + 10 + 2 will be String concatenation and not a simple addition so output will be 3=102
(1+2) -- two integres additoin will result int 3
(3 + " = ") -- this will result int + String = String (concatination)
("3=") -- String + any thing (data type) will result String

Categories

Resources