StackOverflow Q&A you should read if you program in Java

Overview

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

How do I compare Strings?

The more general questions 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 str this 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 are 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 only other type is void which is only used as a return type.




How do I avoid lots of != null?

Checking for null is tedious, however unless you know a variable can't be null, there is a chance it will be null.  There is @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 an write

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

Other useful hints

How to effectively iterator over a map note in Java 8 you can use map.forEach((k, v) -> { });


Comments

Post a Comment

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

Low Latency Microservices, A Retrospective

Unusual Java: StackTrace Extends Throwable