Specification: Pad a Java String with spaces so that it is 16 characters long.
The wrong way to do it:
public String pad(String input)
{
if (input == null)
{
for (int i = 0; i < 16; i++)
{
input += " ";
}
}
else
{
for (int i = input.length(); i < 16; i++)
{
code += " ";
}
}
return input;
}
{
if (input == null)
{
for (int i = 0; i < 16; i++)
{
input += " ";
}
}
else
{
for (int i = input.length(); i < 16; i++)
{
code += " ";
}
}
return input;
}
The bug in the above code is that the += operator on a String will convert a null reference String to the 4 character String "null" so when input is null, the return will be a 20 character String starting with the word null followed by 16 spaces:
"null "
A bug free implementation is:
public String pad(String input)
{
StringBuilder builder = new StringBuilder();
if (input != null)
{
builder.append(input);
}
for (int i = builder.length(); i < 16; i++)
{
builder.append(' ');
}
return builder.toString();
}
{
StringBuilder builder = new StringBuilder();
if (input != null)
{
builder.append(input);
}
for (int i = builder.length(); i < 16; i++)
{
builder.append(' ');
}
return builder.toString();
}