官术网_书友最值得收藏!

Conditional execution

The heart of the sort is the condition and the value swapping inside the loop.

                if (names[j].compareTo(names[j + 1]) > 0) { 
final String tmp = names[j + 1];
names[j + 1] = names[j];
names[j] = tmp;
}

There is only one conditional command in Java, the if command. It has the following format:

if( condition ) block else block

The meaning of the code structure is quite straightforward. If the condition is true, then the first block is executed, otherwise, the second block is executed. The else keyword, along with the second block, is optional. If there is nothing to be executed in case that the condition is false, then there is no need for the else branch, just like in the example. If the array element indexed with j is later in the sort order than the element j+1, then we swap them, but if they are already in order, there is nothing to do with them.

To swap the two array elements, we will use a temporary variable named tmp. The type of this variable is String, and this variable is declared to be final. The final keyword has different meanings depending on where it is used in Java. This may be confusing for beginners unless you are warned about it, just like now. A final class or method is a totally different thing than a final field, which is again different than a final local variable.

主站蜘蛛池模板: 怀柔区| 胶南市| 阿瓦提县| 九台市| 延庆县| 宕昌县| 原阳县| 同江市| 五峰| 乡城县| 瓦房店市| 綦江县| 突泉县| 陆良县| 昌邑市| 长治市| 塔城市| 抚松县| 临桂县| 方正县| 东莞市| 康保县| 潍坊市| 息烽县| 玛纳斯县| 安吉县| 大丰市| 灵武市| 满城县| 满洲里市| 巴里| 万安县| 合江县| 湖南省| 唐河县| 瓦房店市| 昌江| 蒙山县| 夏津县| 潢川县| 太湖县|