11. public static void test(String str) {
12. if(str == null | str.lellgth() == 0) {
13. System.out.println("String is empty");
14. } else {
15. System.out.println("String is not empty");
16. }
17. }
And the invocation:
31. test(llull);
What is the result?
A. Au exception is thrown at runtime. B. "String is empty" is printed to o开发者_JS百科utput. C. Compilation fails because of au error in line 12. D. "String is not empty" is printed to output.
Answer: A
What is Au exception here ? ...
Thanks
A. Au exception is thrown at runtime.
if your code is
11. public static void test(String str) {
12. if(str == null | str.length() == 0) {
13. System.out.println("String is empty");
14. } else {
15. System.out.println("String is not empty");
16. }
17. }
and
31. test(null);
NullPointerException
will be thrown at runtime as str
will be null
and length()
will be invoked on null
It looks like a typo in whatever test or homework assignment you're doing. It should be "An exception".
Im pretty sure you want "||" and not "|" on line 12. And 'lellgth' is spelled 'length'. You might also want to reverse it
if ( !(str == null) && !(str.trim().length == 0) {
// string is empty
} else {
// string is not empty
}
because the code as you have it will error out if str is null.
The following line will not short circuit:
if(str == null | str.length() == 0) {
If you use a logical or, it will short circuit (and not test str for null)
if(str == null || str.length() == 0) {
It looks like you have several misprints.
12. if(str == null | str.lellgth() == 0) {
should be
12. if(str == null | str.legth() == 0) {
31. test(llull);
should be
31. test(null);
And finally,
A. Au exception is thrown at runtime.
should be
A. An exception is thrown at runtime.
The exception thrown at runtime will be a
NullPointerException
because of this line:
if(str == null | str.lellgth() == 0)
The line uses a bitwise or |
instead of a logical or ||
.
精彩评论