toString() givies null value and why?

Viewed 40
  public class TestString {
            public Test test1;
    
                  @Override
            public String toString() {
                StringBuilder sub = new StringBuilder();
                sub.append(test1);
                sub.append("care ful with NPE");
                return test1 +"care ful with NPE";
            }
    
            public static void main(String[] args) {
                final TestString testToString = new TestString();
                System.out.println(testToString);
                
            }
        }
 public class Test {
        private final String fieldName;

   public Test() {
            fieldName = "";
        }
        public Test(String fieldName) {
            this.fieldName = fieldName;
        }
    
        public String toString() {
            StringBuilder sub = new StringBuilder();
            sub.append("xxxasd");
            return "xxxasd";
        }
        public int hashCode() {
            return fieldName.hashCode();
        }
    
    }

how to get the value of test1 toString().here why i get null value here? I use string buffer to append the string but I can return the value as string.

1 Answers

To me it prints nullcare ful with NPE which is understandable because test1 is never initialized so its value is null and the String representation of a null Object is "null".

Related