Member-only story
Java common mistake for beginners
Hi, Java beginner! Welcome to the world of programming, where endless possibilities await you. However, as a newbie, you may come across some common mistakes. Don’t worry! In this article, I will share with you some easy mistakes and give the right cases. Let’s get started!
Null pointer exception of reference type
A null pointer exception is one of the most common exceptions in Java programming. It is usually caused by an attempt to call a method or access a field on a null reference variable. Here is an example of an error that produces a null pointer exception:
String name = null;
System.out.println(name.length());
In the above example, we try to get the length of a null reference variable name
, which results in a null pointer exception. To avoid this error, we should do a null reference check before using the reference type, for example:
String name = null;
if (name != null) {
System.out.println(name.length());
} else {
System.out.println("name is null");
}
In this way, we check whether the length
property of name
is null before accessing it. If it is null, we can take appropriate measures to avoid null pointer exceptions.