File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

help

 
Jaffery Rab
Ranch Hand
Posts: 36
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 295
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
That's because your string variable was not explicitly initialized by you, thus it will be implicitly initialized to null.
Clement
 
Manish Hatwalne
Ranch Hand
Posts: 2591
Android Firefox Browser Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13974
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Jaffery Rab
Ranch Hand
Posts: 36
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx much guys
Jaffery
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic