Core Java

Stack Overflow Answers the Top Java Questions We Didn’t Know We Had

A collection of Stack Overflow questions that you shouldn’t miss out on:

It’s no secret; we all use Stack Overflow. It holds the answers to life, the universe and pretty much everything code related. The platform provides a place for developers, engineers and others to find answers to an issue that they’re facing, or at least set them on the right track towards a solution.

One of the most popular categories on Stack Overflow is Java, with almost 1.5 million questions asked in total, and hundreds that are added every day. It holds some pretty interesting answers to questions you’ve stumbled upon in your day-to-day tasks, as well as answers to questions you had no idea you should ask.

top java questions

We can always learn something new, and that’s exactly what we decided to search for: Interesting answers to questions we didn’t know we had. Let’s check it out.

Java Puzzles

Stack Overflow is a place to find answers, but it’s also an excellent place for more questions and riddles. Kevin Cruijssen, a Software developer from the Netherlands posted asked the following question:

Why does array[idx++]+=“a” increase idx once in Java 8 but twice in Java 9 and 10?

To prove it, he created the following code:

import java.util.*;
public class Main {
  public static void main(String[] args) {
    int size = 3;
    String[] array = new String[size];
    Arrays.fill(array, "");
    for(int i = 0; i <= 100; ) {
      array[i++%size] += i + " ";
    }
    for(String element: array) {
      System.out.println(element);
    }
  }
}

Running this in Java 8, we get the following output:

1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55 58 61 64 67 70 73 76 79 82 85 88 91 94 97 100 
2 5 8 11 14 17 20 23 26 29 32 35 38 41 44 47 50 53 56 59 62 65 68 71 74 77 80 83 86 89 92 95 98 101 
3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99

However, in Java 10, we get this:

2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100 102 
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100

Before you read on, can you try to guess what happened here? What is the mysterious Java property that led to the different output between versions?

Prepare to be underwhelmed: it’s a bug in javac, that started at JDK 9. According to the official bug report, when “+=” is applied to String operands it can cause some side effects, as we can see in the code above.

Jorn Vernee took this answer one step forward and looked at the corresponding bytecode for this line:

array[i++%size] += i + ” “;

This is the output:

  21: aload_2
  22: iload_3
  23: iinc          3, 1
  26: iload_1
  27: irem
  28: aload_2
  29: iload_3
  30: iinc          3, 1
  33: iload_1
  34: irem
  35: aaload
  36: iload_3
  37: invokedynamic #5,  0 // makeConcatWithConstants:(Ljava/lang/String;I)Ljava/lang/String;
  42: aastore

On the bright side, this issue has been fixed and will deploy in JDK 11, along with some other nice features.

The Importance of NullPointerException

How much time do you spend going over logs, trying to find exceptions and handle them? We already know the answer – too long. And indeed, Stack Overflow provides a place where we can consult and search for the right answers to relevant questions, and in most cases, someone has already encountered the very same issue in the past.

One of the more common exceptions developers encounter is NullPointerException. In fact, it’s the most common exception in Java production environments. One question that caught our eye was someone trying to find the root cause of the issue, by asking “What is a NullPointerException, and how do I fix it?.”

The most voted up answer broke it down to steps, so it’ll be easier to understand what happens in the process. It starts by declaring a pointer to an object, by declaring a reference variable.

Integer num;
num = new Integer(10);

The first line is the pointer, and since we didn’t state what to point it to, Java sets it to null. It’s only on the second line where we create an object type Integer and the pointer variable num is assigned this object.

NullPointerException occurs on the first line, after we declare a variable but didn’t create an object. If we will attempt to dereference num before we create the object, we’ll get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that “num may not have been initialized” but sometimes you write code that does not directly create the object.

How can you solve it? One of the more talked-about methods on Stack Overflow is by adding null checks throughout the code. However, you’ll end up with too many lines of code that looks like this:

if (someobject != null) {
    someobject.doCalc();
}

And again, Stack Overflow comes to the rescue to help us make this code more efficient. Checking for null within the code makes sense in the case of null not being a valid response in terms of the contract, or… when it’s not a valid response.

The first advice is pretty simple: don’t use null as a response. However, if null is a valid response, we have to check for it. It’s easier when we’re using methods that return collections; we can return empty collections (or arrays) instead of nulls.

If we’re not using collections, we can use the Null Object pattern. In this pattern, we use an object which implements the expected interface, whose method body is empty. To put it in code, compare this:

Parser parser = ParserFactory.getParser();
if (parser == null) {
  // now what?
  // this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
  // do nothing
} else {
  action.doSomething();
}

To this:

ParserFactory.getParser().findAction(someInput).doSomething();

If it’s the second case we’ve mentioned, null not being a valid response, we can use assert statements. So it’ll look like this:

assert <condition>
//or
assert <condition> : <object>

There are other ways in which you can handle NullPointerExceptions and explanations of why it’s so important – check it out.

Local Variable Type Inference in Java 10

One of the most talked-about changes in Java 10 was the introduction of Local Variable Type Inference, adding some syntactic sugar to Java – simplifying it and improving the developer experience.

Java 10 allows us to declare variables without having to specify the associated type. So:

List<String> list = new ArrayList<String>();
Stream<String> stream = getStream();

Will be replaced with this new, simplified syntax:

var list = new ArrayList();
var stream = getStream();

This change leads to an interesting question; What is the difference between var in Kotlin and in Java? As Alexey Romanov explained, their meaning is very different.

In Kotlin, var means “this is a mutable variable”, and can be used both when type is inferred and when it’s explicit. On the other hand, the meaning of var in Java is “this is a variable with inferred type”, and can be used both for mutable and final variables.

The bottom line is that var in Java can only be used for local variables; while var in Kotlin is used for properties as well.

Final Thoughts

Stack Overflow is more than just a question and answer site. It’s a community, where people help each other out, have lively discussions and just come to enjoy themselves.

If you need help with a piece of code or have a fun riddle that you can’t solve, it’s the perfect place to go. These questions make up just a small part of what you can find there, and if you’ve seen questions that you think deserve a spotlight, we want to know! Post your favorite answers or unanswered questions in the comments below.

Published on Java Code Geeks with permission by Henn Idan, partner at our JCG program. See the original article here: Stack Overflow Answers the Top Java Questions We Didn’t Know We Had

Opinions expressed by Java Code Geeks contributors are their own.

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