Handling Null Values/Exceptions
The NullPointerException is a problem that the majority of Java developers have encountered. When a variable is declared but no object is assigned to it before attempting to use the contents of the variable, the NullPointerException is thrown. Making a catchphrase for NullPointerException rather than providing code to manage the underlying null pointer dereferences is a common error. When programs handle null pointer dereferences rather than catching or suppressing NullPointerExceptions, it can be very challenging to pinpoint which expression is responsible for the exception in the try block or is adding unnecessary performance impact. Although there are other approaches to dealing with null values, there are two that work well when dealing with a String argument.
Checking to see if the String Argument is Null:
Java
boolean isNoun(String noun) { if (noun == null ) { return false ; } String nouns[] = noun.split( " " ); if (nouns.length != 2 ) { return false ; } return (isCapitalized(nouns[ 0 ]) && isCapitalized(nouns[ 1 ])); } |
Throw the NullPointerException on purpose rather than performing an explicit check:
Java
boolean isNoun(String noun) Throws NullPointerException { if (noun == null ) { return false ; } String nouns[] = noun.split( " " ); if (nouns.length != 2 ) { return false ; } return (isCapitalized(nouns[ 0 ]) && isCapitalized(nouns[ 1 ])); } |
To explore other methods, refer to the following articles
10 Most Common Mistakes That Java Developers Make
If you’re working on any new programming language, there might be certain phases where you can get stuck. This eventually leads any developer to make minor-major errors and creates a roadblock towards their learning curve. Not to forget, as much as you’ll be making mistakes, you’ll achieve excellence. Besides this, learning Java is no different task and thus it can also be excelled with time and with the right resources (tutorials, courses, books, etc) but the path towards becoming an expert is not as simple as it sounds, you need to ensure that you’re avoiding all the “Basic” mistakes that most developers do when they’re at “Beginner” level.
No matter how better a programmer you are, it is always necessary to make some mistakes, and the best part is it’s good to be informed about the blunders that you’re doing and avoid making such errors while coding. That’s why we came up with this article to highlight the 10 most common mistakes that every developer makes during their coding life and it might give you some clarity on how to avoid those mistakes. So, let’s check them out one-by-one.
Contact Us