Are you stuck trying to display a message in your program? This is the article for you. Today we’ll be showing you how to use string variables in Java in Android Studio.
If you need an introduction to coding and want to learn for FREE, check out our 30-minute beginners 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.
On a line underneath
setContentView(R.layout.activity_main);, let’s declare our first string variables. Use the keyword
String to do so. Then let’s declare three strings and name them
String firstName, lastName, name;
firstName the value
lastName the value
Interactive. The following format is used to do so:
String firstName = "Mammoth", lastName = "Interactive", name;
For the value of
name, concatenate (combine) the first two strings. Also, because we want to have a space between the words “Mammoth” and “Interactive”, add a space in quotation marks between the two strings in the concatenation. Your line of code should look like so:
String firstName = "Mammoth", lastName = "Interactive", name = firstName + " " + lastName;
To have our string actually appear on the screen, we will need to use the Toast utility. Below your strings, type in the following code:
Within the parentheses of this code, we can set some parameters. In the parentheses after
Toast.makeText, type in the following:
this, "The string " + name + " has " + name.length() + " characters.", Toast.LENGTH_LONG
Thus the message that shows up will tell us of how many characters our strings is made up.
Toast.LENGTH_LONG means the message be displayed for a couple of seconds.
To test the code, run the emulator, and zoom in. You will see the message “The string Mammoth Interactive has 18 characters.”
That is how you use strings in Android Studio! You will now be able to provide messages for the users of your applications. For more FREE tutorials, check out our 30-minute intro course on coding: training.mammothinteractive.com/p/learn-to-code-in-30-minutes