EzDevInfo.com

nullpointerexception interview questions

Top nullpointerexception frequently asked interview questions

Avoiding != null statements

The idiom I use the most when programming in Java is to test if object != null before I use it. This is to avoid a NullPointerException. I find the code very ugly, and it becomes unreadable.

Is there a good alternative to this?

I want to address the necessity to test every object if you want to access a field or method of this object. For example:

if (someobject != null) {
    someobject.doCalc();
}

In this case I will avoid a NullPointerException, and I don't know exactly if the object is null or not. These tests appear throughout my code as a consequence.


Source: (StackOverflow)

Why does int num = Integer.getInteger("123") throw NullPointerException?

The following code throws NullPointerException:

int num = Integer.getInteger("123");

Is my compiler invoking getInteger on null since it's static? That doesn't make any sense!

What's happening?


Source: (StackOverflow)

Advertisements

No Exception while type casting with a null in java

String x = (String) null;

Why there is no exception in this statement?

String x = null;
System.out.println(x);

It prints null. But .toString() method should throw a null pointer exception.


Source: (StackOverflow)

NullPointerException in Java with no StackTrace

I've had instances of our Java code catch a NullPointerException, but when I try to log the StackTrace (which basically ends up calling Throwable.printStackTrace() ), all I get is:

java.lang.NullPointerException

Has anyone else come across this? I tried googling for "java null pointer empty stack trace" but didn't come across anything like this.


Source: (StackOverflow)

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

I currently have an Activity that when it gets displayed a Notification will also get displayed in the Notification bar.

This is so that when the User presses home and the Activity gets pushed to the background they can get back to the Activity via the Notification.

The problem arises when a User presses the back button, my Activity gets destroyed but the Notification remains as I want the user to be able to press back but still be able to get to the Activity via the Notification. But when a USER tries this I get Null Pointers as its trying to start a new activity rather than bringing back the old one.

So essentially I want the Back button to act the exact same as the Home button and here is how I have tried so far:


        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event)  {
            if (Integer.parseInt(android.os.Build.VERSION.SDK) < 5
                    && keyCode == KeyEvent.KEYCODE_BACK
                    && event.getRepeatCount() == 0) {
                Log.d("CDA", "onKeyDown Called");
                onBackPressed();
            }

            return super.onKeyDown(keyCode, event);
        }

        public void onBackPressed() {
            Log.d("CDA", "onBackPressed Called");
            Intent setIntent = new Intent(Intent.ACTION_MAIN);
            setIntent.addCategory(Intent.CATEGORY_HOME);
            setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(setIntent); 

            return;
        }   

However the above code still seems to allow my Activity to be destroyed, How can I stop my Activity from being destroyed when the back button is pressed?


Source: (StackOverflow)

Best explanation for languages without null

Every so often when programmers are complaining about null errors/exceptions someone asks what we do without null.

I have some basic idea of the coolness of option types, but I don't have the knowledge or languages skill to best express it. What is a great explanation of the following written in a way approachable to the average programmer that we could point that person towards?

  • The undesirability of having having references/pointers be nullable by default
  • How option types work including strategies to ease checking null cases such as
    • pattern matching and
    • monadic comprehensions
  • Alternative solution such as message eating nil
  • (other aspects I missed)

Source: (StackOverflow)

Why can I throw null in Java?

When running this:

public class WhatTheShoot {

    public static void main(String args[]){
        try {
            throw null;
        } catch (Exception e){
            System.out.println(e instanceof NullPointerException);
            System.out.println(e instanceof FileNotFoundException);
        }
    }
}

The response is:

true  
false

Which was fairly stunning for me. I would have thought this would net a compile-time error.

Why can I throw null in Java, and why does it upcast it to a NullPointerException?

(Actually, I don't know if it is an "upcast", given I'm throwing null)

Aside from a really really stupid interview question (please nobody ask this in an interview) I cannot see any reason to throw null. Maybe you want to be fired, but that's... I mean, why else would anyone throw null?

Fun fact IntelliJ IDEA 12 tells me that my line, e instanceof NullPointerException, will always be false. Which isn't true at all.


Source: (StackOverflow)

What is a Null Pointer Exception, and how do I fix it?

What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?

What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?


Source: (StackOverflow)

IllegalArgumentException or NullPointerException for a null parameter?

I have a simple setter method for a property and null is not appropriate for this particular property. I have always been torn in this situation: should I throw an IllegalArgumentException, or a NullPointerException? From the javadocs, both seem appropriate. Is there some kind of an understood standard? Or is this just one of those things that you should do whatever you prefer and both are really correct?


Source: (StackOverflow)

Which @NotNull Java annotation should I use?

I'm looking to make my code more readable as well as use tooling like IDE code inspection and/or static code analysis (FindBugs and Sonar) to avoid NullPointerExceptions. Many of the tools seem incompatible with each others' @NotNull/@NonNull/@Nonnull annotation and listing all of them in my code would be terrible to read. Any suggestions of which one is the 'best'? Here is the list of equivalent annotations I've found:

  • javax.validation.constraints.NotNull
    Created for runtime validation, not static analysis.
    documentation

  • edu.umd.cs.findbugs.annotations.NonNull
    Used by Findbugs static analysis and therefore Sonar
    documentation

  • javax.annotation.Nonnull
    This might work with Findbugs too, but JSR-305 is inactive.
    source

  • org.jetbrains.annotations.NotNull
    Used by IntelliJ IDEA IDE for static analysis.
    documentation

  • lombok.NonNull
    Used to control code generation in Project Lombok.
    Placeholder annotation since there is no standard.
    source, documentation

  • android.support.annotation.NonNull
    Marker annotation available in Android, provided by support-annotations package
    documentation


Source: (StackOverflow)

How come invoking a (static) method on a null reference doesn't throw NullPointerException?

I wrote this program in Java

public class Why {

  public static void test() {
    System.out.println("Passed");
  }

  public static void main(String[] args) {
    Why NULL = null;
    NULL.test();
  }

}

I read that invoking a method on a null object causes NullPointerException, and yet the above program doesn't? Why is this? Am I not understanding something correctly?


Source: (StackOverflow)

NullPointerException that doesn't point to any line in my code

I am working on a game where the player can drag and drop things around the screen. I've got a private method which allows me to simulate a drag/drop event for any of the items that the player can move around. For the dragging I am actually leaving the view that they touched where it is and creating a new ImageView with and setting the drawable to the drawingCache from the touched view, then moving this newly created ImageView around the screen following their finger. When you release your finger (drop the view) I am calling myLayout.remove(movingImg); to get it off of the screen. I am having an issue where if I start a simulated drag event and then manually pick up one of the other items I am getting a null pointer on the myLayout.remove() call, here is the trace from Log:

04-06 10:37:43.610: ERROR/AndroidRuntime(23203): java.lang.NullPointerException
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2122)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.view.ViewGroup.drawChild(ViewGroup.java:2506)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2123)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.view.ViewGroup.drawChild(ViewGroup.java:2506)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2123)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.view.ViewGroup.drawChild(ViewGroup.java:2506)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2123)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.view.ViewGroup.drawChild(ViewGroup.java:2506)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2123)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.view.View.draw(View.java:9032)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.widget.FrameLayout.draw(FrameLayout.java:419)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1910)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.view.ViewRoot.draw(ViewRoot.java:1608)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.view.ViewRoot.performTraversals(ViewRoot.java:1329)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1944)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.os.Looper.loop(Looper.java:126)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at android.app.ActivityThread.main(ActivityThread.java:3997)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at java.lang.reflect.Method.invokeNative(Native Method)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at java.lang.reflect.Method.invoke(Method.java:491)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
04-06 10:37:43.610: ERROR/AndroidRuntime(23203):     at dalvik.system.NativeStart.main(Native Method)

The trace doesn't point to anywhere inside my activity. The exception gets thrown whenever the it tries to call myLayout.remove() on the simulated dragging view. I surrounded this line with a try / catch but that did nothing. I know that this is the line thats giving me trouble because if I comment it out then I don't get an exception but obviously then my view never gets removed from the screen. I am building this app on a Motorola xoom, I am not sure if this is a device specific issue or not though. Does anyone know what might be going on here?

This is the where the .removeView() is getting called from:

        @Override
        public void onAnimationEnd(Animation animation) {
            // TODO Auto-generated method stub
            Log.i(myTag, "Animation End");

            try {
                //myLayout.removeView(simulateMovingImg); //This is the line that is throwing a null pointer
                simulateMovingImg.setVisibility(View.GONE); //This is how I am currently getting around the issue
                params = new LayoutParams(oneImg.getWidth(),oneImg.getHeight()); // While its moving it appears larger than normal
                 simulateMovingImg.setLayoutParams(params);                     //  so I set it back to the normal size
                 if(whichTarget == true){
                     targetImg.setImageDrawable(simulateMovingImg.getDrawable()); //targetImg is one of the 'drop zones' so I set its 
                                                                                //  drawable to make it seem like the view was 'dropped' into this zone
                 }else{
                     target1Img.setImageDrawable(simulateMovingImg.getDrawable()); // same with target1Img. 
                 }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

             iAmDone = true;
        }
    });

That is inside an AnimationListener for the translate animation that is moving my ImageView from where it starts to where it is getting 'dropped'


Source: (StackOverflow)

Why comparing Integer with int can throw NullPointerException in Java?

It was very confusing to me to observe this situation:

Integer i = null;
String str = null;

if (i == null) {   //Nothing happens
   ...                  
}
if (str == null) { //Nothing happens

}

if (i == 0) {  //NullPointerException
   ...
}
if (str == "0") { //Nothing happens
   ...
}

So, as I think boxing operation is executed first (i.e. java tries to extract int value from null) and comparison operation has lower priority that's why the exception is thrown.

The question is: why is it implemented in this way in Java? Why boxing has higher priority then comparing references? Or why didn't they implemented verification against null before boxing?

At the moment it looks inconsistent when NullPointerException is thrown with wrapped primitives and is not thrown with true object types.


Source: (StackOverflow)

NullPointerException stack trace not available without debug agent

I have recently found a bug that causes a NullPointerException. The exception is caught and logged using a standard slf4j statement. Abridged code below:

for(Action action : actions.getActions()) {
    try {
        context = action.execute(context);
    } catch (Exception e) {
        logger.error("...", e);
        break;
    }
}

As you can see, nothing fancy. However, of all the exception logging statements that we have, just this one does not print a stack trace. All it prints is the message (represented as "...") and the name of the exception class (java.lang.NullPointerException).

Since the stack trace on an exception is lazy loaded, I thought maybe there is a instruction reordering issue of some sort and decided to call e.getStackTrace() before the log statement. This made no difference.

So I decided to restart with the debug agent enabled. However, because I even attached to the process, I noticed that now the stack traces were printing. So clearly the presence of the debug agent caused some additional debug information to become available.

I have since then fixed the root cause of the exception. But I would like to learn why the stack trace was unavailable without a debugger. Anyone know?

Clarification: this is not a logging issue. Imagine the same try/catch clause, but in the catch, I print the value of:

e.getStackTrace().length

Without a debugger this prints '0', with a debugger it prints a positive number (9 in this case).

More info: this is happening on JDK 1.6.0_13, 64bit, amd64, linux 2.6.9


Source: (StackOverflow)

What is the difference between "(Object)null" and "null" in Java? [duplicate]

This question already has an answer here:

Take a look at the following example:

class nul
{
  public static void main (String[] args)
  {
    System.out.println (String.valueOf((Object)null));
    System.out.println (String.valueOf(null));
  }
}

The first println writes null but the second throws a NullPointerException.

Why is only the second line worth an exception? And what is the difference between the two nulls? Is there a real null and a fake null in Java?


Source: (StackOverflow)