Skip to content

Latest commit

 

History

History
281 lines (206 loc) · 9.03 KB

File metadata and controls

281 lines (206 loc) · 9.03 KB

Strings

Strings are perhaps the most important data type in Java. Many other computer languages have strings, and they are used in almost ALL modern programs. Knowing how to manage them, create and modify them to do what you need them to do, is a "sub-superpower" within Java.

Pay close attention; this stuff is VERY important.

What is a String?

Think about the words on this page. The text here is made up of a bunch of letters, and spaces. Now, when we write by hand, we don’t really think about the space between the words, do we? If we truly ignored the notion of space between the words, wewouldendupwithtextlikethis. And while it is possible to read, our modern eyes are trained on well-edited texts; having no spaces tires us pretty quickly.

So yes, what we see as text in this book is really a series of letters and spaces strung together in a line - line after line, paragraph after paragraph. In modern computing, that kind of data is often called a String. It is one of the most fundamental aspects of coding: the manipulation of strings by programs to transform, present or store text in some fashion.

Many programming languages use some kind of quote or double quote to show where strings start and end. Java uses double quotes, like this: "the quick brown fox". So a string like "the quick brown fox" would be a string from the 't' to the 'x'. And notice the three spaces within the string. If they were not there, the string would be "thequickbrownfox". And that’s important, because to the computer, if it keeps these two strings around, it doesn’t really understand that 'the' and 'quick' are just two common English words. The spaces are there to retain more of what the human meant.

No, to the computer, each letter, including the space 'letter', is just a piece of data and very important.

String - a string of letters and numbers and spaces and punctuation, kept altogether for some use. Here are some strings for you to consider.

"the quick brown fox"
"The New York Times"
"And lo, like wave was he..."
"oops"
"Hello, World!"
"supercalifraglisticexpealadocious"
"On sale for $123.99!!"
"Pi is approximately 3.14159"
"Merge left at the ramp to the right, the restaurant is on the right"
"He said, \"Wait there is more!\""

Think of strings as a tightly packed list. Each item and letter is numbered. The entire string can be "indexed", meaning I can reach in and copy out, say, the fifth letter easily. String indexes are zero-based; therefore, the first character (element) is in index position 0.

Index  -> 012345
String -> Hello

So here, "H" is at 0, "e" is at 1, 'l' is at 2 & 3, and 'o' is at index position 4. Computers often start numbering things like strings, lists, and arrays at 0, not at one. It’s just one of those things: all strings and arrays (which are coming up) start at zero.

Declaring a string

String name = "Wacka Flocka";

Now we have a string variable named name and it’s value is "Wacka Flocka".

String Properties

A common and often used string property is length().

We can use .length to find the length of a string

String str = "Wakanda Forever!";
int answer = str.length();
System.out.println(answer); // -> 16

Accessing Characters in a String

As mentioned before, we can reach into a string and copy out the stuff we find there.

String word = "Hello";
// Access the the first character (first by index, second by function)
System.out.println(word.charAt(0)); // H
// the last character
System.out.println(word.charAt(word.length() - 1)); // o

When you see something like word[0], it is pronounced like "word sub zero". If you have word[5], you would say "word sub five". This is just verbal shorthand for the expression.

String Concatenation (Joining strings)

This simply means joining strings together using the + operator or the concat( ) method. Either one is commonly used.

int price = 20;
String dollarSign = "$";
String priceTag = dollarSign + price; // $20
//or
String priceTag = dollarSign.concat(String.valueOf(price)); // $20
System.out.println(priceTag); // -> $20

Or perhaps a little more useful example:

String name = "Mikaila";
int hoursWorked = 12;

String workReport = "Today, " + name + " worked a total of " + hoursWorked + " hours."
System.out.println(workReport);

The output would be:

Today, Mikaila worked a total of 12 hours.

SubStrings

Getting a substring is a common operation. This is how we extract the characters from a string, between two specified indices. (Which is why it’s important to remember the indexes start at 0.)

someString.substring(start, end)

A start position is required, where to begin the extraction. Remember, first character is at position 0. Characters are extracted from a string between "start" and "end", not including "end" itself.

String firstName = "Christopher";

Now let’s use the 3 substring methods on firstName and extract and print out "Chris"

String firstName = "Christopher";
System.out.println(firstName.substring(0,5)); // "Chris"

Yep. They all print "Chris". (Act impressed…​ thanks!) BUT, let’s try to extract the string "stop" from the name.

String firstName = "Christopher";
System.out.println(firstName.substring(4,8)); // "stop"

Notice how the arguments to the functions are slightly different. This is why it might be best to pick to memorize and use that one.

Let’s try a little harder idea…​

Exercise: Extract and Transform Substring

String fName = "Christopher";
  • Your turn to use the substring/substr/slice method on firstName

  • Extract and print out "STOP" from inside the string above

  • And make it uppercase! ("stop" to "STOP") [1]

Well?

String fName = "Christopher";
System.out.println(fName.substring(4,8).toUpperCase());

Want to bet there is also a "toLowerCase()" method as well?

Summary of substring methods

Take a look at these various ways to copy out a substring from the source string named 'rapper', which contains the string 'mikaila'.

String rapper = "mikaila";

System.out.println(rapper.substring(0,4));  // mika
System.out.println(rapper.substring(1,4));  // ika

System.out.println(rapper.substring(4,7));  // ila
System.out.println(rapper.substring(3,7));  // aila

We’re using each of the three different substring methods to copy out some smaller piece of the 'rapper' string.

Chapter Exercises

Try these exercises in jshell to practice working with strings:

Exercise 1: String Basics

Practice string creation and basic properties:

String firstName = "Alice";
String lastName = "Johnson";
String fullName = firstName + " " + lastName;

System.out.println("First name: " + firstName);
System.out.println("Last name: " + lastName);
System.out.println("Full name: " + fullName);
System.out.println("Full name length: " + fullName.length());
System.out.println("First character: " + fullName.charAt(0));
System.out.println("Last character: " + fullName.charAt(fullName.length() - 1));

Exercise 2: String Methods

Explore different string methods:

String message = "Java Programming is Fun!";

System.out.println("Original: " + message);
System.out.println("Uppercase: " + message.toUpperCase());
System.out.println("Lowercase: " + message.toLowerCase());
System.out.println("Length: " + message.length());
System.out.println("Contains 'Java': " + message.contains("Java"));
System.out.println("Contains 'Python': " + message.contains("Python"));
System.out.println("Starts with 'Java': " + message.startsWith("Java"));
System.out.println("Ends with '!': " + message.endsWith("!"));

Exercise 3: Substring Practice

Extract parts of strings:

String email = "alice.johnson@example.com";

int atIndex = email.indexOf("@");
String username = email.substring(0, atIndex);
String domain = email.substring(atIndex + 1);

System.out.println("Email: " + email);
System.out.println("Username: " + username);
System.out.println("Domain: " + domain);

// Extract first and last name from username
int dotIndex = username.indexOf(".");
String first = username.substring(0, dotIndex);
String last = username.substring(dotIndex + 1);

System.out.println("First name: " + first);
System.out.println("Last name: " + last);

Exercise 4: String Building

Create formatted output:

String productName = "Laptop";
double price = 1299.99;
int quantity = 2;
double total = price * quantity;

String receipt = "Product: " + productName + "\n" +
                "Price: $" + price + "\n" +
                "Quantity: " + quantity + "\n" +
                "Total: $" + total;

System.out.println("=== RECEIPT ===");
System.out.println(receipt);
System.out.println("===============");

// Practice with StringBuilder for better performance
StringBuilder sb = new StringBuilder();
sb.append("Order Summary:\n");
sb.append("Item: ").append(productName).append("\n");
sb.append("Cost: $").append(total);
System.out.println(sb.toString());

1. You could google how to do this, try "Java string make upper case"