Search code examples
javaobjecttostring

Is it possible to use toString on undeclared object?


I want to print "None" value for undeclared objects instead of null. Is it possible?

public class class1 {
    class2 c2;

    public static void main(String[] args) {
        class1 c1=new class1();
        System.out.println(c1.c2);

    }
}
class class2{

    public String toString(){
        if(this==null){
            return "None";
        }else{
            return "Correct";
        }
    }
}

Edit: I have added the code. This code prints:

null

But I want to print "None". What should I do?


Solution

  • The utility class Objects offers a lot of useful methods. There's for example Objects#toString(Object) and Objects#toString(Object, String).

    final String s = Objects.toString(obj, "None");
    

    After your edit: the this reference is never null, therefore this == null will always be false. You need to handle the null-check outside of your class. Normally, String.valueOf will be called when converting an object to a string. This method handles null references, not the class itself. You'd have to manually convert your object to a string first (with the utility described above).

    You'd need to change your code:

    public class Class1 {
        Class2 c2;
    
        public static void main(String[] args) {
            Class1 c1 = new Class1();
            System.out.println(Objects.toString(c1.c2, "None"));
        }
    }
    class Class2 {
        @Override
        public String toString(){
                return "Correct";
        }
    }
    

    You can always create a wrapper around Objects#toString(Object,String) to avoid specifying the default value over and over again:

    public final class MyObjects {
      private MyObjects(){}
      public static String toString(final Object obj) {
        return Objects.toString(obj, "None");
      }
    }