课程: Learning Java 17
Strings in Java
- [Instructor] So far, we've learned about a few data types in Java, Int, Double, Boolean, and Char. These were primitive types and they were great for storing a whole or decimal number, a single letter or symbol, and a true or false value. But what if you want to use some text data in your code, something that requires more than just a single character? In this lesson we'll be looking at the second overarching category of Java data types called reference types. One reference type is called a string. A string is a sequence of ordered characters. Before we could represent a single character with a char. But now we can represent a word or a person's name with the string data type. To create a string, we surround a series of characters with quotation marks. This represents a string value. To create a string variable, we just state the string data type, give the variable a label and then use the assignment operator to assign the variable the string value. It's important to note that the order of the characters does matter. So let's say we have a string desserts and then we have different string stressed. Although these two strings have the same letters, they would not be considered as having equal value because the letters are in different orders. So what makes a string a reference type? Unlike the other data types we've looked at, a string is built out of character. It's not a basic data type. It's created out of organizing char pieces of data in a significant way. The deeper meaning behind reference types is out of the scope of this course. But I highly recommend you check out programming foundations data structures to find out more. Now that we know about strings, let's create a string in Java. Using our program from the last lesson, we'll add a student name variable that holds the student's name. In this case we'll have the student's name be Kayla Harley and we'll print it out to the console. Let's run it. And there we see the name. For this variable, I included the students first and last name. This is a design choice. Instead, we could create two separate strings, one holding the first name and another holding the last name. Let's do that. Then we'll print them out separately. Let's run it. And we get each name separately in the console.
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。