Strings and the StingBuilder Class
The course is part of this learning path
This course delves into the String class and looks at the functionality it provides through a host of methods. We will also discuss how string objects are immutable, which means the object itself can't be modified once they've been created.
- Learn how the StringBuilder class differs from the string class
- Beginner coders or anyone new to Java
- Experienced Java programmers who want to maintain their Java knowledge
- Developers looking to upskill for a project or career change
- College students and anyone else studying Java
This is a beginner-level course and can be taken by anyone with an interest in learning about Java.
In the last lecture, we looked at some of the common, particularly useful methods of the String class namely, charAt, length, equals, and compareTo. In this lecture, we will cover a few more to increase our knowledge of what Strings can do. Namely, we'll look at toUpperCase, toLowerCase, substring, and indexOf.
The toUpperCase and toLowerCase methods are, as you might have guessed, for making uppercase and lowercase Strings. When called on a String object, these methods do not change the String on which they are called. But instead, they create a new String object with the upper or lowercase version of the original and return the reference of the new String object.
The substring method has two primary overloads, which basically means two different versions of the method with the same method name. We'll talk about overloads later in the course in more detail. The two overloads are, One overload of substring taking the single argument, the beginning index. This allows you to start an index in the String and it goes through the end of the String, including the last character. The substring method, just like the toUpperCase and toLowerCase, returns a new String. The second overload takes two arguments. The beginning index and the ending index. Note that the character at the beginning index is included, but the character at the ending index is excluded or not included.
Finally, the indexOf method also has many overloads. We'll concern ourselves only with the two overloads that take String parameters, but versions that take single characters also exist. Both of these take the String parameters that you're looking for as the first argument or only argument as in the single-argument overload's case. However, one overload takes as its second argument, the startFrom index to indicate where in the String to start the search from. This version helps you when you want to loop through and keep trying to find multiple occurrences of Strings being searched for.
You might wonder what happens if indexOf doesn't find the substring it's looking for? Good question. I'm glad you asked. The method returns a -1 to indicate that the String was not found. This is a great value to use, because zero and all the positive integers are all valid indices for the characters. So, -1 can be used as a special value to indicate that the substring in question was not found.
Now that we have a basic idea of what some of these methods do, let's write some code. So, let's create a new Java Class named StringMethods2. Right click 'New', 'Java Class', StringMethods and then the number 2. Alright, public static void main, there is our little skeleton code right there. Put some names or rather Strings in here. I guess we could use the name here. MyName= John Baugh. String upper = myName.toUpperCase. String lower = myName.toLowerCase. Now, if we want to find an index of something, so let's do here, whereIsB. I'll say myName.indexOf and then we're passing in a 'B'. Now in this case, you could have used a single character. So, string_lastName = myName.substring. And we'll start at 5. And if you use the single argument version that goes from whatever index you indicate to the end, and if you look at my name we have, J at 0, o 1,the h is at 2, n is at 3, space is at 4 and the B is at 5.
So, if we start at 5 and we don't specify an ending index, it'll go all the way to the end. So, I only want the last name, so I can just say hey, start at five and give me the substring. So, let's print out all of this fun stuff. We'll say, upper is and then we'll say, System.out.println, lower is. And System.out.println, and we'll say, B is at index, with a space, of course. We'll say, whereIsB. And then println, Last name is lastNname. Now, let's run it of course. So, run that and then go to 'Run', and we get some nice output here. So, we can see the versions of my name in both upper and lowercase. We also see where the index of the character B is in my name, as well as the sub string of my name only including my last name. So, clearly there's a lot of power in these methods and I want you to really, really pay attention to the upcoming challenge and what we've done in this lecture because they might help you for the project at the end. Before moving on to the next lecture, however, I want you to exercise your problem-solving skills. I have another challenge for you.
Using your new found methods of the String class and your problem-solving skills, I would like you to create a new Java Class named NameParser. In this class, you'll of course create the main method. You will take user input and prompt to the user for their first and last names. In much of the Western world, this would of course be the given name which is what we call the first name, followed by a space and then followed by the family name. Remember how to retrieve user input? Use the scanner class with the system.in argument to obtain input from the keyboard through the console. Once you have the user's full name in a single string, you will use the methods we've learned in this lecture to split the name into first and last name. As a hint, remember that you saw how I split my first and last name but you can't use the exact code because not everyone's name is the same size.
So, how might you find where to split the first and last name and then actually perform the split? When you've done this, print out the uppercase version of the first name and the lowercase version of the last name. So, give this one a try. Pause the video and come back when you're done or if you need some help. How'd that work out for you? Did you complete this challenge? This one was a little tricky. So don't worry if you found it very challenging or didn't even finish it, let's work on it together and see what we can do with it. So, we will create the NameParser file, right-click, 'New', 'Java Class', and we'll call this NameParser. And of course, give it a main public static void main with (string args). And since we're using the scanner class, I'm just going to prepare by importing that. Scanner keyboard = new Scanner on System.in.
So, now I'm ready to take user input. And we'll have some strings here, full name, and I'm going to also create strings to hold the first name and the last name. Then, System.out.println, What is your full name? And we will grab the fullName using keyboard.nextLine. Now, in order to split the name, we have to know where the two names are separated because you can't go off of one particular number like we did with my name. We just said the space is at index 5, you can't do that. My name starts at index 5. You can't do that with this because not everyone's name is the same length. So, what we really need to do is we need to find the index of the space between the two names, between the first and the last name. So, int indexOfSpace, fullName.substring. I am sorry, not substring, sorry. IndexOf, I am getting excited, I am getting ahead of myself. So, we got index of the space. So, no matter what the name is, as long as they have a first name, last name specified with a space in between, you should be able to find the index programmatically. Now firstName = I'm going to reuse it.
So, firstName., fullName rather, fullName.substring. And we're going to start at 0, but we're going to go up to index of the space. Now, remember, the second argument is not included. So, we don't want a space in our first name, we just want the first name and this will do it. But what do we do about the last name? Last name is fullName.substring. We want to not start at index of space because that would include a space in front of our last names. We need indexOfSpace+1. Once we've done that, you actually don't need a second argument passed in, because we know we want to go to the end. We want the full last name. And now, I'm going to reuse firstName here. Remember what our goal is, is to have the first name in uppercase and the last name, we're setting to lastName.tolowerCase and what's happening is, firstName.toUpperCase does not modify first name the object that's living in here, which would hold John if it was my name.
What it's doing is, it's actually creating a brand new String in all caps, John with J-O-H-N, all caps, and then it's returning the address of that brand new string object. Because we'll take a look at a little bit later that Strings don't actually allow you to modify them directly, we'll see a lot about that in the next lecture. But we are basically reusing the variables. Now, let's print it out. First name is and then Last name is, here we go. And let's run it. Right click, 'Run', and it is prompting us for a full name. I'm going to put John Baugh for this first round and it will say first name is John, last name is Baugh. Right, pretty cool. Let's run it again, just so you know I'm not fooling with you. Pick something with a different length here. Matthew Leath, there we go. And let's pick another one and we'll say Xena warriorprincess, like that. All one word there. There you go. Pretty cool, awesome.
So, we found the space which could be pretty much anywhere in a name and then once we have its index, we can easily create substrings of the first and last name. Nice work, everyone. In the next lecture, we will discuss another useful class called String Builder. It's similar to String but it allows you to make modifications to the actual text data in the object without creating a brand new object. I'll see you there.
John has a Ph.D. in Computer Science and is a professional software engineer and consultant, as well as a computer science university professor and department chair.