public class Quiz public static void mainString args String

public class Quiz {public static void main(String[] args) {String s = null; if (s.length() >0) {System.out.println(s);} else {System.out.println(\"empty string\");}}} Which of the following statement best characterizes the above Java program: The program runs without error, but displays nothing on the console. Displays a message of the form \"String@5e8fce95\" on the console. Displays \"empty string\" on the console. Produces a compile-time error: public Quiz.java:4: variable s might not have been initialized if (s.length() > 0) {1 error Produces a run-time error: Exception in thread \"main\" java.lang.NullPointerException at Quiz.main(Quiz.java:4)

Solution

The variable can have a default value (and setName can prevent it being set to null):

Either the print or printString method can check for null, for example:

Or you can design the class so that name always has a non-null value:

 public class Quiz {public static void main(String[] args) {String s = null; if (s.length() >0) {System.out.println(s);} else {System.out.println(\

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site