Reputation:
When use the interactions panel to run my code I get a null value before the result. for example when I enter: 1st word - google 2nd word - chrome
the result should be - gcohorgolme but instead it is - nullgcohorgolme
Any ideas why? Here is my code:
public class Collate{
String result;
String x;
String y;
public String collate(String x, String y){
for(int i = 0; i < x.length(); i++)
{
result += x.charAt(i);
result += y.charAt(i);
}
return (result);
}
}
Thanks a bunch!
Upvotes: 0
Views: 115
Reputation: 36
You can always use a StringBuffer.
public static String collate(String x, String y){
StringBuffer result = new StringBuffer();
for(int i = 0; i < x.length(); i++)
{
result.append(x.charAt(i)).append(y.charAt(i));
}
return (result.toString());
}
Upvotes: 1
Reputation: 10632
4.3.1 Objects (from Java Language Specifications):
The string concatenation operator
+
, which, when given a String operand and a reference, will convert the reference to a String by invoking the toString method of the referenced object (using "null" if either the reference or the result of toString is a null reference), and then will produce a newly created String that is the concatenation of the two strings
And here the result
String was initialized with a null reference. So to get the desired result, you need to initialize the result
as:
String result="";
Upvotes: 0
Reputation: 709
You haven't initialized your result
value.
Remember that you should always initialize your variables. The null
happens because your result is getting initialized an then converted to a String, which is null
.
Upvotes: 3
Reputation: 1103
result += x.charAt(i)
is equal to
result = result + x.charAt(i)
but result
is null at first loop.
Upvotes: 1
Reputation: 525
Initialize your result
string, as String result = "";
This step should always be taken as a precaution, otherwise you may end up with a null
output as you have here.
Upvotes: 2
Reputation: 15158
Make sure you initialize result
:
public String collate(String x, String y){
result = ""; // <-- here
for(int i = 0; i < x.length(); i++)
{
result += x.charAt(i);
result += y.charAt(i);
}
return (result);
}
Upvotes: 7