var Obj = new function(){

     var StateValues = ['AL','AK','AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA',
    'KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND',
    'OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'];

    this.getItemRow = function(itemValue) {
     var myPosition=-1
       for (var i=0;i<StateValues.length;i++) {
          if(StateValues[i]==itemValue) {
            myPosition = i;
             break;
         }
      }
      return myPosition;
    };
}

This is an easier way to create objects.

var blah = 'this is private'
this.blah = 'this is public'

Answer from Stefan Kendall on Stack Overflow
🌐
Bacancy Technology
bacancytechnology.com › qanda › javascript › null-pointer-exception-in-javascript
Null Pointer Exception in JavaScript: A Complete Guide
June 27, 2024 - In JavaScript, a Null Pointer Exception is not a built-in error or exception type. However, JavaScript does have an error called TypeError that can occur when you try to access properties or call methods on null or undefined values.
Discussions

error handling - Catching "NullPointerExceptions" in JavaScript - Stack Overflow
If someId doesn't exist, a method will be called on null, which halts the entire program, in effect disabling all JS effects after the error. I could just check for null before executing such a statement, but this is getting tiring. I would like to catch an exception but I'm not sure which ... More on stackoverflow.com
🌐 stackoverflow.com
javascript - How do I avoid Null Pointer Exception? - Stack Overflow
Add a hidden input field that will submit the same value and copy the value from the disabled to this hidden field in the 's onsubmit() event ... Or alternatively , as you believe the null pointer exception is because subCaste is set to null ,you can try to to set subCaste variable ... More on stackoverflow.com
🌐 stackoverflow.com
November 21, 2011
How can I avoid null pointer errors in JavaScript? - Stack Overflow
I've got the following code: const result = A.field_1.subfield_2 How can I evaluate result to null when A in null (or A.field_1) and avoid null errors? I was wondering if there's a more elegant ap... More on stackoverflow.com
🌐 stackoverflow.com
July 17, 2019
java - What is a NullPointerException, and how do I fix it? - Stack Overflow
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 progra... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

What is a null pointer exception?
A null pointer exception is a runtime error thrown when a program tries to use a reference that points to nothing (null) as if it pointed to a real object. Calling a method on it, reading or writing a field, or indexing it all fail because there is no object there to act on. In Java it is the NullPointerException class, in C# it is NullReferenceException, in Python it is an AttributeError on a None value, and in JavaScript it is a TypeError such as cannot read properties of null.
🌐
generalistprogrammer.com
generalistprogrammer.com › home › tutorials › programming › null pointer exception: the complete cross-language guide to fixing and preventing it (2026)
How to Fix a Null Pointer Exception (NPE): Complete Guide 2026
How do you fix a null pointer exception?
Find the exact reference that is null at the line in the stack trace, then either make sure it is assigned a real value before you use it, or guard the access so the null case is handled safely. The fastest fix is a null check (if the value is not null, use it; otherwise fall back), but the durable fix is to stop the value being null in the first place: initialize fields, return empty collections instead of null, validate inputs at the boundary with something like Objects.requireNonNull, and use the language's null-safety features such as Java Optional, Kotlin's safe-call operator, C# nullable
🌐
generalistprogrammer.com
generalistprogrammer.com › home › tutorials › programming › null pointer exception: the complete cross-language guide to fixing and preventing it (2026)
How to Fix a Null Pointer Exception (NPE): Complete Guide 2026
How do you avoid null pointer exceptions in Kotlin?
Kotlin builds null safety into the type system. A type like String can never hold null, so the compiler rejects unsafe access at compile time; only a nullable type, written String?, can be null. To use a nullable value you use the safe-call operator ?. which returns null instead of throwing, the Elvis operator ?: to supply a default, or, rarely, the not-null assertion !! which deliberately throws if the value is null. Because most code uses non-null types, whole categories of NPEs simply cannot occur.
🌐
generalistprogrammer.com
generalistprogrammer.com › home › tutorials › programming › null pointer exception: the complete cross-language guide to fixing and preventing it (2026)
How to Fix a Null Pointer Exception (NPE): Complete Guide 2026
🌐
Medium
medium.com › @kiranbjm › what-is-a-null-pointer-exception-de351fb907e7
What is a Null Pointer Exception? | by Kiran Benny Joseph | Medium
October 26, 2024 - What is a Null Pointer Exception? A NullPointerException happens when your code tries to access properties, methods, or functions on a variable that hasn’t been assigned a reference in memory …
🌐
Dobegin
dobegin.com › npe-hell
Null pointer exceptions hell - do begin
Null pointer exception (NPE) is known by different names in different programming languages. Null pointer dereference in C/C++, NullPointerException in Java, NullReferenceException in C# and .NET, and many other names in scripting languages like JavaScript’s “undefined is not a function” among them.
🌐
Generalist Programmer
generalistprogrammer.com › home › tutorials › programming › null pointer exception: the complete cross-language guide to fixing and preventing it (2026)
How to Fix a Null Pointer Exception (NPE): Complete Guide 2026
June 17, 2026 - It happens when your code takes a reference that points to nothing — a null — and tries to use it as if it pointed to a real object: calling a method on it, reading a field, or indexing into it.
Find elsewhere
🌐
SayoNetech
sayonetech.com › home › blog › javascript errors: top 6 culprits & how to fix them
JavaScript Errors: Top 6 Culprits & How to Fix Them
August 10, 2025 - Read our blog: Checkout Python ... undefined," are common JavaScript errors that occur when a variable or object is accessed without a valid value assigned to it....
🌐
Airbrake
blog.airbrake.io › blog › javascript-error-handling › null-undefined-properties
JavaScript Error Handling - TypeError: null or undefined has no properties
July 13, 2022 - As we saw above, null is considered ... a nonexistent entity. Unlike every other object which might be defined, the JavaScript engine sees a null value and immediately treats it as a pointer to nothing....
🌐
Afine
afine.com › home › blog › null pointer exceptions: from java's pitfalls to kotlin's solutions
Null Pointer Exceptions: From Java’s Pitfalls to Kotlin’s Solutions
February 12, 2026 - If input is null (e.g., from a user form or HTTP request), calling .length() will throw an exception because there’s no actual string to operate on.
🌐
DEV Community
dev.to › mcsee › code-smell-304-null-pointer-exception-1meo
Code Smell 304 - Null Pointer Exception - DEV Community
June 18, 2025 - Null pointer exceptions happen when you try to access methods or properties on objects that don't exist. This happens when variables contain null references instead of valid object instances.
🌐
Hacker News
news.ycombinator.com › item
Typescript is GREAT. Strict null-checking eliminates the dreaded null-pointer ex... | Hacker News
April 16, 2017 - The way I look at Typescript vs. Javascript is that with Typescript, it's like having always having a pair programming buddy (the compiler) who never makes mistakes · When I was using typescript this still came up if you missed an array bounds check, you'd end up with an unexpected undefined.
🌐
Niksilver
niksilver.com › 2006 › 11 › 23 › javascript-puzzler-throw-null
Javascript puzzler: throw null – niksilver.com
November 23, 2006 - JsUnit’s mistake was to assume a null exception means no exception. Strict typing helps avoid problems that come about because we’re human and make mistakes. A wise man in ancient China once said “the compiler is your friend”. Javascript doesn’t have a compiler, and I can do with all the friends I can get.
🌐
OWASP Foundation
owasp.org › www-community › vulnerabilities › Catch_NullPointerException
Catch NullPointerException | OWASP Foundation
try { UserSession user = Server.Session.getUserLoginSession(); Server.sendText("Hello "+ user.getName()); } catch (NullPointerException npe) { Server.sendText("Please login"); }
🌐
EDUCBA
educba.com › home › software development › software development tutorials › java tutorial › java nullpointerexception
Java NullPointerException | How NullPointerException Works in Java?
April 4, 2023 - It is a runtime exception that occurs when the object instantiation is not proper. The object is declared as having a null value in it. The null pointer exception simply signifies that it is trying to call an object with a reference that has ...
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
Top answer
1 of 12
4227

There are two overarching types of variables in Java:

  1. Primitives: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type int or char are primitives.

  2. References: variables that contain the memory address of an Object i.e. variables that refer to an Object. If you want to manipulate the Object that a reference variable refers to you must dereference it. Dereferencing usually entails using . to access a method or field, or using [ to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of type Object are references.

Consider the following code where you declare a variable of primitive type int and don't initialize it:

Use with AIint x;
int y = x + x;

These two lines will crash the program because no value is specified for x and we are trying to use x's value to specify y. All primitives have to be initialized to a usable value before they are manipulated.

Now here is where things get interesting. Reference variables can be set to null which means "I am referencing nothing". You can get a null value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to null).

If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to dereference it you get a NullPointerException.

The NullPointerException (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist.

Take the following code:

Use with AIInteger num;
num = new Integer(10);

The first line declares a variable named num, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it to null.

In the second line, the new keyword is used to instantiate (or create) an object of type Integer, and the reference variable num is assigned to that Integer object.

If you attempt to dereference num before creating the object you get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized," but sometimes you may write code that does not directly create the object.

For instance, you may have a method as follows:

Use with AIpublic void doSomething(SomeObject obj) {
   // Do something to obj, assumes obj is not null
   obj.myMethod();
}

In which case, you are not creating the object obj, but rather assuming that it was created before the doSomething() method was called. Note, it is possible to call the method like this:

Use with AIdoSomething(null);

In which case, obj is null, and the statement obj.myMethod() will throw a NullPointerException.

If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException because it's a programmer error and the programmer will need that information for debugging purposes.

In addition to NullPointerExceptions thrown as a result of the method's logic, you can also check the method arguments for null values and throw NPEs explicitly by adding something like the following near the beginning of a method:

Use with AI// Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");

Note that it's helpful to say in your error message clearly which object cannot be null. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj is reassigned, it is not null and can be dereferenced safely.

Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething() could be written as:

Use with AI/**
  * @param obj An optional foo for ____. May be null, in which case
  *  the result will be ____.
  */
public void doSomething(SomeObject obj) {
    if(obj == null) {
       // Do something
    } else {
       // Do something else
    }
}

Finally, How to pinpoint the exception & cause using Stack Trace

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

Sonar with find bugs can detect NPE. Can sonar catch null pointer exceptions caused by JVM Dynamically

Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006.

In Java 14, the following is a sample NullPointerException Exception message:

in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null

List of situations that cause a NullPointerException to occur

Here are all the situations in which a NullPointerException occurs, that are directly* mentioned by the Java Language Specification:

  • Accessing (i.e. getting or setting) an instance field of a null reference. (static fields don't count!)
  • Calling an instance method of a null reference. (static methods don't count!)
  • throw null;
  • Accessing elements of a null array.
  • Synchronising on null - synchronized (someNullReference) { ... }
  • Any integer/floating point operator can throw a NullPointerException if one of its operands is a boxed null reference
  • An unboxing conversion throws a NullPointerException if the boxed value is null.
  • Calling super on a null reference throws a NullPointerException. If you are confused, this is talking about qualified superclass constructor invocations:
Use with AIclass Outer {
    class Inner {}
}
class ChildOfInner extends Outer.Inner {
    ChildOfInner(Outer o) { 
        o.super(); // if o is null, NPE gets thrown
    }
}
  • Using a for (element : iterable) loop to loop through a null collection/array.

  • switch (foo) { ... } (whether its an expression or statement) can throw a NullPointerException when foo is null.

  • foo.new SomeInnerClass() throws a NullPointerException when foo is null.

  • Method references of the form name1::name2 or primaryExpression::name throws a NullPointerException when evaluated when name1 or primaryExpression evaluates to null.

    a note from the JLS here says that, someInstance.someStaticMethod() doesn't throw an NPE, because someStaticMethod is static, but someInstance::someStaticMethod still throw an NPE!

* Note that the JLS probably also says a lot about NPEs indirectly.

2 of 12
972

NullPointerExceptions are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException. These are the most common, but other ways are listed on the NullPointerException javadoc page.

Probably the quickest example code I could come up with to illustrate a NullPointerException would be:

Use with AIpublic class Example {

    public static void main(String[] args) {
        Object obj = null;
        obj.hashCode();
    }

}

On the first line inside main, I'm explicitly setting the Object reference obj equal to null. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException because there is no code to execute in the location that the reference is pointing.

(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)

🌐
GitHub
github.com › angular › angular › issues › 19602
Live example is throwing a null pointer exception in javascript · Issue #19602 · angular/angular · GitHub
October 7, 2017 - I go to https://angular.io/generated/live-examples/toh-pt6/eplnkr.html for the live. I try to do anything and it is not responding. Also on load it throws a console log error. So this is to report two errors. I was just looking through the code and it looks like it is also supposed to be populated ...
Author: angular
🌐
Medium
medium.com › teamzerolabs › undefined-null-node-js-fast-prevention-a55c4b9c5717
How to reduce null-checks in JavaScript and Node.JS | by Jack Yeh | TeamZeroLabs | Medium
February 3, 2020 - console.log("Hello ", getDrName(doctors[3])); // doctors[3] is undefined./Users/jack/tzl_2020/playground/main.js:9 function getDrName({ firstName, lastName }) { ^TypeError: Cannot destructure property `firstName` of 'undefined' or 'null'. at getDrName (/Users/jack/tzl_2020/playground/main.js:9:19) at Object.<anonymous>…
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-lang-nullpointerexception
Java NullPointerException - Detect, Fix, and Best Practices | DigitalOcean
August 3, 2022 - Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.