wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "help" Watch "help" New topic
Author

help

Jaffery Rab
Ranch Hand

Joined: Jan 18, 2002
Posts: 36
class hey{

String s;
hey(){
if(s.length()==0){
System.out.println("Hello");}
else{
System.out.println("Fail");}

}
public static void main(String args[]){
new hey();
}}
when I compile it, I will get NullPointException even if I will check s.length()<0; or s.length()>0;
why is that?
Jaffery
Steven Wong
Ranch Hand

Joined: Mar 07, 2002
Posts: 295
Hi,
That's because your string variable was not explicitly initialized by you, thus it will be implicitly initialized to null.
Clement


best regards,<br />Steven<br />SCJP, SCEA
Manish Hatwalne
Ranch Hand

Joined: Sep 22, 2001
Posts: 2578

In other words change your if condition to this -

Due to short circuit nature of && operator, the condition s.length()==0 will be evaluated only when s is not null.
HTH,
- Manish
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Originally posted by Jaffery Rab:
when I compile it, I will get NullPointException even if I will check s.length()<0; or s.length()>0;
why is that?
Jaffery
In fact, the s.length() will cause a NullPointerException because you are running a method on a null!


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Jaffery Rab
Ranch Hand

Joined: Jan 18, 2002
Posts: 36
Thanx much guys
Jaffery
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

Jaffery-
Just a suggestion -- but try giving your posts a descriptive subject instead of "help" give it something like "NullPointerException with String.length()" -- Just an idea
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Originally posted by Jessica Sant:
Jaffery-
Just a suggestion -- but try giving your posts a descriptive subject instead of "help" give it something like "NullPointerException with String.length()" -- Just an idea

To go along with what Jessica said - giving your posts a good topic makes them easier to search for. If someone wanted to find something on a NullPointerException, they might never find your thread.
Corey


SCJP Tipline, etc.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: help
 
Similar Threads
Confusion
another Mock Exam Question
JXam Qns
When does a NullPointerException occurs?
Determine the space occurrence within a String