Common Questions in Java: Insights from Stack Overflow
Got some Java questions? Here are a few answers about comparing strings and avoiding != null.
Join the DZone community and get the full member experience.
Join For FreeOverview
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 are 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 that 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.
Is Java Pass by Reference or Pass by Value?
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 is a chance it will be null. There is @NotNull annotation 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);
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
How to convert a String to an Enum
How to effectively iterator over a map note in Java 8 you can use map.forEach((k, v) -> { });
Published at DZone with permission of Peter Lawrey, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments