July 22, 2018
How do I compare strings in java
Introduction
Comparing strings is a very common task in coding. How do we do that in Java ? well there are tons of content in that regard. I compiled the bare minimum that you need in case you are only looking for the syntax.
Take a look…
Syntax Summary
Comparison type | Syntax | Explanation |
---|---|---|
Reference equality | Use == | Check if they are the same object or not ? |
Value equality | Use .equals() | Do they have the same value |
Lexicographic equality | Use compareTo | A is less than B and so on |
Let us demonstrate that…
Source code
The following code snippet uses JUnit framework to perform various types of string comparison…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
//Import needed stuff import org.junit.*; import static org.junit.Assert.*; import java.util.*; //Testing class public class Testing { //Constructor public Testing() { System.out.println("In constructor"); } //This method is invoked before //JUnite test case executes @ Before public void setUp() { System.out.println("In setUp"); } //This method is invoked after //JUnit test case is executed @ After public void tearDown() { System.out.println("In tearDown"); } //Test 1 @Test public void testValueEquality() { //Value checking assertTrue(new String("Cisco").equals("Cisco")); //Value checking different syntax assertTrue(Objects.equals(new String("Cisco"), "Cisco")); //Value checking against a null assertFalse(Objects.equals(null, "Cisco")); } //Test 2 @Test public void testObjectEquality() { //Same value but not same objects assertFalse(new String("Cisco") == "Cisco"); //Same value but not same objects assertFalse(new String("Cisco") == new String("Cisco")); //In this case they are internally the same object assertTrue("Cisco" == "Cisco"); } //Test 3 @Test public void testAlphabeticalOrder() { //Lexographic comparison assertTrue(new String("Cisco").compareTo("Apple") > 0); assertTrue(new String("Apple").compareTo("Cisco") < 0); assertTrue(new String("Cisco").compareTo("Cisco") == 0); } } |
Example Output
Compile the code and run the tests as follows…
1 2 |
javac -cp junit-4.12.jar Testing.java java -cp .:junit-4.12.jar:hamcrest-core-1.3.jar org.junit.runner.JUnitCore Testing |
The output should look like…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Testing JUnit version 4.12 In constructor .In setUp In tearDown In constructor .In setUp In tearDown In constructor .In setUp In tearDown Time: 0.006 OK (3 tests) |
You can download the source code from here. That is all for today.
Thanks for visiting. For questions and feedback, please use the comments section below