Examveda
Examveda

Determine output:
public class Test{
      public static void main(String args[]){
            String str = null;
            if(str.length() == 0){
                  System.out.print("1");
            }
            else if(str == null){
                  System.out.print("2");
            }
            else{
                  System.out.print("3");
            }
      }
}

A. Compilation fails.

B. "1" is printed.

C. "2" is printed.

D. "3" is printed.

E. An exception is thrown at runtime.

Answer: Option E


This Question Belongs to Java Program >> Strings

Join The Discussion

Comments ( 5 )

  1. Vamsi Vamsi
    Vamsi Vamsi :
    5 months ago

    In the code, the str variable is initialized as null. When the program attempts to execute str.length(), it triggers a NullPointerException because you cannot invoke methods or access properties on a null object. The code attempts to check the length of the string (str.length()) before checking if it is null (str == null), leading to the exception.

    To avoid the exception, you should first check if the string is null before attempting to access its length.

  2. Jiya Ahuja
    Jiya Ahuja :
    4 years ago

    How plz explain

  3. Mohammad Shahrukh
    Mohammad Shahrukh :
    5 years ago

    Exception in thread "main" java.lang.NullPointerException
    at gomes.main(gomes.java:10)

  4. Rishabh Nandwal
    Rishabh Nandwal :
    6 years ago

    NullPointerException is thrown when an application attempts to use an object reference that has the null value

  5. Swapnil Patil
    Swapnil Patil :
    6 years ago

    how it will work give the solution with given code

Related Questions on Strings