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

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.

Related

Is it possible to add integer values while concatenating Strings? [duplicate]

This question already has answers here:
concatenating string and numbers Java
(7 answers)
Closed 1 year ago.
Consider the following code (excerpt of main method):
String str = "The result: ";
int c = 5;
int k = 3;
System.out.println(str + c + k); // This would concatenate the all values, i.e. "The result: 53"
If the only thing allowed to be modified is within System.out.println(), is it possible to concatenate str to the sum of k and c?
Yes.
System.out.println(str + (c + k));
You can change order of execution by adding parentheses (same way as in math).
Indeed, as #talex said, you may use this single line code.
Yet, I think that this additude is a bit confusing, and may cause the code to be unreadable.
A better practice would be:
String str = "The result: ";
int c = 5;
int k = 3;
int result = c + k;
System.out.println(str + result);
This way, the code is more readable, and the order of execution will not confuse the programmers that read this code.
Yes
you should have use parentheses around sum of integers
System.out.println(str + (c + k));

Evaluation Order with string and ints

String s1 = "six" + 3 + 3;
String s2 = 3 + 3 + "six:";
System.out.println(s1);
System.out.print(s2);
Output :
six33
6six:
Why is 3+3 not added in the first one but is added in the second one?
The order of the operation is important
In the first one the concatenation works like so :
String s1 = "six" + 3 + 3;
"six3" + 3 // string plus int return string
"six33" // string plus int return string
In the second one :
String s2 = 3 + 3 + "six:";
6 + "six" // int plus int return int
"6six" // int plus string return string
For more details read documentation of Operators and 15.7. Evaluation Order
All binary operators except for the assignment operators are evaluated
from left to right; assignment operators are evaluated right to left.
In S1, the compiler reads (six) characters, then reads and reads. The numerical value of number 3 cannot be summed with text (six), as a character and added after x, then reads 3 and added after the first 3.
In s2 he reads 3 and then 3 can execute the process collected by the compiler and prints 6 directly and then reads (six) can not be collected will be printed after the number 6
Order is important. In second case firstly it does arithmetic operation and string concatenation so it results in 6six

Using only 1 System.out.print() instead of 3. More details below [duplicate]

I am trying to concatenate strings in Java. Why isn't this working?
public class StackOverflowTest {
public static void main(String args[]) {
int theNumber = 42;
System.out.println("Your number is " . theNumber . "!");
}
}
You can concatenate Strings using the + operator:
System.out.println("Your number is " + theNumber + "!");
theNumber is implicitly converted to the String "42".
The concatenation operator in java is +, not .
Read this (including all subsections) before you start. Try to stop thinking the php way ;)
To broaden your view on using strings in Java - the + operator for strings is actually transformed (by the compiler) into something similar to:
new StringBuilder().append("firstString").append("secondString").toString()
There are two basic answers to this question:
[simple] Use the + operator (string concatenation). "your number is" + theNumber + "!" (as noted elsewhere)
[less simple]: Use StringBuilder (or StringBuffer).
StringBuilder value;
value.append("your number is");
value.append(theNumber);
value.append("!");
value.toString();
I recommend against stacking operations like this:
new StringBuilder().append("I").append("like to write").append("confusing code");
Edit: starting in java 5 the string concatenation operator is translated into StringBuilder calls by the compiler. Because of this, both methods above are equal.
Note: Spaceisavaluablecommodity,asthissentancedemonstrates.
Caveat: Example 1 below generates multiple StringBuilder instances and is less efficient than example 2 below
Example 1
String Blam = one + two;
Blam += three + four;
Blam += five + six;
Example 2
String Blam = one + two + three + four + five + six;
Out of the box you have 3 ways to inject the value of a variable into a String as you try to achieve:
1. The simplest way
You can simply use the operator + between a String and any object or primitive type, it will automatically concatenate the String and
In case of an object, the value of String.valueOf(obj) corresponding to the String "null" if obj is null otherwise the value of obj.toString().
In case of a primitive type, the equivalent of String.valueOf(<primitive-type>).
Example with a non null object:
Integer theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
Example with a null object:
Integer theNumber = null;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is null!
Example with a primitive type:
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
2. The explicit way and potentially the most efficient one
You can use StringBuilder (or StringBuffer the thread-safe outdated counterpart) to build your String using the append methods.
Example:
int theNumber = 42;
StringBuilder buffer = new StringBuilder()
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer.toString()); // or simply System.out.println(buffer)
Output:
Your number is 42!
Behind the scene, this is actually how recent java compilers convert all the String concatenations done with the operator +, the only difference with the previous way is that you have the full control.
Indeed, the compilers will use the default constructor so the default capacity (16) as they have no idea what would be the final length of the String to build, which means that if the final length is greater than 16, the capacity will be necessarily extended which has price in term of performances.
So if you know in advance that the size of your final String will be greater than 16, it will be much more efficient to use this approach to provide a better initial capacity. For instance, in our example we create a String whose length is greater than 16, so for better performances it should be rewritten as next:
Example optimized :
int theNumber = 42;
StringBuilder buffer = new StringBuilder(18)
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer)
Output:
Your number is 42!
3. The most readable way
You can use the methods String.format(locale, format, args) or String.format(format, args) that both rely on a Formatter to build your String. This allows you to specify the format of your final String by using place holders that will be replaced by the value of the arguments.
Example:
int theNumber = 42;
System.out.println(String.format("Your number is %d!", theNumber));
// Or if we need to print only we can use printf
System.out.printf("Your number is still %d with printf!%n", theNumber);
Output:
Your number is 42!
Your number is still 42 with printf!
The most interesting aspect with this approach is the fact that we have a clear idea of what will be the final String because it is much more easy to read so it is much more easy to maintain.
The java 8 way:
StringJoiner sj1 = new StringJoiner(", ");
String joined = sj1.add("one").add("two").toString();
// one, two
System.out.println(joined);
StringJoiner sj2 = new StringJoiner(", ","{", "}");
String joined2 = sj2.add("Jake").add("John").add("Carl").toString();
// {Jake, John, Carl}
System.out.println(joined2);
You must be a PHP programmer.
Use a + sign.
System.out.println("Your number is " + theNumber + "!");
"+" instead of "."
Use + for string concatenation.
"Your number is " + theNumber + "!"
This should work
public class StackOverflowTest
{
public static void main(String args[])
{
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
}
}
For exact concatenation operation of two string please use:
file_names = file_names.concat(file_names1);
In your case use + instead of .
For better performance use str1.concat(str2) where str1 and str2 are string variables.
String.join( delimiter , stringA , stringB , … )
As of Java 8 and later, we can use String.join.
Caveat: You must pass all String or CharSequence objects. So your int variable 42 does not work directly. One alternative is using an object rather than primitive, and then calling toString.
Integer theNumber = 42;
String output =
String // `String` class in Java 8 and later gained the new `join` method.
.join( // Static method on the `String` class.
"" , // Delimiter.
"Your number is " , theNumber.toString() , "!" ) ; // A series of `String` or `CharSequence` objects that you want to join.
) // Returns a `String` object of all the objects joined together separated by the delimiter.
;
Dump to console.
System.out.println( output ) ;
See this code run live at IdeOne.com.
In java concatenate symbol is "+".
If you are trying to concatenate two or three strings while using jdbc then use this:
String u = t1.getString();
String v = t2.getString();
String w = t3.getString();
String X = u + "" + v + "" + w;
st.setString(1, X);
Here "" is used for space only.
In Java, the concatenation symbol is "+", not ".".
"+" not "."
But be careful with String concatenation. Here's a link introducing some thoughts from IBM DeveloperWorks.
You can concatenate Strings using the + operator:
String a="hello ";
String b="world.";
System.out.println(a+b);
Output:
hello world.
That's it
So from the able answer's you might have got the answer for why your snippet is not working. Now I'll add my suggestions on how to do it effectively. This article is a good place where the author speaks about different way to concatenate the string and also given the time comparison results between various results.
Different ways by which Strings could be concatenated in Java
By using + operator (20 + "")
By using concat method in String class
Using StringBuffer
By using StringBuilder
Method 1:
This is a non-recommended way of doing. Why? When you use it with integers and characters you should be explicitly very conscious of transforming the integer to toString() before appending the string or else it would treat the characters to ASCI int's and would perform addition on the top.
String temp = "" + 200 + 'B';
//This is translated internally into,
new StringBuilder().append( "" ).append( 200 ).append('B').toString();
Method 2:
This is the inner concat method's implementation
public String concat(String str) {
int olen = str.length();
if (olen == 0) {
return this;
}
if (coder() == str.coder()) {
byte[] val = this.value;
byte[] oval = str.value;
int len = val.length + oval.length;
byte[] buf = Arrays.copyOf(val, len);
System.arraycopy(oval, 0, buf, val.length, oval.length);
return new String(buf, coder);
}
int len = length();
byte[] buf = StringUTF16.newBytesFor(len + olen);
getBytes(buf, 0, UTF16);
str.getBytes(buf, len, UTF16);
return new String(buf, UTF16);
}
This creates a new buffer each time and copies the old content to the newly allocated buffer. So, this is would be too slow when you do it on more Strings.
Method 3:
This is thread safe and comparatively fast compared to (1) and (2). This uses StringBuilder internally and when it allocates new memory for the buffer (say it's current size is 10) it would increment it's 2*size + 2 (which is 22). So when the array becomes bigger and bigger this would really perform better as it need not allocate buffer size each and every time for every append call.
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = value.length >> coder;
int newCapacity = (oldCapacity << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
return (newCapacity <= 0 || SAFE_BOUND - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
private int hugeCapacity(int minCapacity) {
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
int UNSAFE_BOUND = Integer.MAX_VALUE >> coder;
if (UNSAFE_BOUND - minCapacity < 0) { // overflow
throw new OutOfMemoryError();
}
return (minCapacity > SAFE_BOUND)
? minCapacity : SAFE_BOUND;
}
Method 4
StringBuilder would be the fastest one for String concatenation since it's not thread safe. Unless you are very sure that your class which uses this is single ton I would highly recommend not to use this one.
In short, use StringBuffer until you are not sure that your code could be used by multiple threads. If you are damn sure, that your class is singleton then go ahead with StringBuilder for concatenation.
First method: You could use "+" sign for concatenating strings, but this always happens in print.
Another way: The String class includes a method for concatenating two strings: string1.concat(string2);
import com.google.common.base.Joiner;
String delimiter = "";
Joiner.on(delimiter).join(Lists.newArrayList("Your number is ", 47, "!"));
This may be overkill to answer the op's question, but it is good to know about for more complex join operations. This stackoverflow question ranks highly in general google searches in this area, so good to know.
you can use stringbuffer, stringbuilder, and as everyone before me mentioned, "+". I'm not sure how fast "+" is (I think it is the fastest for shorter strings), but for longer I think builder and buffer are about equal (builder is slightly faster because it's not synchronized).
here is an example to read and concatenate 2 string without using 3rd variable:
public class Demo {
public static void main(String args[]) throws Exception {
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
System.out.println("enter your first string");
String str1 = br.readLine();
System.out.println("enter your second string");
String str2 = br.readLine();
System.out.println("concatenated string is:" + str1 + str2);
}
}
There are multiple ways to do so, but Oracle and IBM say that using +, is a bad practice, because essentially every time you concatenate String, you end up creating additional objects in memory. It will utilize extra space in JVM, and your program may be out of space, or slow down.
Using StringBuilder or StringBuffer is best way to go with it. Please look at Nicolas Fillato's comment above for example related to StringBuffer.
String first = "I eat"; String second = "all the rats.";
System.out.println(first+second);
Using "+" symbol u can concatenate strings.
String a="I";
String b="Love.";
String c="Java.";
System.out.println(a+b+c);

String outputs confusing with +

public class Test2 {
public static void main (String[] args){
System.out.println("3 + 6");
System.out.println(3 + 6);
System.out.println(3 + 6 + "buffer");
System.out.println("buffer" + 3 + 6);
System.out.println("buffer " + (3 + 6));
}
}
the output for
System.out.println(3 + 6 + "buffer");
is
9 buffer
and
the output for
System.out.println("buffer" + 3 + 6);
is
buffer 36
why the difference? and why
System.out.println(3 + 6);
output is
9
?
The arithmetic operator resolves from left to right. And when you do + With string it's append as a string.
System.out.println(3 + 6 + "buffer");
That becomes
System.out.println( 9 + "buffer");
And when you do
System.out.println("buffer" + 3 + 6);
that evaluates as
// "buffer3" + 6
// "buffer36"
and
System.out.println(3 + 6)
There is no string concatenation. So direct integer addition happend.
In case of
System.out.println("buffer " + (3 + 6));
You added parenthesis to 3+6. Due to the higher precedence that expression in parenthesis evaluates first. Hence that becomes
System.out.println("buffer " + 9);
The expressions passed to println are evaluated before being passed.
They are evaluated from left to right.
If the first (left) operand in the expression is a String, + performs String concatenation, so "buffer" + 3 + 6 becomes "buffer3" + 6 which becomes "buffer36".
If the first and second operands are numbers, + performs addition, so 3 + 6 + "buffer" becomes 9 + "buffer" which becomes "9buffer".
If some of the operands are surrounded by brackets, the operator between them is applied first, so "buffer " + (3 + 6) is equivalent to "buffer " + 9.
Expressions are evaluating left to right direction.
So System.out.println(3 + 6 + "buffer"); in this line firstly evaluating sum of integer numbers and System.out.println("buffer" + 3 + 6); here is the first type is string and evaluating type conversion according to string type to the right.
The expression you pass is first evaluated starting from left to right. Here in case of 3+6+"buffer" the first two parameters are integer so the + operator adds them and sum is 9 and when it gets the third parameter "buffer" which is a string, it converts the result to string and prints it. Hence you get the string "9buffer" as result.
However in the second case "buffer"+3+6 first parameter is string and second is integer so second param is converted to string first and then + operator concatenates them. Similar is the case when it reaches the third operator it does "buffer"+6 and again concatenates it and hence result becomes "buffer36".
if you are using + sign for String, the java compiler take it as concatenate and automatically call toString to other object.
So when you are trying to print 3+6+"stuff" it means int+int+contate to String so first it add two number and after that converts it to string and concate it with "stuff".
And if you call "stuff"+3+6 it will print stuff36
In the first one (3+6+"buffer") when the program is run java reads your program from left so it takes 3 and 6 as integer and their sum is 9 then it reads a string so it joins it with the string and result is "9buffer".
In the second one ("buffer"+3+6) it reads string first so it joins the other to with it
and result is buffer36.
In the third one (3+6) it takes them integers because no string is present before them
so it gives 9.

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