Why printing "" + variables output each variable individually without spacing? - java

One of my assignments has this code:
System.out.println("" + x + y + count);
that outputs the value of x, y and count individually without any spaces. I would like to know more about it online. However, I can't seem to find the right keywords to search it up online. Can someone please explain to me the logic behind this or perhaps point to me a name or keyword for such a situation?
I have always known the " " as a tool to print out a string so I'm confused by this.
Thanks in advance.

If we apply standard Java precedence rules, the statement:
System.out.println("" + x + y + count);
is equivalent to
System.out.println((("" + x) + y) + count);
Then we look at the meaning of +
If the static types of both a and b are numeric types (either primitive numeric or their boxed types) then a + b is numeric addition.
Otherwise, a + b is string concatenation. The two arguments are converted to strings and the strings are concatenated.
Based on this we can say that all of the + operators in the example will be treated as string concatenations.
If you want spaces between x, y and count you need to add some string literals; e.g.
System.out.println("" + x + " " + y + " " + count);
or, more simply:
System.out.println(x + " " + y + " " + count);
If you wanted x, y and count to be added (assuming that they are numeric), then you could write this:
System.out.println("" + (x + y + count));
or, more simply:
System.out.println(x + y + count);
The latter is using a different overload of println.
I have always known the "" as a tool to print out a string so I'm confused by this.
Ummm ... it is actually an empty string literal. The usage "" + x is simply an idiom for converting x to a String. The empty string literal has other uses too. The main one is to represent a String with zero characters.

Or you can use String format like this:
System.out.printf("%d%d%d", x, y, count);

The "" is an empty String. In Java when you concatenate a String with other primitives that can be cast to String the result is a String. That means that the code
System.out.println("" + something);
is a different way to write
System.out.println(String.valueOf(something));
However in your scenario the "" + x + y + count means that the elements are converted to String and then concatenated - this means that if x==1, y==2, count==3 the result would be 123. If you wanted to just cast the result to String you would have to indicate that the computation should happen before casting to String for example by using brackets
System.out.println("" + (x+y+count));
The output of this would be 6.

Related

System.out.println behavior when using String and int together [duplicate]

This question already has answers here:
Java String Concatenation with + operator
(5 answers)
Closed 3 years ago.
Consider the below code snippet -
public class Student {
public static void main(String args[]) {
int a = 3;
int b = 4;
System.out.println(a + b +" ");
System.out.println(a + b +" "+ a+b);
System.out.println(""+ a+b);
}
}
The output for the above snippet is coming as -
7
7 34
34
It is clear from the output that if we use String at first in the print statement then the integers are concatenated. But, if we use integer at first then the values are added and displayed.
Can someone please explain why is this behavior?
I even tried to look at the implementation of println() method in PrintStream class but could not figure out.
Actually it's not println() implementation who's causing that, this is Java way to treat the + operator when dealing with Strings.
In fact the operation is treated from left to right so:
If the string comes before int (or any other type) in the operation String conversion is used and all the rest of the operands will be treated as strings, and it consists only of a String concatenation operation.
If int comes first in the operation it will be treated as int, thus addition operation is used.
That's why a + b +" " gives 7 because Stringis in the end of the operation, and for other expressions a + b +" "+ a+b or ""+ a+b, the variables a and b will be treated as strings if the come after a String in the expression.
For further details you can check String Concatenation Operator + in Java Specs.
It has nothing to do with the implementation of println. The value of the expression passed to println is evaluated before println is executed.
It is evaluated left to right. As long as both operands of + are numeric, addition will be performed. Once at least one of the operands is a String, String concatenation will be performed.
System.out.println(a + b + " ");
// int + int int + String
// addition, concatenation
System.out.println(a + b + " " + a + b);
// int + int int + String Str+Str Str+Str
// addition, concat, concat, concat
System.out.println("" + a + b);
// String+int String+int
// concat, concat
First case:
System.out.println(a + b +" ");
In this order, a + b will first be evaluated as a int sum, then converted to a string when adding the space (the second + here is for string concatenation).
Second case:
System.out.println(a + b +" "+ a+b);
Here the first part will be int sum operation then converted to a string as we add the space (the 2nd + is for string concatenation), the rest will be string concatenation as the left operand is already a string.
Third case:
System.out.println(""+ a+b);
Same as 2nd.
Notes:
In order to change this behavior, just add parenthesis to force the int sum before the string concatenations.

Strange result when trying to add a char after an integer and then print the result

I'm trying to create a simple calculator voor Ohm's law.
So the idea is that you can fill in 2 variables and then it will calculate the third variable.
When I was creating this program, I found a little problem and I don't understand how it happens and unfortunately I'm not able to find the answer.
I tried to print a String where the complete calculation is shown. So the 2 variables the user filled in and the answer. After the variable for Ohm ('R' in this example) the correct symbol should be printed aswell.
As shown in the example below, the only way I can add the symbol after the variable is by first adding an empty string(""). Otherwise the unicode wil be added to the variable?!
I've made a quick example to show my problem:
public class Main {
public static void main(String[] args) {
float R = 2.54f;
float U = 4.00f;
float I = R / U;
char ohm = '\u2126';
System.out.println(R + "" + ohm + " (R) / " + U + "V (U) = " + I + "A (I)");
System.out.println(R + ohm + " (R) / " + U + "V (U) = " + I + "A (I)");
}
}
Result in console:
2.54Ω (R) / 4.0V (U) = 0.635A (I)
8488.54 (R) / 4.0V (U) = 0.635A (I)
As you can see, the second print doesn't show the Ohm symbol, but adds a value to the variable 'R'. Hopefully I've made my question clear enough.
Thanks in advance.
R + ohm performs a numeric addition of a float and a char (which is an integral type). Therefore you see a float result instead of the String concatenation you expect. The float result you see is 8486 + 2.54 (since 8486 is the decimal value of the hexadecimal number 2126).
In your first println statement you avoid that by concatenating a String ("") to the float, which results in a String. Then the Ohm char is concatenated to that String.
You can also begin with the empty String to get the desired output:
System.out.println("" + R + ohm + " (R) / " + U + "V (U) = " + I + "A (I)");

String.equals comparison fails to match

I am using .equals for String comparison below, but x does not match "OU":
String memberOfValue="CN=cn,​OU=ou,​OU=roles,​OU=de,​OU=apps,​DC=meta,​DC=cc,​DC=com";
String[] pairs = memberOfValue.split(",");
for (int i=0;i<pairs.length;i++) {
String pair = pairs[i];
String[] keyValue = pair.split("=");
System.out.println(keyValue[0]);
String x = keyValue[0];
String y = "OU";
System.out.println(x);
System.out.println(x.equals(y));
}
Where am I going wrong?
Adding these two lines of code shows the problem:
System.out.println("x: " + x + " - " + x.chars().boxed().collect(Collectors.toList()));
System.out.println("y: " + y + " - " + y.chars().boxed().collect(Collectors.toList()));
It gives
x: ​OU - [8203, 79, 85]
y: OU - [79, 85]
Which shows that you have some invisible char whose integer value is 8203 (zero width space, see What's HTML character code 8203?) in your string. Not sure how you got that.
As #JB Nizet says, you have non-printable characters in your memberOfValue variable, there are some types of characters as for example:
control, format, private use, surrogate, unassigned, etc...
Here is the complete list: http://www.fileformat.info/info/unicode/category/index.htm
In these cases, you can remove all characters from your string using this regular expression: \\P{Print}
For example:
String x = keyValue[0].replaceAll("[\\P{Print}", "");
When you compare the strings again, the result will be correct.
There are two possible problems from what I'm seeing.
A.) If the strings are capitalized differently they will not return equal unless you use the method .equalsIgnoreCase() instead of .equals()
B.) You're not getting the right strings that you're expecting. Be sure to print out or debug which string is getting parsed through.

If statement running when false

I'm attempting to write some code for a game in Java, however one of the if statements isn't working as expected.
if(player.gety() < y+row*tileSize){
player.draw(g);
System.out.println("Row: " + y+row*tileSize);
System.out.println("Player: " + player.gety());
}
When this code is run the output that I receive is:
Player: 200
Row: -79.99999999968651320
Player: 200
Row: -79.99999999968651320
Player: 200
Row: -79.99999999968651320
This doesn't make much sense as player.gety() is clearly larger than y+row*tileSize. Is there any reason why this would be happening?
String concatenation is what's tripping you up here. Specifically,
"Row: " + y+row*tileSize
is not the same thing as
"Row: " + (y+row*tileSize)
In the first case, you're getting
("Row: " + y)+ (row*tileSize)
where y is being converted to its String representation and concatenated onto "Row: ", and then the product of row * tileSize is getting converted to its String representation and concatenated onto that.
In the second case, you'd be getting (y + row * tileSize), a single numeric value, which would then be turned into a String representation and concatenated onto the String "Row: :"
This is actually behaving as demanded by the spec. When either operand of the + operator is a String, it no longer means "addition", it means "concatenation", and concatenation does not obey the arithmetical rules of precedence. Instead, it greedily coerces its other operand to a String value and cats the two together.
This can have some unexpected results, as you've discovered. Try adding the parens as suggested above, or printing out the values of the variables individually:
System.out.println("y = "+ y + " row = "+row + " tileSize = " + tileSize)
and it'll be easier to see what's happening.
EDIT:
I expect that you'll find that More likely, y = -79.999999999 (ie, -79.9, repeating) and row*tileSize=68651320. Adding those up you get substantially more than 200.
Yes, I don't think the Row output statement is showing what you think it's showing. Also, might player.draw(g) modify the result of player.gety()? Put the output statements first in the if-true block. Output each variable instead of an expression.

Why does the expression x+x not print the same result in the two places it appears? [duplicate]

This question already has answers here:
Java: sum of two integers being printed as concatenation of the two
(10 answers)
Closed 7 years ago.
Why does the expression x+x not print the same result in the two places it appears?
String s = args[0];
System.out.println("Hello "+s);
int x = 40;
System.out.println(x);
System.out.println(x+x);
System.out.println(s+" "+x+x);
The result of this code is when I execute in cmd java EG1 kaan
Hello kaan
40
80
kaan4040
why is the last result of the print displaying kaan4040 and not kaan80?
Because of automatic conversion to String.
On this line you "start printing" an integer, so adding another integer to it will again produce integer that is then converted to String and printed out:
System.out.println(x + x); // integer + integer
However on this line you "start printing" a String, so all other values you add to it are at first converted to String and then concatenated together:
System.out.println(s + " " + x + x); // String + String + integer + integer
If you want the two integers to be added together before the concatenation is done, you need to put brackets around it to give it a higher priority:
System.out.println(s + " " + (x + x)); // String + String + integer
In your last print statement, you are doing a string concatenation instead of an arithmetic addition.
Change System.out.println(s+" "+x+x) to System.out.println(s+" "+(x+x)).
Make changes System.out.println(s+" "+x+x); to System.out.println(s+" "+(x+x)); Because it need to add the value and then string concatenation
Because java does some work with your code. When you do System.out.println(x+x);, it sees x+x as an expression with two ints and evaluates it (which is 80). When you do ""+x+x, it sees 3 String, and thus evaluates this expression as a String concatenation.
(btw, by it, I mean javac, and "sees", I mean, well "reads")
Or change print code to System.out.println(x +x+" " +s );
You are performing concatenation instead of addition
Whenever you append anything to string then it will result to string only. You have appended x+x to " " which will append 40 after name. You can use System.out.println(s+" "+(x+x)).
On the last print statement:
System.out.println(s+" "+x+x);
s is a string and is concatenated with " ", from left to right the expression formed by concatenation with s and " ", is then concatenated with x and then ( s + " " + x ) is concatenated with x, yielding kaan4040.
If the + operator is used with:
2 Strings, concatenation occurs
1 String and 1 int, concatenation occurs
2 ints, arithmetic addition
Consider the following scenario:
System.out.println(x + x + " " + "hello");
In this example 80Kaan is printed as arithmetic addition occurs between x and x, then the resulting value (80) is concatenated with the space and hello.
Read from left to right.
int x = 40;
System.out.println(x);
System.out.println(x + x);
System.out.println("" + x + x);
40
80
4040
40 is int 40
80 is int 40 + int 40 (Maths)
4040 is String 40 concat String 40 (because add "" String)
String s = args[0];
System.out.println("Hello "+s);
int x = 40;
System.out.println(x); //1st statement
System.out.println(x+x); //2nd statement
System.out.println(s+" "+x+x); //3rd statement
The first statement simply converts x into String
The second satatement added the numbers because there aren't strings, the compiler thinks of plus sign as addition of two numbers.
the third one sees that there is a string so the compiler thinks like:
print the value of s, add space(" "), add the value of x (convert x into string), add the value of x (convert x into string ).
Hence, Kaan4040.
If you want to print 80, you can do it in two ways:
int sum = x+x;
System.out.println(s+" "+sum); //more readable code
or
System.out.println(s+" "+ (x+x) ); //may confuse you
the compiler will think of x+x as integers since it doesn't find any string inside the parenthesis. I prefer the first one though. :)
why is the last result of the print displaying kaan4040 and not kaan80?
This is because this is how String behaves when used with the + symbol. and it can mean differently when used in a println method.
It means String concatenation when you use it with a String
The 5 even though being an integer will be implicitly converted to String.
E.g:
System.out.println("Hello" + 5); //Output: Hello5
It become mathematical operation:plus when used within a pair of brackets because the brackets will be operated first (add first), then convert to String.
The 1st + is concatenation, and 2nd + is add (Refer to codes below).
E.g:
System.out.println("Hello" + (5+7)); //Output: Hello12
If any one of the '+' operator operand is string, then java internally create 'StringBuilder' and append those operands to that builder. for example:
String s = "a" + 3 + "c";
it's like
String s = new StringBuilder("a").append(3).append("c").toString(); //java internally do this

Categories