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

Welcome to a key concept in Android Studio: comparing integers. No matter what coding language you’re using, integers are one of the most common ways to represent a number. 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

We are going to compare integers in order to determine whether or not they’re equal. To follow along with this example in Android Studio, go into Project view. Then go to app > java > (topmost) com.example.zebra.demo > MainActivity.

Beneath setContentView(R.layout.activity_main);, declare integers number1 and number2, and assign them the values 9 and -18:

int number1 = 9, number2 = -18;

Create If/Else Statements:

if(){

}
else{

}

Next, we have to create a message that will be displayed on the screen. First, initialize an empty string in case the emulator doesn’t run the If/Else Statements.

String message = "";

Because we’re comparing numbers 1 and 2 for equality, type the following into the parentheses of your If Statement: number1 == number2.

As you may have learned from our article on Boolean Variables, one equals sign assigns a value to a variable. A double equals sign compares two numbers and checks whether or not they’re equal.

As part of our If Statement, let’s have the message “Numbers are EQUAL.” display on the screen.

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

On the other hand, if the numbers aren’t equal, let’s have the message “Numbers are NOT EQUAL.” show up by adding that in the Else Statement. Note that all of your statements must end in semi-colons.

Furthermore, we have to create a Toast message 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.

By running the emulator and zooming in, you will see the string “Numbers are NOT EQUAL.” appear on the screen because 9 doesn’t equal -18. To see the message “Numbers are EQUAL.” set numbers 1 and 2 to the same value.

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