Sunday, October 28, 2018

String notEquals java

There are many articles and examples about String equals() method and why not to use == for String comparison. While searching in google I find lot of questions about String notEquals() and how to find if a string notEquals another String. For Java programmers who have intermediate knowledge, this will be not much useful as they are aware of the concept of negation but I am writing this article to help beginners to understand the concept of notEquals while comparing Strings in their code.

Do we have notEquals() method in String API?


Unfortunately the answer is 'No' but we can achieve it with negating equals() method.
The following example will demonstrate this concept.

notEquals using Java String API



public class StringNotEquals {
	
	public static void main(String[] args) {
		
		String stringOne = "January";
		String stringTwo = "March";
		
		if(!stringOne.equals(stringTwo)){
			System.out.printf("%s not equals to %s",stringOne, stringTwo);
		}
		else{
			System.out.printf("%s equals to %s",stringOne, stringTwo);
		}
		
	}

}

Output: January not equals to March

No comments:

Post a Comment