Win a copy of Event Streams in Action this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

another Mock Exam Question

 
Ranch Hand
Posts: 413
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all
This is a question from Mock Exam
1 String s = null;
2 if ( s != null & s.length() > 0)
3 System.out.println("s != null & s.length() > 0");
4 if ( s != null && s.length() > 0)
5 System.out.println("s != null & s.length() > 0");
6 if ( s != null | | s.length() > 0)
7 System.out.println("s != null & s.length() > 0");
8 if ( s != null | s.length() > 0)
9 System.out.println("s != null | s.length() > 0");
Which of the following lines throwing null pointer exception

A. 2,4
B. 6,8
C. 2,4,6,8
D. 2,6,8
Correct answer is D
But I could not get logic behind it clearly
Can anyone be of any help in this regard ?

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A logical OR operator '|' and a logical AND '&' operator evaluates both the expressions and therefore java compiler throws a nullpointerException while evaluating the 's.length()' statement as s is set to null. But in a short Circuited(&&) operator if the 1st condition is true it evaluates the next condition and gives the exception but in a short circuited (| |) operator if the first condition is true the it dosnt evaluate the next condition hence the exception is not thrown.
 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Refer Short Circuit operators (| | ,&&),in these operators ,decision to execute the second expression is based on the result of the first one.
Normal operators (&,|)will evaluate both the expressions.
At line 2, s.length() is evaluated and results in exception.
At line 4,s.length() is not evaluated because the first one is false.
At line 6,s.length() is evaluated as the first expression is false.
At line 8,s.length() is evaluated.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!