Introduction to Comparing Strings: Android Studio Crash Course (Free Tutorial)

If there’s one thing you should learn about coding, it’s how to compare strings. Strings are pretty important because they’re the messages that get displayed on computer screens. With this article, you’ll learn how to use Android Studio to determine whether or not certain strings are equal.

If you want to learn the basics of coding for FREE, check out our 30-minute introductory course here: training.mammothinteractive.com/p/learn-to-code-in-30-minutes

To follow along with this example in Android Studio, go into Project view. Then go to app > java > (topmost) com.example.zebra.demo > MainActivity. Feel free to hide Project view.

First off, let’s declare 2 strings, car1 and car2, and name them “Toyota” and “Honda”. As well, we want to specify that there’s a message we want to be displayed on the screen. To do so, add the following code beneath setContentView(R.layout.activity_main);:

String car1 = "Toyota", car2 = "Honda", message;

Right away, create If/Else Statements:

if(){

}
else{

}

In order to compare two strings, we have to use a method called “equals”. Type the following into the parentheses of your If Statement: car1.equals(). In the parentheses of THIS code, write car2 as a parameter.

If the two strings are equal (in other words, contain the same values), let’s have the message “Strings are EQUAL.” appear on the screen. The code of your If Statement should look like this:

if(){
message = "Numbers are EQUAL.";
}

If the numbers AREN’T equal, let’s have the message “Strings are NOT EQUAL.” show up by coding that in our Else Statement.

In order for the message to display on the screen, below your Else Statement, type in “Toast”, select “Create a new Toast”, and hit Enter. Android Studio will auto-complete the following code:

Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();

Replace the double quotation marks with message. The screen will display the content in message.

If you run the emulator and zoom in, you will see “Strings are NOT EQUAL.” appear on the screen because “Toyota” isn’t the same as “Honda”. To see the message “Strings are EQUAL.” give car1 and car2 the same value.

Well done! You now know how to compare strings in Android Studio. If you want to learn even more coding for FREE, check out our 30-minute beginners course here: training.mammothinteractive.com/p/learn-to-code-in-30-minutes

Mammoth Interactive Favicon

Why you NEED to take this course :

Get in Touch.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

EMAIL US

support@mammothinteractive.com