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");
}
}
}
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
Join The Discussion
Comments ( 5 )
Related Questions on Strings
In Java, which class is used to represent a sequence of characters as a string?
A. String
B. StringBuilder
C. StringSequence
D. StringArray
What is the correct way to create a new empty String object in Java?
A. String emptyString = "";
B. String emptyString = new String();
C. String emptyString = " ";
D. String emptyString = null;
E. Both A and B
Which of the following methods is used to compare two strings for equality in Java?
A. equals()
B. compareTo()
C. equalsIgnoreCase()
D. compare()
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.
How plz explain
Exception in thread "main" java.lang.NullPointerException
at gomes.main(gomes.java:10)
NullPointerException is thrown when an application attempts to use an object reference that has the null value
how it will work give the solution with given code