Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

StackOverflow: Seven of the Best Java Answers That You Haven’t Seen

DZone's Guide to

StackOverflow: Seven of the Best Java Answers That You Haven’t Seen

Henn Idan of Takipi covers branch prediction, security in Java, exceptions, and those puzzling questions on StackOverflow that get you thinking.

· Java Zone
Free Resource

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

This post is by Henn Idan on the Takipi blog.

StackOverflow is a gold mine 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 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.

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. An educated guess if you’d prefer, only it’s not actually a guess.

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 failed branch prediction. That happened because the branch had no recognizable pattern, so trying to predict its actions is pretty random.

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.

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.

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 presents the following print statement, that prints out “hello world”:

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 six 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.

Instead of getting the result of one, since they are one 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 five 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.

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.

Bio of the author of this post Henn Idan: I write about Java, Scala and everything in between. Lover of gadgets, apps, technology and tea.

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

Topics:
stack overflow ,java ,question and answer

Published at DZone with permission of Henn Idan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}