Backspace character

In December I asked a question: What’s wrong with this code? I agree that the question was rather broad without context. I just asked it in the same way a friend asked me.

Many people noticed '\b' character in the code… Is it good or bad? Well, it depends.

What is '\b' character?

Quote from an answer by T.J. Crowder at Stack Overflow: On most terminals or consoles, '\b' is a nondestructive backspace. It moves the cursor backward, but doesn’t erase what’s there.

Another answer provides a detailed explanation of how the backspace character works.

If you’re interested, see The “backspace” escape character ‘\b’ in C, unexpected behavior? question.

What can be wrong?

As long as the output is written to terminal or console, it does what it’s supposed to do, most of the time at least. But what about capturing the output to a file? Then you’ll see a weird character in the file.

In my opinion, backspace character in that code serves no purpose. Much better way would be just to remove the last space from the buffer:

sb.deleteCharAt(sb.length() - 1);

It is the safest approach and it has no (possible) undesirable effects.

Another issue is if objs is empty, the opening '[' would be removed from the string. I think the assumption here is that objs is never empty which can be enforced by the calling code.

Advertisements

What’s wrong with this code?

There’s a code snippet. What’s wrong with it?

StringBuffer sb = new StringBuffer(" - The required object is unknown: ");
sb.append("Please choose an object from [");
for (String tmp : objs) {
    sb.append(tmp);
    sb.append(' ');
}
sb.append('\b');
sb.append(']');

Is it possible to change a String in Java

Everyone knows String object in Java is immutable. It means it is impossible to change its value after the object was created.

It was my answer to the question How can the value of string be changed? I was asked this question on a job interview.

But is it really impossible? Yes, it is… unless you use reflection. The following program demonstrates how you can change the value stored in a String object:

Read the rest of this entry »