Thursday, May 6, 2010

String

Given below code :

public class StringTester {

private String test;

public String getTest() {
return test;
}

public void setTest(String test) {
this.test = test;
}

public static void main(String[] args) {
StringTester stringTester = new StringTester();
if (stringTester.getTest() == null) {
System.out.println("test is NULL");
} else if (stringTester.getTest().isEmpty()) {
System.out.println("test is EMPTY");
}

System.out.println("test : " + stringTester.getTest());
if (stringTester.getTest().equals("hello")) {
System.out.println(stringTester.getTest() + " is equals to \"hello\"");
}
}
}



The result will be :
test is NULL
test : null
Exception in thread "main" java.lang.NullPointerException
at vc.qa.automation.rachel.StringTester.main(StringTester.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:90)

A string which has not been set :

  • will be printed out as "null".
  • cannot be compared with other strings.

1 comment: