Ten Java language "trap" you come across a few?

 

As an object-oriented programming language, Java, with its easy to use, powerful features favored by the majority of programming enthusiasts, along with the waves of the open source community, Java language is sweeping the globe, unstoppable, in all over the world practitioners Java technology, it also ranked first in the annual list of programming languages, and powerful enough to show that the king of Java wind.

However, even such a powerful programming language, there are a lot of "pit father" function, a little attention, we will fall into the pit, ranging from ridicule and contempt were colleagues, while tragic consequences had to run away .

Of course, the word pit father plus the double quotes, because most of the time, because we are not enough skilled, violate our common sense that led to unpleasant consequences.

Today we have to sort out what Java is the most "pit father", in violation of the most common sense of function points, by way of charts published to readers. Explain code in this article based on JDK8 to compile implementation.

1 switch must be added before the end of break

For multiple branch selection, less readable series of if-else-if statement makes the code, it is recommended to use a switch statement instead, but branch judging switch case, you must add the break statement will suspend the other case execution, such as:

int count = 1;
switch(count){
    case 1:
        System.out.println("one");
    case 2:
        System.out.println("two");
    case 3:
        System.out.println("three");
}

The above code output:

one
two
three

However, this is not what we want, or that violates our common sense. Met certain conditions, of course, need only be executed in such a condition to the logic, should ignore the other case, skip, as the above code, only one output line. Of course, with break at the end of each case we can achieve our desired effect.

This function point slightly "pit father", also beginners often make mistakes, so it is also a glorious list, ranked No. 10.

 

2 logical operators "short circuit" phenomena

When using logical operators, we encounter the phenomenon of "short circuit": once to determine the overall value of the expression, it does not calculate the remaining part, of course, this point is actually very useful function, but for beginners She said, may feel more surprised, improper use will have a "pit father" consequences. For example the following code:

int num = 1;
System.out.println(false && ((num++)==1));
System.out.println(num);

1 and false is output as the first half of the && is a logical false, true or false regardless of the latter part, whole expression returns false, so it is not counted in the back part, into true if false then the second half will be implemented, num will become 2 a.

It is ranked No. 9 in the "pit father" list.

The zero-based array 3

Java programmers are aware of the array index is zero-based, for example, we have to traverse an array, the following options are available:

int[] arr = new int[]{1,3,5,7,9};
for(int i=0;i<arr.length;i++){
System.out.println("the element is:"+arr[i]);
}

Which with our daily life experience is contrary to normal circumstances are from one element to start counting, especially for beginners, a bit difficult to accept, would be very surprised. Even for experienced programmers, some places need extra attention, such as:

String str = "hello world";
System.out.println(str.charAt(1));

We know, charAt role is to get to a location in a string of characters, however, the output of the code above is not the first character h, but e, because arrays are zero-based, this is more "pit father" what. Of course, the reason the designers do is take into account the memory offset factor.

Every time when writing this code, we need to do this mapping and transformation 1-0 of (skilled is the subconscious conversion), and indeed a little "pit father", so it is not immune, ranked No. 8.

 

4 ArrayList error when traversing deleted

Talk is cheap, first on the code:

public static void main(String[] args) {
   List<String> list = new ArrayList<String>();
   list.add("abc");
   list.add("bc");
   list.add("bc");
   list.add("abcd");
   list.add("abcdef");
   //报错
   int length = list.size();
   for(int i = 0;i < length;i++){
       if(list.get(i).equals("bc")){
           list.remove(i);
       }
   }
}

Want to remove an element from the ArrayList, so we wrote the above code, but it throws an IndexOutOfBoundsException because ArrayList will be recalculated after you remove the element number, put in a for loop that is list.size can:

for(int i=0;i<list.size();i++){
   if(list.get(i).equals("bc")){
       list.remove(i);
   }
}

Of course, this approach is also problematic, it is recommended to use an iterator way to remove elements.

For less skilled programmers, it will sometimes fall into this trap. This is a ranking of 7.

 

5 characters into digital pit

Sometimes, we want the characters directly into the integer type conversion by, for example, like this:

char symbol = '8';
System.out.println((int) symbol);

8 is the result we want, however, the output of the above code was 56, a little "pit father", the specific cause of reference of knowledge ASCII.

 

6 while loop "camouflage"

For the while loop, if you do not add braces, even though the latter statement is put together, it will only execute the first statement, such as:

int i = 0;
while(i++<3)
       System.out.print("A");
       System.out.print("B");

The above code output:

AAAB

Instead of 3 A, 3 B, the more "pit father," is that if the two statements on one line, would be more confusing:

int i = 0;
while(i++<3)
       System.out.print("A");System.out.print("B");

This is likewise the above wording output AAAB. So, like this case, even if only one statement, also suggested adding braces, perfect to avoid the pit.

 

7 Integer class has cache

This feature is one of the high-frequency hot spot is the interview, a little attention, there are likely to be brought into the ditch, we take a look at the following code:

public static void main(String[] args){
   Integer a = 100;
   Integer b = 100;
   Integer c = 200;
   Integer d = 200;
   System.out.println(a==b);
   System.out.println(c==d);
}

The above code actually output:

true
false

This is really so unexpected, the same code, but with different values ​​(but not much difference between the way), it creates a different output, which is too outrageous. Original, there is a static inner Integer class IntegerCache, when the class is loaded, it will [-128, 127] value between cached, Integer a = 100 and this assignment mode, will first call the class Integer valueOf static method, which attempts to value from the cache, if you do not have to re-new an object within the range of:

public static Integer valueOf(int i) {
   if (i >= IntegerCache.low && i <= IntegerCache.high)
       return IntegerCache.cache[i + (-IntegerCache.low)];
   return new Integer(i);
}

This feature appeared in the "pit father" list of the first four.

 

8 empty method body resulting in an infinite loop

If the loop method body is empty, resulting in an endless loop, for instance, the following code numbers 1,2,3 print out:

int i = 1;
while(i<4){
   System.out.println(i++);
}

If you're in keyboarding, accidentally add a semicolon at the end while (if the method does not increase the body brackets, more prone to this case):

int i = 1;
while(i<4);{
   System.out.println(i++);
}

You guessed how the above code can compile and run properly, however, it is caught in an infinite loop ...... not very "pit father"? The for loop there is a similar situation.

It ranked No. 3 ranking.

= + 9 magic

We know, for a = a + b is similar to this assignment, there is a shorthand way: a + = b, however, if you accidentally wrote a = + b, what will the results be? We take a look at the following code:

100 = I int;
I + = 2; // Note, plus behind
System.out.println (i);

The above code will neither output 102, also does not complain, but output 2, it is indeed surprising, totally not what we expected result, amazing, very "pit father."

Therefore, it is ranked second, ranking the second place position.

10 Java annotations can recognize Unicode

First look at the code:

public static void main(String[] args){
    // \u000d System.out.println("Hello World!");
}

At first glance, the code is commented, of course, will not output anything, however, it is the output of each programmer will feel at home in the Hello World, this is because, unicode decoding occurs before the code is compiled, the compiler will \ u style text escape code, the comment is even so, then \ u000A is converted into \ n newline character, so the code is executed normally println.

This feature really "pit father" extremely violation of common sense, it must be on the list must be crowned champion of the position.

These are summarized in the Java language editor Ten "pit father" function point, whether you agree with this ranking? What features do you think more should be selected for this list?

Released three original articles · won praise 464 · views 110 000 +

Guess you like

Origin blog.csdn.net/weixin_42784331/article/details/104303549