Main Tutorials

Constant value should always come first in comparison

Normal practice

Constant value comes second in comparison.


        private static final String COMPARE_VALUE = "VALUE123";
	
	public boolean compareIt(String input){
		
		if(input.equals(COMPARE_VALUE)){
			return true;
		}else{
			return false;
		}
	}

Problem

This is fine to compare a constant value with the above method, however it will potentially causing a NullPointerException, if user pass a “null” value for the comparison. For example :


if(input.equals(COMPARE_VALUE)) //hit NullPointerException if input is "null"

Best practice

Constant value should always come first in comparison.


        private static final String COMPARE_VALUE = "VALUE123";
	
	public boolean compareIt(String input){
		
		if(COMPARE_VALUE.equals(input)){
			return true;
		}else{
			return false;
		}
	}

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Arne Lewinski
8 years ago

Sorry but I cannot agree on that issue. If you use the constant first you support structures that veil programming errors. And one should only produce code either to add functionality, fix an programming error or trying to support structures to avoid programming errors (like design patterns). On top you have a weak assertion about the variable. So following code is always forced to check for null values as well. If you have to deal with null values from other modules your task is to map them into proper representations in your domain model as early as possible. In your own code avoid null as parameter or return value, so there won’t be any null-checks neccessary anymore, the suggested piece of code included. You see, this subject is more about avoiding null than accepting it to conquer your code.

Matt
1 year ago
Reply to  Arne Lewinski

Strongly agree.

Camilo
11 years ago

If user pass a “null” value for the comparison there will be a null pointer exception inside the String#equals method when the constant is set first. There might be another good reason for that pattern since I have seen it in many projects.