The Artima Developer Community
Sponsored Link

Java Answers Forum
=NullPointerException with Compartor, help

2 replies on 1 page. Most recent reply: Sep 8, 2003 3:44 AM by David

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
giles corey

Posts: 1
Nickname: anonaki
Registered: Sep, 2003

=NullPointerException with Compartor, help Posted: Sep 6, 2003 12:38 PM
Reply to this message Reply
Advertisement
Why does the code below throw a java.lang.NullPointerException?? The two objects being
compared obviously don't become Null references.
any help would be greatly appreciated.

import java.util.*;

class test3
{
public static void main( String [] args )
{
Object obj1 = new Integer( 1 );
Object obj2 = new Integer( 2 );

if ( cmp.compare( obj1 ,obj2 ) == 0 )
System.out.println( "They are Equal" );
}

static Comparator cmp;
}


Senthoorkumaran Punniamoorthy

Posts: 335
Nickname: senthoor
Registered: Mar, 2002

Re: =NullPointerException with Compartor, help Posted: Sep 6, 2003 2:51 PM
Reply to this message Reply
Its throwing an exception since Comparator is a Interface rather than a Class. An interface must be implemented before usage. The Comparator interface has two methods, equals() and compare(). You should refer to the JavaDoc before implementing these interfaces.

In your case you are passing the objects to the interface itself and not to a class which implements the interface.

Check these article for more info

http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-sort_p.html


http://www.onjava.com/lpt/a/3286

David

Posts: 150
Nickname: archangel
Registered: Jul, 2003

Re: =NullPointerException with Compartor, help Posted: Sep 8, 2003 3:44 AM
Reply to this message Reply
Senthoorkumaran is basically right, but I think the point is being missed. You've declared a reference variable ('cmp'), but you never assign anything to it! It's equivalent to doing the following:
  String myString;
  String myNewString = myString.toUpperCase(); // Will throw NullPointerException!

Flat View: This topic has 2 replies on 1 page
Topic: Event Handling (not using applets) Previous Topic   Next Topic Topic: Casting applet to JApplet

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use