Stack Overflow questions you should read if you program in Java

by Peter Lawrey - 15 Apr 2016

There are common questions which come up repeatedly in Java. Even if you know the answer, it's worth getting a more thorough understanding of what is happening in these cases.

How do I compare Strings?

The more general question is, how do I compare the contents of an Object? What is surprising when you use Java for the first time is that if you have a variable like String which is a reference to an Object, not the Object itself. This means when you use == you are only comparing references. Java has no syntactic sugar to hide this fact, so == only compares references, not the contents of references.

If you’re in any doubt, Java only has primitives and references for data types up to Java 9 (in Java 10 it might value value types). The other type is void, which is only used as a return type.

Some other questions you should check out:

How do I avoid lots of != null?

Checking for null is tedious, however unless you know a variable can't be null, there still a chance it will be null. There are @NotNull annotations available for FindBugs and IntelliJ, which can help you detect null values where they shouldn't be without extra coding. Optional can also play a role now.

Say you have:

   if (a != null && a.getB() != null && a.getB().getC() != null) {
a.getB().getC().doSomething();
}

Instead of checking for null, you can write:

    Optional.ofNullable(a)
.map(A::getB)
.map(B::getC)
.ifPresent(C::doSomething);

See the answer for “Avoid null statements” for more information.

Other useful hints:

How to effectively iterator over a map – Note that in Java 8 you can use:

  map.forEach((k, v) -> { });

For more posts about Java, see my blog Vanilla Java. You can also contact me on Twitter @PeterLawrey.

Similar blog posts