Stack Overflow questions you should read if you program in Java
Peter Lawrey shares some advice as the man with the most answers for Java on Stack Overflow.
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:
- Is Java Pass by Reference or Pass by Value?
- How do I compare Strings?
- Why does 128 == 128 return false but 127 == 127 return true?
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:
- Converting an InputStream to a String
- How to generate numbers in a specific range
- When to use a LinkedList instead of an ArrayList
- Difference between public, default, protected and private
- How to test if an Array contains a value
- Why you should implement Runnable rather than extend Thread
- Does finally always execute?
- How to convert a String to an Enum
- Breaking out of nested loops
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.
We're hiring! Do you like working in an ever evolving organization such as Zalando? Consider joining our teams as a Software Engineer!