Core Java

Stackoverflow: 7 of the Best Java Answers That You Haven’t Seen

What are some of the most interesting answers you can find on Stackoverflow?

Stackoverflow is a goldmine for developers. It helps us find the most useful answers to specific issues we encounter, and we always find ourselves learning new things from it.

For the following post, we’ve looked into the most popular Java questions and answers and decided to highlight some precious gems that we found. There’s always something new to learn, even if you’re an experienced developer.

Java Answers for All

Java is the second most popular tag on Stackoverflow, with more than a million questions linked to it. During the last week over 4,600 questions were uploaded to the site, and there’s no doubt it’s the biggest and most active online community of developers.

This information goes hand in hand with Stackoverflow’s Developer Survey Results for 2016, in which 56,033 coders were asked what’s their language of choice. Java came in at 3rd place:

most-popular-technology
Most popular technology 2016. Source: Stackoverflow

We already know that Java reigns the job market, and it’s safe to assume that you too have visited Stackoverflow once or twice to find an answer for a question. However, even if you’re just casually browsing Stackoverflow without a specific question in mind, lots of interesting things can pop up. Let’s see some of those gems.

1. Branch Prediction

One of the most upvoted Java questions on Stackoverflow is “Why is it faster to process a sorted array than an unsorted array?”. In order to answer this, you’ll need to use branch prediction. It’s an architecture that aims to improve the application flow, through guessing the way a specific branch would go before the actual path has been chosen. Educated guess if you’d prefer, only it’s not actually a guess.

for (int i = 0; i < 100000; ++i)
        {
            // Primary loop
            for (int c = 0; c < arraySize; ++c)
            {
                if (data >= 128)
                    sum += data;
            }
        }

The branch here is the if statement. In this case, if the array is sorted branch prediction will work. If it’s not sorted, it won’t work.

Mysticial has tried to explain this in a simpler way, using a railroad and a train. Imagine you operate a junction and need to decided which way the train will go, will you choose left or right? Sure, you can stop the train and ask the driver which way is the right one, but that makes the whole process slow, clumsy and irritating. You need to make a guess. How can you be sure your guess is the right one? Take a look at past drives of the current train and understand which way it goes each time.

That’s branch prediction: identify patterns and follow them.

Unfortunately, in this case the user who asked the main question was a victim of branch prediction fail. That happened because the branch had no recognizable pattern, so trying to predict its actions is pretty random.

2. Security in Java

Another popular question Java users often upvote is “Why is char[] preferred over String for passwords in Java?”. The question itself is a little more specific, asking why a Swing password field has a getPassword() (returns char[]) method instead of getText() (returns String).

No surprise here – it’s a security issue. Strings are immutable, meaning you can’t modify them after they’re created. This also means that you can’t get rid of the data before GC comes knocking. In the off chance someone will have access to your memory, the String with the password might be available for him to take.

That’s why you should use a char array. You’ll be able to explicitly wipe the data when you’re done with it, or you can overwrite it with anything else you’d like. The sensitive data won’t be present anywhere in the system, even before GC runs.

3. Exceptions

Even though many devs prefer to ignore checked exceptions, there are a lot of questions about exceptions in Java. It’s a main issue you should be addressing in your code, and ignoring the problem won’t make it go away.

One of the most upvoted questions is “What is a NullPointerException, and how do I fix it?”. We weren’t shocked to see how popular this exception is, since it also ranked as the number 1 exception type in production Java applications.

At Takipi, we actually have an option to set up alerts whenever a new NullPointerException (or any other exception) is introduced on the system. Check it out.

4. Quirks and Magic

Every now and then you come across a puzzling question in Stackoverflow, that teaches you something new. We chose a few of our favorite gems:

Why does this code using random strings print “hello world”?

The question present the following print statement, that prints out “hello world”:

public static String randomString(int i)
{
    Random ran = new Random(i);
    StringBuilder sb = new StringBuilder();
    while (true)
    {
        int k = ran.nextInt(27);
        if (k == 0)
            break;

        sb.append((char)('`' + k));
    }

    return sb.toString();
}

System.out.println(randomString(-229985452) + " " + randomString(-147909649));

The answer is that there is no spoon. Meaning that choosing a random set of integers will not be random. Instead, the instance will follow the random number generation algorithm that begins with a specific seed parameter (in this case -229985452 or -147909649). Every time you’ll ask for a random pattern, that same seed will generate the same pattern – which will print out hello world.

The user Eng.Fouad explained it perfectly:

In new Random(-229985452).nextInt(27) the first 6 numbers that the random generates are:
8, 5, 12, 12, 15, 0

And the first 6 numbers that new Random(-147909649).nextInt(27) generates are:
23, 15, 18, 12, 4, 0

When you add those numbers to the integer representation of the character ` (which is 96) you get “hello world”:
104 –> h
101 –> e
108 –> l
108 –> l
111 –> o

119 –> w
111 –> o
114 –> r
108 –> l
100 –> d

Why is subtracting these two times (in 1927) giving a strange result?

In the following question, the user parses two date strings referencing times one second apart and compares them.

public static void main(String[] args) throws ParseException {
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    String str3 = "1927-12-31 23:54:07";  
    String str4 = "1927-12-31 23:54:08";  
    Date sDt3 = sf.parse(str3);  
    Date sDt4 = sf.parse(str4);  
    long ld3 = sDt3.getTime() /1000;  
    long ld4 = sDt4.getTime() /1000;
    System.out.println(ld4-ld3);
}

Instead of getting the result of 1, since they are 1 second apart, he gets the result 353 (queue the spooky music). This has a pretty basic explanation: it’s a time zone thing. On December 31st 1927 Shanghai time moved 5 minutes and 52 seconds back, and Java is parsing it as the instant for that local date/time.

We do have to point out that if you’ll try to run the code from the original question, it will generate a different result. As Jon Skeet pointed out in his answer, in Time Zone Database Project 2014 the time of the change has moved to 1900-12-31, and it’s now a mere 343 second change.

Uncatchable ChuckNorrisException

This is a bit of an obvious question: if an exception is thrown but no one can catch it, will the application crash? Or as the question asks: “Is it possible to construct a snippet of code in Java that would make a hypothetical java.lang.ChuckNorrisException uncatchable?”.

The short answer is that it’s possible, but there’s a “but” involved. You can compile code that throws a ChuckNorrisException, and define a class ChuckNorrisException which does not extend Throwable at runtime. That alone isn’t enough to get it to work, and you’ll have to disable the bytecode verifier. The answer from jtahlborn gives will take you through the full process.

If you’re a fan of Java puzzles, you might want to check out our Java Deathmatch game.

5. Hash Maps

One of the most common issue we came across on Stackoverflow is related to hash maps. A lot of users want to know what’s the difference between collections and when one should be used over another.

The key ingredient here is iteration order. With HashMap you’ll have no information about the order, and that order might change as you add more elements to your collection. With TreeMap you’ll get a sorted iteration, while with LinkedHashMap you’ll get a FIFO order.

If you’re still feeling confused about this, our friends at Rebel Labs made a handy chart that explains the benefits of one collection over the other.

Final Thoughts

It doesn’t matter how much you know about Java, there’s always more you can learn. Stackoverflow helps out with specific problems in the code, but it’s also a great source to learn new information about things we think we know front to back.

If you came across an interesting question, a fiery debate or another quirk, we would love to hear about it in the comments below.

Henn Idan

Henn works at OverOps, helping developers know when and why code breaks in production. She writes about Java, Scala and everything in between. Lover of gadgets, apps, technology and tea.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button