Why the following code use String and StringBuffer in the same line?

105 views Asked by At
set.add(new String(s) + (ch == 0 ? "" : ch) + new StringBuffer(new String(s)).reverse());

I encountered this code from written by someone. It is java code. s is a char[]. set is a String set. So why does he use String and then StringBuffer?

2

There are 2 answers

0
Amethystx87 On

String has a constructor which takes an array of chars, hence why they create a new String first.

Then to reverse the String, they create a StringBuffer to use a built in reverse function in order to not implement their own. StringBuffer's constructor takes a String, hence why a String is made first and then a StringBuffer

1
hc_dev On

Let's split the 3 parts on 3 lines to compare:

set.add(
  new String(s) 
+ (ch == 0 ? "" : ch) 
+ new StringBuffer(new String(s)).reverse()
);

Rewritten

It is equivalent with

String trimZero = ch == 0 ? "" : String.valueOf(ch);
set.add(String.valueOf(s) + trimZero + StringUtils.reverse(s));

Well, using Apache's StringUtils.reverse().

If s is a String it can simply added as is, for example, in an alternative way (to emphasize the different structures):

if (ch == 0) {
   set.add(s + StringUtils.reverse(s));
} else {
   set.add(s + String.valueOf(ch) + StringUtils.reverse(s));
}

Output wise

For example:

  • alphabet gets added as alphabet8tebahpla (for coincidence ch is a non-zero integer).
  • an gets added as anna (given that ch == 0)

Abbreviations and naming-conventions

When guessing the types I would say:

  • ch probably is a primitive char, array of that, or CharSequece
  • s most-likely is a String (rather than the rarely used short integer)

Usually abbreviations in symbols/names are ambiguous and can be considered a code-smell.

However there seems to be a historical and accepted convention or habit, especially for temporary / looping variables like:

  • int i
  • String s
  • char ch

The Java Pocket Guide, 4th Edition by Robert Liguori, Patricia Liguori, Chapter 1. Naming Conventions assorted them in a table:

Temporary variable names may be single letters such as i, j, k, m, and n for integers and c, d, and e for characters. Temporary and looping variables may be one-character names as shown in Table 1-1.

Even core Java methods have such (ambiguous) abbreviated parameter-names

  • if the method-context is obvious enough
  • that the contents and purpose of the parameter is self-explaining

E.g. String.contains(CharSequence s)