The Artima Developer Community
Sponsored Link

Java Buzz Forum
Casting null and failing fast

0 replies on 1 page.

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 0 replies on 1 page
Chris Winters

Posts: 931
Nickname: cwinters
Registered: Jul, 2003

Daytime: Java hacker; nighttime: Perl hacker; sleeptime: some of both.
Casting null and failing fast Posted: Nov 18, 2004 1:41 PM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Chris Winters.
Original Post: Casting null and failing fast
Feed Title: cwinters.com
Feed URL: http://www.cwinters.com/search/registrar.php?domain=jroller.com®istrar=sedopark
Feed Description: Chris Winters on Java, programming and technology, usually in that order.
Latest Java Buzz Posts
Latest Java Buzz Posts by Chris Winters
Latest Posts From cwinters.com

Advertisement

I never thought about it before, but it turns out you can cast null with no ill effects. Here's an example:

public class CastNull {
    public static void main( String[] args ) {
        Object someNull = null;
        String castedFromObject = (String)someNull;
        try {
            out( "Length: " + castedFromObject.length() );
        } catch ( NullPointerException e ) {
            out( "Caught NPE from castedFromObject" );
        }
        String castedFromNull = (String)null;
        try {
            out( "Length: " + castedFromNull.length() );
        } catch ( NullPointerException e ) {
            out( "Caught NPE from castedFromNull" );
        }
    }
    private static void out( String msg ) {
        System.out.println( msg );
    }
}

I had expected this to die at the two String casts. Nope. Each dies when you try to call a method on it -- this will print out both of the 'Caught NPE' lines from the catch blocks. If you think about null as an instance of Object (which happens to be null) then it makes sense, but doesn't the fail-fast principle tell us we should instead die at the cast?

Read: Casting null and failing fast

Topic: Two Americas Previous Topic   Next Topic Topic: Eclipse Tips & Tricks

Sponsored Links



Google
  Web Artima.com   

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