Probably Java developers can not answer the question

Source: Internet
Author: User
Tags set set stack trace google guava

Links: http://www.importnew.com/16566.html

A few months ago, we posted a new project on a small website called the Java Death Race. After the quiz was released, more than 20,000 developers took the quiz. The site is based on 20 multi-choice Java topics. We've got a lot of developer quiz stats, and today we're happy to share some of the data and answers with you.

We got 61,872 answers from 20 topics, with about 3,094 answers for each of these topics. Each Java "death" test randomly extracts 5 topics from 20 topics, and then each topic has 90 seconds to answer. There are four possible options for each of these issues. We are often complained that these topics are too difficult. So our quiz is known as the Java "death" race, and there's no reason for that! From the statistical data of the test results, we can know which problems are the hardest and which are the simplest. In this blog post, I would like to share with you 5 of the most difficult questions we have chosen from our quizzes and then work together to solve them.

On average, about 41% of the answers given by the developers are correct, and the results are not bad. The index of each question and its response statistic results can be obtained from here. The statistics used in this blog were obtained on July 26. From here you can try our Java "death" contest quiz.

1. The most difficult problem in the Java "Death Race"

Let's start with the hardest bone to chew. This issue is provided by Alexandru-constantin Bledea from the Romanian capital, Bucharest. The problem is really a brain teaser, and only about 20% of the participants get it right, which means that a blind election can improve your chances of answering the correct question. This question is about Java generics.

Main topic:

Where is this code wrong?

A. Compile error, because no SqlException is thrown

B. Throw classcastexception, because SqlException is not an instance of RuntimeException

C. No error, the program prints out the thrown SqlException stack trace information

D. Compile error, because we cannot convert the SqlException type to RuntimeException

OK, what information can we get from the topic? Generics in the topic involve type erasure, as well as some exceptions. Here you need to recall some knowledge:

Both RuntimeException and SqlException inherit from exception, but in this code runtimeexception is an unchecked exception, and SqlException is the exception being inspected.

The 2.Java generics are not materialized. This means that at compile time, the type information of the generic is "lost" and the generic parameter is replaced by its qualified type, or if the qualified type does not exist, the generic parameter is replaced with an object. This is what we call the "erase" type.

We naively hope that line seventh will produce a compile error because we can't convert SqlException to RuntimeException, but that doesn't happen. What happens is to replace T with exception, so we have:

throw (Exception) t; T is also an Exception

The Pleasethrow method expects a exception, and T is replaced with exception, so the type conversion is erased, as if the code was not written. This is supported by the following byte code:

Private throws java/lang/81 this ltemp; L0 L1 0//  signature ltemp<tt;>; // declaration:temp<t> Localvariable T ljava/lang/exception; L0 L1 1= 1= 2

Let's take a look again, if the code does not involve generics, then what is the bytecode generated by the compilation, and we see the following code before Athrow:

Checkcast java/lang/runtimeexception

Now, we can be sure that there is no type conversion involved in the code, so we can exclude the following two options:

"Compile error because we cannot convert the SqlException type to RuntimeException"

"Throw classcastexception, because SqlException is not an instance of RuntimeException"

So after all we throw out the SqlException, and then you want it to be caught by a catch block, and then print its stack trace information. However, it backfired.

This code is deceptive, and it makes the compiler as confusing as we are. This code makes the compiler think that the catch code block is unreachable. For unsuspecting bystanders, there is no sqlexception in the code. So the correct answer is: The compilation fails because the compiler thinks that SqlException is not thrown from the try block-but actually it can be thrown!

Thank Alexandru again for sharing this issue with us! We can look at the error in the code in another cool way and how SqlException actually throws it: Modify the catch code block and modify it to receive a runtimeexception. So you can see the stack information of the SqlException. (In fact, SqlException is not captured by the catch snippet, but is captured by the virtual machine and prints out the exception stack information.) )

2, the crux of the problem is whether to use the ToString ()

The problem is only 24% of the correct rate, it is the difficulty of the 20 problems in the runner-up.

The main question: what is the printing result of this program?

A.M1 & New Name

B. All of the above are wrong

C.m1&m1

D.new Name & new name

The problem is actually much simpler, as long as we see line 12th, it directly prints M1 and M2, not m1.name and M2.name. The tricky part of this code is that when we print an object, Java uses the ToString method. The "name" attribute is our own, and if you forget that and the other places are right, you may mistakenly choose the answer to M1&new name.

This line of code assigns the Name property of two objects to "M1".

M1.name = M2.name = "M1";

The CallMe method then sets the Name property of the M2 object to "new name" and the code ends.

However, this code snippet will actually print out the following information, including the class name and their hash code:

[Email protected] & [email protected]

So the correct answer is "None of the above"

3, Google Guava class library in the sets

Main topic:

Where is the wrong part of the problem?

A. Cannot compile

B. No problem

C. may cause memory overflow

D. May cause an infinite loop

This problem does not in fact require the expertise of the Guava sets class library, but it confuses most developers. Only 25% of the participants gave the correct answer, and the right rate for blind selection was the same.

So what can we see from this code? We have a method that returns a collection that contains a person's circle of friends. There is a loop in the method that checks whether the Bestfriend property of a person object is null. If not NULL, the bestfriend is added to the results collection. If a person object does have a bestfriend, then repeat the above procedure for the person's bestfriend, so we can always add the person object to the Bestfriend collection until there is a person, It has no bestfriend, or its bestfriend is already in our result set. The last part is a bit subtle, we can't add duplicate elements to this set set, that is, the person object, so this method does not cause an infinite loop.

The real problem is that this code is likely to cause an out-of-memory exception (out of exception). This loop actually has no boundaries, so we can keep adding the person object to the set until the memory runs out.

By the way, if you want to learn more about Google Guava, you can read our blog: The lesser known yet useful features about it

4. Initialize with two curly braces

The question is: where is this code wrong?

A. No errors

B. May get a null value

C. Code cannot be compiled

D. Print out incorrect results

This problem is one of the least code issues, but it's enough to confuse most developers. Only 26% of the respondents answered the question correctly.

Few developers know the simple syntax for initializing a set of constants, although this syntax brings some side effects. But in fact, this little-known grammar is not a good thing. After the exclamation, you see, we add an element to the list and print the list. Normally, you expect to see the result of the print being [John], but initializing with two curly braces is another set of initialization procedures. Here, we use an anonymous class to initialize a list, and when we want to print names, we actually print null, because the initializer is not yet complete, and the list is empty at this point.

For the initialization of a container using two curly braces, refer to here.

5. Bizarre events for runtime map containers

This is another community contribution, and the contributors are from Israel's Barak Yaish. Only 27% of the respondents can answer this question.

What is the output of this piece of code?

A. Cannot compile

B. Type conversion exception

C.[] True

d.["Bar", "ber"]

Well, let's look at the code. The Compute method finds a value in the map by key. If this value is null, then insert (key, value) and return value. Because the list is empty at the beginning, the "foo" value does not exist and V is null. Then we insert a "foo" into the map and "foo" points to New arraylist<object> (), at which point the ArrayList object is empty, so it prints [].

Next line, the "foo" key value exists in the map container, so we calculate the expression on the right. The ArrayList object is successfully converted to the list type, and then the "BER" string is inserted into the list. The Add method returns True, so true is the second line of printed content.

So the correct answer is "[]true]". Thank Barak again for sharing this problem with us.

Probably Java developers can not answer the question

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.