Null Pointer Exception When Reading File Java
Table of Contents
- Reasons for NullPointerException
- 1. Invoking the case method of a null object
- 2. Accessing or modifying the field of a null object.
- three. Taking the length of null every bit if it were an array.
- 4. Accessing or modifying the slots of null as if information technology were an array.
- 5. Throwing zero as if information technology were a Throwable value.
- 6. When yous add aught to Collections which do not allow nulls such as ConcurrentHashMap
- vii. Trying to synchronize using nix object.
- Detection of NullPointerException
- Prepare NullPointerException
- one. Null bank check
- 2. Do null bank check as well before putting key or value in Collection which do non let null
- Best practices for avoiding NullPointerException
- 1. Cord comparing
- two. Employ Optional
- 3. Use ternary opertor
- 4. Go along check on arguments of method
- 5. Use StringUtils from Apache Common
In this tutorial, we will see the most frequent java exception i.e. Exception in thread main java.lang.NullPointerException. It is one of the Runtime Exception.
Heighten your manus if yous ever got NullPointerException while working on java lawmaking. I am certain that this is the exception you might accept encountered most oft. You might likewise agree that NullPointerException is hurting for nigh of coffee developers(novice or expert), but there is not much nosotros can practice almost them, because this is the price we need to pay for convenient or unavoidable cypher references.
Reasons for NullPointerException
Reasons for NullPointerException equally defined by Java docs.
- Invoking the instance method of a null object.
- Accessing or modifying the field of a nix object.
- Taking the length of null as if it were an assortment.
- Accessing or modifying the slots of zilch as if it were an array.
- Throwing nix as if it were a Throwable value.
- When yous add null to Collections which do not allow nulls such every bit [ConcurrentHashMap](https://java2blog.com/concurrenthashmap-in-java/ "ConcurrentHashMap")
- Trying to synchronize using goose egg object.
Let's sympathize each of these in item. I am creating a Employee class which nosotros are going to use in our examples.
| i 2 3 4 v 6 vii 8 nine 10 11 12 thirteen xiv 15 xvi 17 eighteen nineteen xx 21 22 23 24 25 26 27 28 29 30 31 | package org . arpit . java2blog ; public grade Employee { Cord proper noun ; int historic period ; public Employee ( ) { } public Employee ( String name , int age ) { this . name = name ; this . age = age ; } public String getName ( ) { return name ; } public void setName ( Cord name ) { this . proper name = name ; } public int getAge ( ) { return age ; } public void setAge ( int age ) { this . age = age ; } } |
1. Invoking the example method of a nada object
This is most obvious one.
| package org . arpit . java2blog ; public class InvokingMethodOnNullMain { public static void main ( String [ ] args ) { Employee e1 = cipher ; String proper name = e1 . getName ( ) ; System . out . println ( "Employee Proper noun: " + proper name ) ; } } |
When you lot run above program, y'all will get below output.
Exception in thread "chief" java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:7)
As you tin can come across, e1 is null at line 7 and nosotros are calling getMethod on it, thats why we are getting Exception in thread " main java.lang.NullPointerException here.
two. Accessing or modifying the field of a nada object.
It is very much similar to calling instance method on cypher.
| package org . arpit . java2blog ; public class NullFieldExampleMain { public static void chief ( String [ ] args ) { Employee e1 = null ; String proper noun = e1 . name ; System . out . println ( "Employee Proper noun: " + name ) ; } } |
When you lot run to a higher place programme, you will get below output.
Exception in thread "master" java.lang.NullPointerException
at org.arpit.java2blog.NullFieldExampleMain.master(InvokingMethodOnNullMain.java:8)
As you can see, e1 is null at line eight and we are accessing name field of e1, thats why we are getting NullPointerException hither.
three. Taking the length of null as if it were an array.
When you try to get length of null array, you will get NullPointerException.
| package org . arpit . java2blog ; public class NullArrayLengthMain { public static void main ( String [ ] args ) { Employee [ ] arrEmp = null ; int length = arrEmp . length ; System . out . println ( "Length of assortment: " + length ) ; } } |
When you run higher up programme, yous will get below output.
Exception in thread "main" java.lang.NullPointerException
at org.arpit.java2blog.NullArrayLengthMain.chief(InvokingMethodOnNullMain.java:9)
4. Accessing or modifying the slots of null as if it were an assortment.
When y'all try to access or modify null slot in array.Allow's understand with the aid of example.
| package org . arpit . java2blog ; public class InvokingMethodOnNullMain { public static void main ( Cord [ ] args ) { Employee [ ] arrEmp = nil ; System . out . println ( arrEmp [ 3 ] ) ; } } |
When you lot run above program, you will get beneath output.
Exception in thread "main" java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.chief(InvokingMethodOnNullMain.java:8)
v. Throwing null as if it were a Throwable value.
When you lot throw zip as Throwable.
| package org . arpit . java2blog ; public class InvokingMethodOnNullMain { public static void chief ( Cord [ ] args ) { throw aught ; } } |
When you run in a higher place program, you lot volition go below output.
Exception in thread "main" java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:7)
six. When yous add goose egg to Collections which do not allow nulls such equally ConcurrentHashMap
| package org . arpit . java2blog ; import java . util . concurrent . ConcurrentHashMap ; public class InvokingMethodOnNullMain { public static void main ( String [ ] args ) { ConcurrentHashMap < String , Cord > map = new ConcurrentHashMap <> ( ) ; map . put ( null , "Dummy" ) ; } } |
When you run above programme, you will get below output.
Exception in thread "chief" java.lang.NullPointerException
at coffee.base/coffee.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1022)
at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.coffee:1017)
at org.arpit.java2blog.InvokingMethodOnNullMain.primary(InvokingMethodOnNullMain.java:10)
7. Trying to synchronize using null object.
When y'all synchronize on zippo object, you will go NullPointerException
| bundle org . arpit . java2blog ; import java . util . concurrent . ConcurrentHashMap ; public grade InvokingMethodOnNullMain { public static void principal ( String [ ] args ) { Object obj = zip ; synchronized ( obj ) { ConcurrentHashMap < String , String > map = new ConcurrentHashMap <> ( ) ; map . put ( "Dummy" , "value" ) ; } } } |
When you run higher up program, you volition get below output.
Exception in thread "main" java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.primary(InvokingMethodOnNullMain.java:10)
Detection of NullPointerException
It is easier to observe NullPointerException. Bank check exception trace, it volition tell y'all class name, method name and line number.Become to that line number and bank check what can be the reason for NullPointerException.
Fix NullPointerException
Permit's take above scenrios and fix NullPointerException.
1. Null check
bank check null before calling method or field.
| package org . arpit . java2blog ; public class InvokingMethodOnNullMain { public static void main ( String [ ] args ) { Employee e1 = aught ; if ( e1 != null ) { Cord name = e1 . getName ( ) ; Arrangement . out . println ( "Employee Proper noun: " + proper name ) ; } } } |
When yous run above program, you won't become NullPointerExcpetion.
ii. Do null check every bit well before putting primal or value in Drove which exercise not let nothing
Best practices for avoiding NullPointerException
one. Cord comparison
This is almost frequent reason for Exception in thread main coffee.lang.NullPointerException, let's sympathise with the help of example.
| package org . arpit . java2blog ; public class StringComparisonMain { public static void primary ( String [ ] args ) { Employee e1 = new Employee ( ) ; if ( e1 . getName ( ) . equalsIgnoreCase ( "John" ) ) { Organisation . out . println ( "Employee Proper name is John" ) ; } } } |
Equally nosotros did not gear up name of Employee e1, we will get NullPointerException here.
When yous run above program, yous will get beneath output.
Exception in thread "chief" java.lang.NullPointerException
at org.arpit.java2blog.StringComparisonMain.primary(StringComparisonMain.java:viii)
You can change logic as below.
| package org . arpit . java2blog ; public form StringComparisonMain { public static void main ( Cord [ ] args ) { Employee e1 = new Employee ( ) ; if ( "John" . equalsIgnoreCase ( e1 . getName ( ) ) ) { System . out . println ( "Employee Proper name is John" ) ; } } } |
This volition avoid Exception in thread main java.lang.NullPointerException.
Please note that it may cause unexpected beliefs due to null. If proper noun cannot be zippo at all for Employee, and then don't use in a higher place method as it will ignore null names in this case.
ii. Apply Optional
Java 8 has introduced a new form chosen Optional.In general, we do not observe any value in method, we return null from it and it becomes hurting for caller to check for null to employ information technology.
For case:
| public static Employee findEmployee ( List < Employee employeeList , String name ) { for ( Employee eastward : employeeList ) { if ( e . getName ( ) . equalsIgnoreCase ( proper noun ) ) { render e ; } } return null ; } |
Every bit y'all can encounter, if we did not find employee in employeeList, nosotros are returning nothing from findEmployee() method. The caller will become employee object from findEmployee() method and may call getName() method which volition in plough raise NullPointerException.You tin apply Optional to avoid such situations.
| 1 2 3 iv 5 6 7 8 ix 10 11 12 xiii xiv 15 xvi 17 18 19 xx 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 xl 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | package org . arpit . java2blog ; import java . util . ArrayList ; import java . util . List ; import java . util . Optional ; public grade JavaOptionalMain { public static void main ( String [ ] args ) { Listing < Employee > employeeList = createEmployeeList ( ) ; Optional < Employee > employeeOpt = findEmployee ( employeeList , "John" ) ; if ( employeeOpt . isPresent ( ) ) { Employee employee = employeeOpt . go ( ) ; System . out . println ( "Employee name: " + employee . getName ( ) ) ; } else { Arrangement . out . println ( "There is no employee with name John" ) ; } } public static Optional < Employee > findEmployee ( List < Employee > employeeList , Cord proper name ) { for ( Employee e : employeeList ) { if ( eastward . getName ( ) . equalsIgnoreCase ( proper name ) ) { render Optional . of ( e ) ; } } return Optional . empty ( ) ; } public static Listing < Employee > createEmployeeList ( ) { List < Employee > employeeList = new ArrayList <> ( ) ; Employee e1 = new Employee ( "Adam" , 23 ) ; Employee e2 = new Employee ( "Dave" , 34 ) ; Employee e3 = new Employee ( "Carl" , 45 ) ; Employee e4 = new Employee ( "Mohan" , 29 ) ; Employee e5 = new Employee ( "Paresh" , 30 ) ; employeeList . add ( e1 ) ; employeeList . add together ( e2 ) ; employeeList . add ( e3 ) ; employeeList . add ( e4 ) ; employeeList . add ( e5 ) ; return employeeList ; } } |
There is no employee with name John
Information technology gives indication to caller than returned value can be null.
3. Use ternary opertor
You can employ ternary operation to check for null.
| package org . arpit . java2blog ; public grade InvokingMethodOnNullMain { public static void main ( String [ ] args ) { Employee e1 = null ; Cord name = e1 == null ? e1 . getName ( ) : "" ; System . out . println ( "Employee Name: " + name ) ; } } |
As you can see, we won't become NullPointerException hither.
4. Keep check on arguments of method
| 1 2 3 iv 5 6 seven 8 nine ten 11 12 13 fourteen 15 xvi 17 xviii 19 xx 21 22 23 | package org . arpit . java2blog ; public class InvokingMethodOnNullMain { public static void master ( String [ ] args ) { String str = null ; int len = getLength ( str ) ; Organisation . out . println ( "Length of String:" + len ) ; } public static int getLength ( String str ) { if ( str != zero ) { return str . length ( ) ; } else { return 0 ; } } } |
5. Utilize StringUtils from Apache Common
You can use StringUtils class to take care of lots of String nix and empty Cord check. Sometimes you need to cheque if String is null or empty, you can utilise isEmpty method from StringUtils to take care of information technology.
That's all about Exception in thread "main" java.lang.NullPointerException in coffee.
Source: https://java2blog.com/exception-thread-main-java-lang-nullpointerexception/
0 Response to "Null Pointer Exception When Reading File Java"
Post a Comment