Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Common Questions in Java: Insights from Stack Overflow

DZone's Guide to

Common Questions in Java: Insights from Stack Overflow

Got some Java questions? Here are a few answers about comparing strings and avoiding != null.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

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 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?

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 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);

Avoid null statements

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 in Java 8 you can use map.forEach((k, v) -> { });

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
java ,stack overflow

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}