It's okay to combine null with Java's `+` operator (it doesn't drop with nullpo)

There are times when I want to concatenate a String variable with the + operator and display it in the log, but I often think "that? Is this variable null okay?" I will. If you crash it with Nullpo for log output, it will be overturned.

In conclusion, there is no problem! !! is.

It's okay to combine null with the + operator

String n = null;
System.out.println("fuga:" + n); 
// fuga:Output as null

It's okay to use null for format

It's okay to use String.format

String n = null;
System.out.println(String.format("hoge:%s",n)); 
// hoge:Displayed as null
System.out.println(String.format("fuga:%02d", n));
// fuga:Displayed as null

It's okay to combine instances of a class with the + operator

import java.util.ArrayList;
public class Main {
    public static void main(String[] argv) {
        //Your own class is also okay
        MyClass myClass = new MyClass();
        System.out.println("hoge:" + myClass);
        // hoge:MyClass@Displayed as 60e53b93(@After that it changes)

        //Built-in class is also okay
        ArrayList<Object> arrayList = new ArrayList<>();
        System.out.println("fuga:" + arrayList);
        // fuga:[]Displayed as(I see, i see)

        //Built-in class is also a die job
        Object object = new Object();
        System.out.println("piyo:" + object);
        // piyo:java.lang.Object@5e2de80c(@After that it changes)
    }
}
class MyClass {
}

Be careful when using an instance of a class in format!

As we have seen so far, except for the fomat operator % s, if it is an instance of a class that cannot be converted, an Exception will be thrown and it will fall.

public class Main {
    public static void main(String[] argv) {
        MyClass myClass = new MyClass();
        System.out.println(String.format("hoge:%s",myClass));
        // hoge:MyClass@Displayed as 78308db1(@After that it changes)

        System.out.println(String.format("hoge:%d",myClass));
        // java.util.Fall with IllegalFormatConversionException
    }
}
class MyClass {
}

Summary

It was a Java8 operation-based verification, but it was okay if it was combined with the + operator. I wonder if Java teachers will comment on Vespra.

Recommended Posts

It's okay to combine null with Java's `+` operator (it doesn't drop with nullpo)
Things to check when it doesn't work with proguard