12.8 — Null pointers
In the previous lesson ( 12.7 -- Introduction to pointers ), we covered the basics of pointers, which are objects that hold the address of another object. This address can be dereferenced using the dereference operator (*) to get the object at that address:
The above example prints:
In the prior lesson, we also noted that pointers do not need to point to anything. In this lesson, we’ll explore such pointers (and the various implications of pointing to nothing) further.
Besides a memory address, there is one additional value that a pointer can hold: a null value. A null value (often shortened to null ) is a special value that means something has no value. When a pointer is holding a null value, it means the pointer is not pointing at anything. Such a pointer is called a null pointer .
The easiest way to create a null pointer is to use value initialization:
Value initialize your pointers (to be null pointers) if you are not initializing them with the address of a valid object.
Because we can use assignment to change what a pointer is pointing at, a pointer that is initially set to null can later be changed to point at a valid object:
The nullptr keyword
Much like the keywords true and false represent Boolean literal values, the nullptr keyword represents a null pointer literal. We can use nullptr to explicitly initialize or assign a pointer a null value.
In the above example, we use assignment to set the value of ptr2 to nullptr , making ptr2 a null pointer.
Use nullptr when you need a null pointer literal for initialization, assignment, or passing a null pointer to a function.
Dereferencing a null pointer results in undefined behavior
Much like dereferencing a dangling (or wild) pointer leads to undefined behavior, dereferencing a null pointer also leads to undefined behavior. In most cases, it will crash your application.
The following program illustrates this, and will probably crash or terminate your application abnormally when you run it (go ahead, try it, you won’t harm your machine):
Conceptually, this makes sense. Dereferencing a pointer means “go to the address the pointer is pointing at and access the value there”. A null pointer holds a null value, which semantically means the pointer is not pointing at anything. So what value would it access?
Accidentally dereferencing null and dangling pointers is one of the most common mistakes C++ programmers make, and is probably the most common reason that C++ programs crash in practice.
Whenever you are using pointers, you’ll need to be extra careful that your code isn’t dereferencing null or dangling pointers, as this will cause undefined behavior (probably an application crash).
Checking for null pointers
Much like we can use a conditional to test Boolean values for true or false , we can use a conditional to test whether a pointer has value nullptr or not:
The above program prints:
In lesson 4.9 -- Boolean values , we noted that integral values will implicitly convert into Boolean values: an integral value of 0 converts to Boolean value false , and any other integral value converts to Boolean value true .
Similarly, pointers will also implicitly convert to Boolean values: a null pointer converts to Boolean value false , and a non-null pointer converts to Boolean value true . This allows us to skip explicitly testing for nullptr and just use the implicit conversion to Boolean to test whether a pointer is a null pointer. The following program is equivalent to the prior one:
Conditionals can only be used to differentiate null pointers from non-null pointers. There is no convenient way to determine whether a non-null pointer is pointing to a valid object or dangling (pointing to an invalid object).
Use nullptr to avoid dangling pointers
Above, we mentioned that dereferencing a pointer that is either null or dangling will result in undefined behavior. Therefore, we need to ensure our code does not do either of these things.
We can easily avoid dereferencing a null pointer by using a conditional to ensure a pointer is non-null before trying to dereference it:
But what about dangling pointers? Because there is no way to detect whether a pointer is dangling, we need to avoid having any dangling pointers in our program in the first place. We do that by ensuring that any pointer that is not pointing at a valid object is set to nullptr .
That way, before dereferencing a pointer, we only need to test whether it is null -- if it is non-null, we assume the pointer is not dangling.
A pointer should either hold the address of a valid object, or be set to nullptr. That way we only need to test pointers for null, and can assume any non-null pointer is valid.
Unfortunately, avoiding dangling pointers isn’t always easy: when an object is destroyed, any pointers to that object will be left dangling. Such pointers are not nulled automatically! It is the programmer’s responsibility to ensure that all pointers to an object that has just been destroyed are properly set to nullptr .
When an object is destroyed, any pointers to the destroyed object will be left dangling (they will not be automatically set to nullptr ). It is your responsibility to detect these cases and ensure those pointers are subsequently set to nullptr .
Legacy null pointer literals: 0 and NULL
In older code, you may see two other literal values used instead of nullptr .
The first is the literal 0 . In the context of a pointer, the literal 0 is specially defined to mean a null value, and is the only time you can assign an integral literal to a pointer.
As an aside…
On modern architectures, the address 0 is typically used to represent a null pointer. However, this value is not guaranteed by the C++ standard, and some architectures use other values. The literal 0 , when used in the context of a null pointer, will be translated into whatever address the architecture uses to represent a null pointer.
Additionally, there is a preprocessor macro named NULL (defined in the <cstddef> header). This macro is inherited from C, where it is commonly used to indicate a null pointer.
Both 0 and NULL should be avoided in modern C++ (use nullptr instead). We discuss why in lesson 12.11 -- Pass by address (part 2) .
Favor references over pointers whenever possible
Pointers and references both give us the ability to access some other object indirectly.
Pointers have the additional abilities of being able to change what they are pointing at, and to be pointed at null. However, these pointer abilities are also inherently dangerous: A null pointer runs the risk of being dereferenced, and the ability to change what a pointer is pointing at can make creating dangling pointers easier:
Since references can’t be bound to null, we don’t have to worry about null references. And because references must be bound to a valid object upon creation and then can not be reseated, dangling references are harder to create.
Because they are safer, references should be favored over pointers, unless the additional capabilities provided by pointers are required.
Favor references over pointers unless the additional capabilities provided by pointers are needed.
1a) Can we determine whether a pointer is a null pointer or not? If so, how?
Yes, we can use a conditional (if statement or conditional operator) on the pointer. A pointer will convert to Boolean false if it is a null pointer, and true otherwise.
1b) Can we determine whether a non-null pointer is valid or dangling? If so, how?
There is no easy way to determine this.
For each subitem, answer whether the action described will result in behavior that is: predictable, undefined, or possibly undefined. If the answer is “possibly undefined”, clarify when.
2a) Assigning a new address to a non-const pointer
2b) Assigning nullptr to a pointer
2c) Dereferencing a pointer to a valid object
2d) Dereferencing a dangling pointer
2e) Dereferencing a null pointer
2f) Dereferencing a non-null pointer
Possibly undefined, if the pointer is dangling.
Why should we set pointers that aren’t pointing to a valid object to ‘nullptr’?
We can not determine whether a non-null pointer is valid or dangling, and accessing a dangling pointer will result in undefined behavior. Therefore, we need to ensure that we do not have any dangling pointers in our program.
If we ensure all pointers are either pointing to valid objects or set to nullptr , then we can use a conditional to test for null to ensure we don’t dereference a null pointer, and assume all non-null pointers are pointing to valid objects.
Pointers in C / C++ [Full Course] – FREE
Null Pointer in C/C++
In this Lecture, we will discuss about Null Pointer in C++.
You can allocate memory on the heap using the new operator like this.
It will allocate the memory on the heap and returns a pointer pointing to that memory location. We can initialise our pointer with this value. Now, our pointer ptr points to a memory location on the heap, which contains the integer value. Afterward, we can access that value using the pointer, or we can also change the content of that value using the pointer like this.
After usage, we must delete the allocated memory on the heap. For that, we will use the delete operator to delete the memory like this.
After this line, the memory allocated in the heap will be deleted. However, the pointer ptr will still be pointing to that memory location, which is now an invalid memory location because the memory is already deallocated. So we need to make sure that after the delete operator, the pointer ptr must point to NULL. Like this,
Now pointer ptr is a NULL Pointer. If we don’t assign NULL t pointer, the pointer will be called a dangling pointer ptr. Now, if we try to access any value using this pointer, it can result in an undefined behavior, because pointer ptr is pointing to a memory location that is already deleted. Therefore, we must initialise the pointer to NULL after deleting the memory. The value of NULL is 0.
Also, while accessing the value using a pointer, we should always first check if the memory is valid or not. For that, we can pass the pointer in an if condition. Like this,
If the pointer is pointing to a NULL value, it means it’s not a valid value, and we can’t access the value. However, if the pointer contains the NULL, which is also equivalent to zero, this if condition will fail and will not go to this if block.
When we declare a pointer and don’t initialise it, the default value will be a garbage value. It means the pointer is pointing to some invalid memory location.
Now, if someone tried to access the value through this pointer, it can result in undefined behavior. Therefore, we should always initialise a pointer while declaring it. Either we need to initialise it with a valid address either on its stack or in heap, or if we plan to assign a valid point at a later stage, then we must initialise the pointer with NULL.
While accessing the value, we must check if the given pointer is valid or not like this, and then only should we access the value at that memory location pointed by this pointer.
If you try to delete a null pointer, then it can also result in undefined behaviour, if data type of Object is a User defained data type. Therefore, before deleting a pointer, we should always check if the pointer is valid or not using the if operator. If the pointer is valid or contains a valid memory location, it will return true, and we can delete the memory. However, if the pointer is a null pointer, then the if statement will return false, and we won’t delete the value.
The complete example is as follows,
In this lecture, we learned about Null Pointer in C and C++.
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
- Trending Categories
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
NULL pointer in C
A null pointer is a pointer which points nothing.
Some uses of the null pointer are:
a) To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet.
b) To pass a null pointer to a function argument when we don’t want to pass any valid memory address.
c) To check for null pointer before accessing any pointer variable. So that, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL.
Learning faster. Every day.
- Null Pointer Exception in C#
- Differentiate the NULL pointer with Void pointer in C language
- Calling class method through NULL class pointer in C++
- Null Pointer Exception in Java Programming
- Why is address zero used for the null pointer in C/C++?
- Calling a member function on a NULL object pointer in C++
- Why do we check for a NULL pointer before deleting in C/C++?
- Double Pointer (Pointer to Pointer) in C
- What should we assign to a C++ pointer: A Null or 0?
- Pointer Arithmetic in C/C++
- What is null pointer exception in Java and how to fix it?
- void pointer in C
- Function Pointer in C
- Explain the concept of pointer to pointer and void pointer in C language?
- How to define pointer to pointer in C language?
Kickstart Your Career
Get certified by completing the course
3 Major use of NULL Pointer in C Programming | What does actually NULL means?
- Updated: Mar 09, 2019
Understanding the NULL pointer is easy but not so if you are implementing in your code. At the end of this post, you will learn to avoid NULL pointer problems and handling them gracefully.
Following are the topics covered in this article.
Table of Contents
- What is a NULL?
What is a NULL Pointer?
Why do we need a null pointer.
- Best Practices to use NULL Pointer
- What is the use of NULL Pointer in C?
- Difference Between NULL and Void Pointer
- Usage of a NULL Pointer in Various Programming Languages
So let’s begin…
What is NULL?
It is a special marker or keyword which has no value.
Each programming language has its own nuance.
In most of the programming language including C, Java, typically, 0 (zero) is a NULL and predefined constant or Macro.
NULL is a value that is not a value. Confusing, right?
Here is a simple example to differentiate.
In C++ programming,
char *par = 123; is not valid and gives a compilation error. Compiler except passing a hexadecimal value to the pointer and we are passing integer value.
Whereas char *par = 0; is a valid statement. Here, 0 (zero) is a null in C++ programming. As null does not have any value, the compiler can not discriminate.
For this reason, C.A.R Hoare (inventor of Null) said that inventing the NULL pointer was his biggest mistake. We leave this here, as it is not the scope of this article.
Whenever you assign any data to the variable, it gets stored at a particular location in the physical memory. This memory location has unique address value in hexadecimal format (something like 0x006CoEEA8 ).
The variable that stores this memory address is called as a Pointer .
When you assign a NULL value to the pointer, it does not point to any of the memory locations. The null pointer is nothing but the pointer which points to nothing.
It is also called as a NULL macro .
Here is a simple C program to print the value of NULL macro.
We can use this NULL constant value to assign to any pointer so that it will not point to any of the memory locations.
Here is the simple syntax for declaring a NULL pointer.
Here, ptr is a NULL pointer.
We can also assign 0 directly to the pointer.
This is also a valid expression in C. But, it is a standard practice to use a NULL constant.
The NULL constant is defined in many of the header files in the C programming language; including, stdio.h stddef.h , stdlib.h , etc.
In C programming, usually, we add stdio.h in the program to use scanf() and printf() functions. So, you don’t need to add any extra header files.
Later in the code, you can assign any memory location to ptr pointer.
Whenever you declare a pointer in your program, it points to some random memory location. And when you try to retrieve the information at that location, you get some garbage values. Many time, you might have observed this.
Using this garbage value in the program or passing it to any function, your program may crash.
Here, NULL pointer comes handy.
I am describing the use of the NULL pointer in C programming by three different ways. Before that, let’s see the best practices to use NULL pointer in programming.
Best Practices for NULL Pointer Usage:
How to use a NULL pointer to avoid any errors in your programming?
- Make a habit of assigning the value to a pointer before using it. Don’t use pointer before initializing it.
- If you don’t have a valid memory address to store in a pointer variable, just initialize a pointer to NULL.
- Before using a pointer in any of your function code, check if it has not a NULL value.
What is the use of NULL Pointer in C?
Above all understanding, this is the first question you ask yourself about the NULL pointer. Here are some use cases of NULL pointer…
1. Avoid Crashing a Program:
If you pass any garbage value in your code or to the particular function, your program can crash. To avoid this, you can use NULL pointer.
Before using any pointer, compare it with NULL value and check.
In the above code, we are passing a pointer to fact() function. In fact() function, we are checking if the input pointer is NULL or not.
If the value of the pointer ptrA is not NULL, execute the function body.
Passing a NULL value to the function code without checking can terminate your program by crashing inside the function. So, it is one of the best use of NULL pointer in C.
2. While Freeing (de-allocating) Memory:
Suppose, you have a pointer which points to some memory location where data is stored. If you don’t need that data anymore, for sure, you want to delete that data and free the memory.
But even after freeing the data, pointer still points to the same memory location. This pointer is called as a dangling pointer . To avoid this dangling pointer, you can set the pointer to NULL.
Let’s check this below example to avoid dangling pointer in C.
Here, malloc() is an inbuilt function to create a dynamic memory.
What is the difference between NULL and Void Pointer?
Many of the programmer, especially beginners, get confused between NULL and void pointer.
The void is one of the data types in C. Whereas, NULL is the value which is assigned to the pointer.
The data type of the pointer is nothing but the type of data stored at the memory location where the pointer is pointed. When you are not sure about the type of data that is going to store at a particular memory location, you need to create the void pointer .
Below is an example for creating void pointer in C.
3. NULL pointer Uses in Linked List:
A NULL pointer is also useful in Linked List. We know that in Linked List, we point one node to its successor node using a pointer.
As there is no successor node to the last node, you need to assign a NULL value to the link of the last node. (As shown in above image.)
Check the implementation of Linked List in C to know how NULL pointer is used. I have described it in detail.
This is all about NULL pointer in C and CPP programming. The understanding of the NULL pointer is a concept. Like C programming, you can see the same use cases of NULL pointers in many other programming languages.
Usage of a NULL pointer in various Programming Languages?
Many of the programming languages use the NULL pointer concept. It is not necessary to have the same name for a NULL pointer, but the concept is almost the same in all the programming languages.
- In C, the NULL keyword is a predefined macro.
- In C++, the NULL is inherited from C programming.
- The latest development in C++11, there is an explicit pointer to handle the NULL exception, called null ptr constant.
- In Java programming , there is a null value. It indicates that no value is assigned to a reference variable.
- In some other programming language like Lips, it is called as nil vector .
Check out all the C and C++ programming questions . You will find NULL pointer and macro very useful.
This is all about NULL macro and use of NULL pointer in C programming. If you have any question, feel free to ask in a comment.
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on <b>CSEstack.org</b> portal.
Great Post. Agree with Mathew. Many people learn about NULL pointer but many few uses them in their project.
I think the NULL pointer is extremely useful to avoid the crash and for better programming.
You are absolutely right, Vatsal. Thanks for putting your thought.
I read about NULL pointer earlier, but this is very descriptive and you have mentioned very good use cases.
Great to see you here Mathew. I am glad you like it.
Very neatly explained. Thank you and keep up the good work. 🙂
Thanks Abha for putting your thought 🙂 It keeps motivating me to work hard.
output is 10. It still works. My program is not crashed.
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
Save my name, email, and website in this browser for the next time I comment.
- C- Introduction
- C- Compile & Execute Program
- C- Data Types
- C- if-else statement
- C- While, do-while, for loop
- C- Function (Types/Call)
- C- strlen() vs sizeof()
- C- Nested Switch Statement
- C- Recursion
- C- Dynamic Programming
- C- Storage Classes
- C- Creating Header File
- C- Null Pointer
- C- Stack and Queue
- C- Implement Stack using Array
- C- Implement Linked List in C
- C- File Handling
- C- Makefile Tutorial
Programming for Practice
- Online C/C++ Compiler
- Remove White Spaces from String
- Implement strstr Function in C
- Convert String to Int – atoi()
- Check if String is Palindrome
- Check if Two Strings are Anagram
- Split String in using strtok_r()
- Undefined reference to strrev
- Check if Array is Sorted
- Count Number of 1’s in Binary
- Reverse a Linked List Elements
- Program to Find 2’s Complement
- Convert Decimal to Binary in C
- Add Two Numbers without Operator
- Find Next Greater Number
- Swap values without temp variable
- Print 1 to 100 without Loop
Object Oriented Concepts in C++
- C++: C vs OOPs Language
- C++: Introduction to OOPs Concepts
- C++: Inheritance
Sign up on Python Hint
Join our community of friendly folks discovering and sharing the latest topics in tech.
We'll never post to any of your accounts without your permission.
How to assign a NULL value to a pointer in python?
on 9 months ago
Setting a NULL value to a pointer using None keyword
Assigning null value to a pointer during initialization, de-referencing a null pointer and handling the error, conclusion:, glob exclude pattern.
9 months ago
Beautifulsoup : Difference between .find() and .select()
What exactly does += do?
What is the purpose of Flask's context stacks?
How to *actually* read CSV data in TensorFlow?
How to get the Worksheet ID from a Google Spreadsheet with python?
Python setup.py: ask for configuration data during setup, how to make the shebang be able to choose the correct python interpreter between python3 and python3.5, how to pass const char* from python to c function, how to use plotly/dash (python) completely offline, python - matplotlib - how do i plot a plane from equation, in django/python, how do i set the memcache to infinite time, how do you reload a module in python version 3.3.2, python 3.4 - library for 2d graphics, failed to load the native tensorflow runtime. python 3.5.2, c++ vs python precision, how can i make my code more readable and dryer when working with xml namespaces in python, how to use python multiprocessing module in django view, calculating power for decimals in python, color logging using logging module in python, installation.
Copyright 2023 - Python Hint
Term of Service
- Hello World
- Taking Input from User
- Find ASCII Value of Character
- Using gets() function
- Switch Case
- Checking for Vowel
- Reversing Case of Character
- Swapping Two Numbers
- Largest and Smallest using Global Declaration
- Basic for Loop
- Basic while Loop
- Basic do-while Loop
- Nested for Loops
- Program to find Factorial of number
- Fibonacci Series Program
- Palindrome Program
- Program to find Sum of Digits
- Program to reverse a String
- Program to find Average of n Numbers
- Armstrong Number
- Checking input number for Odd or Even
- Print Factors of a Number
- Find sum of n Numbers
- Print first n Prime Numbers
- Find Largest among n Numbers
- Exponential without pow() method
- Find whether number is int or float
- Print Multiplication Table of input Number
- Reverse an Array
- Insert Element to Array
- Delete Element from Array
- Largest and Smallest Element in Array
- Sum of N Numbers using Arrays
- Sort Array Elements
- Remove Duplicate Elements
- Sparse Matrix
- Square Matrix
- Determinant of 2x2 matrix
- Normal and Trace of Square Matrix
- Addition and Subtraction of Matrices
- Matrix Mulitplication
- Simple Program
- Memory Management
- Array of Pointers
- Pointer Increment and Decrement
- Pointer Comparison
- Pointer to a Pointer
- Concatenate Strings using Pointer
- Reverse a String using Pointer
- Pointer to a Function
- Null Pointer
- isgraph() and isprint()
- Removing Whitespaces
- gets() and strlen()
- strlen() and sizeof()
- Frequency of characters in string
- Count Number of Vowels
- Adding Two Numbers
- Fibonacci Series
- Sum of First N Numbers
- Sum of Digits
- Largest Array Element
- Prime or Composite
- LCM of Two Numbers
- GCD of Two Numbers
- Reverse a String
Files and Streams
- List Files in Directory
- Size of File
- Write in File
- Reverse Content of File
- Copy File to Another File
- Largest of three numbers
- Second largest among three numbers
- Adding two numbers using pointers
- Sum of first and last digit
- Area and Circumference of Circle
- Area of Triangle
- Basic Arithmetic Operations
- Conversion between Number System
- Celsius to Fahrenheit
- Simple Interest
- Greatest Common Divisor(GCD)
- Roots of Quadratic Roots
- Identifying a Perfect Square
- Calculate nPr and nCr
- Windows Shutdown
- Without Main Function
- Menu Driven Program
- Changing Text Background Color
- Current Date and Time
Using Null Pointer Program
NULL is a macro in C, defined in the <stdio.h> header file, and it represent a null pointer constant. Conceptually, when a pointer has that Null value it is not pointing anywhere.
If you declare a pointer in C, and don't assign it a value, it will be assigned a garbage value by the C compiler, and that can lead to errors.
Void pointer is a specific pointer type. void * which is a pointer that points to some data location in storage, which doesn't have any specific type.
Don't confuse the void * pointer with a NULL pointer.
NULL pointer is a value whereas, Void pointer is a type.
Below is a program to define a NULL pointer.
Use Null Pointer to mark end of Pointer Array in C
Now let's see a program in which we will use the NULL pointer in a practical usecase.
We will create an array with string values ( char * ), and we will keep the last value of the array as NULL. We will also define a search() function to search for name in the array.
Inside the search() function, while searching for a value in the array, we will use NULL pointer to identify the end of the array.
So let's see the code,
Peter is in the list. Scarlett not found.
This is a simple program to give you an idea of how you can use the NULL pointer. But there is so much more that you can do. You can ask the user to input the names for the array. And then the user can also search for names. So you just have to customize the program a little to make it support user input.
- ← Prev
- Next →
c mcq tests.
- C++ Language
- Ascii Codes
- Boolean Operations
- Numerical Bases
Basics of c++.
- Structure of a program
- Variables and types
- Basic Input/Output
- Statements and flow control
- Overloads and templates
- Name visibility
Compound data types
- Character sequences
- Dynamic memory
- Data structures
- Other data types
- Classes (I)
- Classes (II)
- Special members
- Friendship and inheritance
Other language features
- Type conversions
- Preprocessor directives
- Input/output with files
Address-of operator (&)
Dereference operator (*)
- & is the address-of operator , and can be read simply as "address of"
- * is the dereference operator , and can be read as "value pointed to by"
Pointers and arrays, pointer initialization, pointer arithmetics.
Pointers and const
Pointers and string literals.
Pointers to pointers
- c is of type char** and a value of 8092
- *c is of type char* and a value of 7230
- **c is of type char and a value of 'z'
Invalid pointers and null pointers, pointers to functions.
- Design Pattern
- Interview Q
C Control Statements
C functions, c dynamic memory, c structure union, c file handling, c preprocessor, c command line, c programming test, c interview.
- Send your Feedback to [email protected]
Help Others, Please Share
Learn Latest Tutorials
Python Design Patterns
B.Tech / MCA
- 90% Refund @Courses
- Java Arrays
- Java Strings
- Java Collection
- Java 8 Tutorial
- Java Multithreading
- Java Exception Handling
- Java Programs
- Java Project
- Java Collections Interview
- Java Interview Questions
- Spring Boot
- Solve Coding Problems
- Java Tutorial
Overview of Java
- Introduction to Java
- The Complete History of Java Programming Language
- C++ vs Java vs Python
- How to Download and Install Java for 64 bit machine?
- Setting up the environment in Java
- How to Download and Install Eclipse on Windows?
- JDK in Java
- How JVM Works - JVM Architecture?
- Differences between JDK, JRE and JVM
- Just In Time Compiler
- Difference between JIT and JVM in Java
- Difference between Byte Code and Machine Code
- How is Java platform independent?
Basics of Java
- Java Basic Syntax
- Java Hello World Program
- Java Data Types
- Primitive data type vs. Object data type in Java with Examples
- Java Identifiers
Operators in Java
- Java Variables
- Scope of Variables In Java
Wrapper Classes in Java
Input/output in java.
- How to Take Input From User in Java?
- Scanner Class in Java
- Java.io.BufferedReader Class in Java
- Difference Between Scanner and BufferedReader Class in Java
- Ways to read input from console in Java
- System.out.println in Java
- Difference between print() and println() in Java
- Formatted Output in Java using printf()
- Fast I/O in Java in Competitive Programming
Flow Control in Java
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Java if statement with Examples
- Java if-else
- Java if-else-if ladder with Examples
- Loops in Java
- For Loop in Java
- Java while loop with Examples
- Java do-while loop with Examples
- For-each loop in Java
- Continue Statement in Java
- Break statement in Java
- Usage of Break keyword in Java
- return keyword in Java
- Java Arithmetic Operators with Examples
- Java Unary Operator with Examples
- Java Assignment Operators with Examples
- Java Relational Operators with Examples
- Java Logical Operators with Examples
- Java Ternary Operator with Examples
- Bitwise Operators in Java
- Strings in Java
- String class in Java
- Java.lang.String class in Java | Set 2
- Why Java Strings are Immutable?
- StringBuffer class in Java
- StringBuilder Class in Java with Examples
- String vs StringBuilder vs StringBuffer in Java
- StringTokenizer Class in Java
- StringTokenizer Methods in Java with Examples | Set 2
- StringJoiner Class in Java
- Arrays in Java
- Arrays class in Java
- Multidimensional Arrays in Java
- Different Ways To Declare And Initialize 2-D Array in Java
- Jagged Array in Java
- Final Arrays in Java
- Reflection Array Class in Java
- util.Arrays vs reflect.Array in Java with Examples
OOPS in Java
- Object Oriented Programming (OOPs) Concept in Java
- Why Java is not a purely Object-Oriented Language?
- Classes and Objects in Java
- Naming Conventions in Java
- Java Methods
Access Modifiers in Java
- Java Constructors
- Four Main Object Oriented Programming Concepts of Java
Inheritance in Java
Abstraction in java, encapsulation in java, polymorphism in java, interfaces in java.
- 'this' reference in Java
- Inheritance and Constructors in Java
- Java and Multiple Inheritance
- Interfaces and Inheritance in Java
- Association, Composition and Aggregation in Java
- Comparison of Inheritance in C++ and Java
- abstract keyword in java
- Abstract Class in Java
- Difference between Abstract Class and Interface in Java
- Control Abstraction in Java with Examples
- Difference Between Data Hiding and Abstraction in Java
- Difference between Abstraction and Encapsulation in Java with Examples
- Difference between Inheritance and Polymorphism
- Dynamic Method Dispatch or Runtime Polymorphism in Java
- Difference between Compile-time and Run-time Polymorphism in Java
Constructors in Java
- Copy Constructor in Java
- Constructor Overloading in Java
- Constructor Chaining In Java with Examples
- Private Constructors and Singleton Classes in Java
Methods in Java
- Static methods vs Instance methods in Java
- Abstract Method in Java with Examples
- Overriding in Java
- Method Overloading in Java
- Difference Between Method Overloading and Method Overriding in Java
- Differences between Interface and Class in Java
- Functional Interfaces in Java
- Nested Interface in Java
- Marker interface in Java
- Comparator Interface in Java with Examples
- Need of Wrapper Classes in Java
- Different Ways to Create the Instances of Wrapper Classes in Java
- Character Class in Java
- Java.Lang.Byte class in Java
- Java.Lang.Short class in Java
- Java.lang.Integer class in Java
- Java.Lang.Long class in Java
- Java.Lang.Float class in Java
- Java.Lang.Double Class in Java
- Java.lang.Boolean Class in Java
- Autoboxing and Unboxing in Java
- Type conversion in Java with Examples
Keywords in Java
- Java Keywords
- Important Keywords in Java
- Super Keyword in Java
- final Keyword in Java
- static Keyword in Java
- enum in Java
- transient keyword in Java
- volatile Keyword in Java
- final, finally and finalize in Java
- Public vs Protected vs Package vs Private Access Modifier in Java
- Access and Non Access Modifiers in Java
Memory Allocation in Java
- Java Memory Management
- How are Java objects stored in memory?
- Stack vs Heap Memory Allocation
- How many types of memory areas are allocated by JVM?
- Garbage Collection in Java
- Types of JVM Garbage Collectors in Java with implementation details
- Memory leaks in Java
- Java Virtual Machine (JVM) Stack Area
Classes of Java
- Understanding Classes and Objects in Java
- Singleton Method Design Pattern in Java
- Object Class in Java
- Inner Class in Java
- Throwable Class in Java with Examples
Packages in Java
- Packages In Java
- How to Create a Package in Java?
- Java.util Package in Java
- Java.lang package in Java
- Java.io Package in Java
- Java Collection Tutorial
Exception Handling in Java
- Exceptions in Java
- Types of Exception in Java with Examples
- Checked vs Unchecked Exceptions in Java
- Java Try Catch Block
- Flow control in try catch finally in Java
- throw and throws in Java
- User-defined Custom Exception in Java
- Chained Exceptions in Java
Null Pointer Exception In Java
- Exception Handling with Method Overriding in Java
- Multithreading in Java
- Lifecycle and States of a Thread in Java
- Java Thread Priority in Multithreading
- Main thread in Java
- Java.lang.Thread Class in Java
- Runnable interface in Java
- Naming a thread and fetching name of current thread in Java
- What does start() function do in multithreading in Java?
- Difference between Thread.start() and Thread.run() in Java
- Thread.sleep() Method in Java With Examples
- Synchronization in Java
- Importance of Thread Synchronization in Java
- Method and Block Synchronization in Java
- Lock framework vs Thread synchronization in Java
- Difference Between Atomic, Volatile and Synchronized in Java
- Deadlock in Java Multithreading
- Deadlock Prevention And Avoidance
- Difference Between Lock and Monitor in Java Concurrency
- Reentrant Lock in Java
File Handling in Java
- Java.io.File Class in Java
- Java Program to Create a New File
- Different ways of Reading a text file in Java
- Java Program to Write into a File
- Delete a File Using Java
- File Permissions in Java
- FileWriter Class in Java
- Java.io.FileDescriptor in Java
- Java.io.RandomAccessFile Class Method | Set 1
- Regular Expressions in Java
- Regex Tutorial - How to write Regular Expressions?
- Matcher pattern() method in Java with Examples
- Pattern pattern() method in Java with Examples
- Quantifiers in Java
- java.lang.Character class methods | Set 1
- Java IO : Input-output in Java with Examples
- Java.io.Reader class in Java
- Java.io.Writer Class in Java
- Java.io.FileInputStream Class in Java
- FileOutputStream in Java
- Java.io.BufferedOutputStream class in Java
- Java Networking
- TCP/IP Model
- User Datagram Protocol (UDP)
- Differences between IPv4 and IPv6
- Difference between Connection-oriented and Connection-less Services
- Socket Programming in Java
- java.net.ServerSocket Class in Java
- URL Class in Java with Examples
JDBC - Java Database Connectivity
- Introduction to JDBC (Java Database Connectivity)
- JDBC Drivers
- Establishing JDBC Connection in Java
- Types of Statements in JDBC
- JDBC Tutorial
NullPointerException is a RuntimeException. In Java , a special null value can be assigned to an object reference. NullPointerException is thrown when a program attempts to use an object reference that has the null value.
Reason for Null Pointer Exception
These are certain reasons for Null Pointer Exception as mentioned below:
- Invoking a method from a null object.
- Accessing or modifying a null object’s field.
- Taking the length of null, as if it were an array.
- Accessing or modifying the slots of null objects, as if it were an array.
- Throwing null, as if it were a Throwable value.
- When you try to synchronize over a null object.
Why do we need the Null Value?
Null is a special value used in Java. It is mainly used to indicate that no value is assigned to a reference variable. One application of null is in implementing data structures like linked lists and trees. Other applications include the Null Object pattern (See this for details) and the Singleton pattern . The Singleton pattern ensures that only one instance of a class is created and also, aims for providing a global point of access to the object.
A simple way to create at most one instance of a class is to declare all its constructors as private and then, create a public method that returns the unique instance of the class:
In above example, a static instance of the singleton class. That instance is initialized at most once inside the Singleton getInstance method.
How to Avoid the NullPointerException?
To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects. Following are the common problems with the solution to overcome that problem.
Case 1 : String comparison with literals
A very common case problem involves the comparison between a String variable and a literal. The literal may be a String or an element of an Enum. Instead of invoking the method from the null object, consider invoking it from the literal.
Below is the Example of the Case 1:
We can avoid NullPointerException by calling equals on literal rather than object.
Case 2 : Keeping a Check on the arguments of a method
Before executing the body of your new method, we should first check its arguments for null values and continue with execution of the method, only when the arguments are properly checked. Otherwise, it will throw an IllegalArgumentException and notify the calling method that something is wrong with the passed arguments.
Below is the Example of the Case 2:
Case 3 : Use of Ternary Operator
The ternary operator can be used to avoid NullPointerException. First, the Boolean expression is evaluated. If the expression is true then, the value1 is returned, otherwise, the value2 is returned. We can use the ternary operator for handling null pointers:
The message variable will be empty if str’s reference is null as in case
- Otherwise, if str point to actual data , the message will retrieve the first 6 characters of it as in case
- Related Article – Interesting facts about Null in Java
Frequently Asked Questions
1. what is nullpointerexception in java.
NullPointerException in Java is a type RuntimeException.
2. Why Null Pointer Exception Occurs?
NullPointerException occurs when one tries to access or manipulate object reference that has a Null value stored in it.
3. How to handle a Null Pointer Exception in Java?
There are certain methods to handle Null Pointer Exception in Java are mentioned below: String comparison with literals Keeping a Check on the arguments of a method Use of Ternary Operator
4. Reason for Null Pointer Exception.
NullPointerException is thrown when a program attempts to use an object reference that has the null value.
Please Login to comment...
- Exception Handling
- Technical Scripter