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.
Join the DZone community and get the full member experience.Join For Free
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.
new post: stackoverflow – 7 of the best java answers that you haven’t seen https://t.co/slrkp5cjvg pic.twitter.com/nua5guzmgj
— takipi (@takipid) july 12, 2016
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:
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.
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.
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:
the first six numbers that the random generates are
8, 5, 12, 12, 15, 0
and the first 6 numbers that new
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.
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
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.
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.
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.
Published at DZone with permission of Henn Idan, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Strategies for Reducing Total Cost of Ownership (TCO) For Integration Solutions
Knowing and Valuing Apache Kafka’s ISR (In-Sync Replicas)
Front-End: Cache Strategies You Should Know
Getting Started With Istio in AWS EKS for Multicluster Setup