UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 16.8 Free with a free account
Strings: Why Text Needs Its Own Data Handling
Data Structures and Algorithms · Chapter 16: Sorting, Selection, and Text ProcessingSection 16.8 · lesson 74 of 879 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Data Structures and Algorithms.
Lesson complete
Earn the 3 college credits for Data Structures and Algorithms
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Pattern Matching: Finding a Word Inside a Text →← Sorting and Selection in PracticeNext lesson: Pattern Matching: Finding a Word Inside a Text →
In this lesson
How Java stores, compares, and builds text efficiently.
- Explain why Java strings are immutable and why equals, not ==, compares text
- Use StringBuilder to build and edit text efficiently
- Predict the result of compareTo from character codes
- Recognize quadratic string patterns in loops and replace them
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,193 words). Read along, or search it.
Opening Question
Why file10 Sorts Before file2
Here are three file names: file2, file10, and file1. Let's ask Java to sort them. The result: file1, file10, file2. Ten lands before two. No person would sort them that way. So why does Java? The answer is in how text is stored and compared. A string looks like an array of characters, but text has needs of its own.
What Text Needs
Comparing, Joining, Converting, and Encoding
Text has to compare in dictionary order, be glued together and cut apart, and convert to and from numbers. It serves as a lookup key in maps, and it has to cover every writing system on Earth. Java's String class is shaped by these needs.
Immutability
Strings Never Change After Creation
A Java String is immutable: once it's created, its characters can never change. Methods that seem to change one, like toUpperCase, or the plus operator, build a new string, and leave the original alone. Run it. The old name still reads cat. The upper-case copy is CAT, and s now names a new string, cats. Next, two equal literals share one object, so double equals says true. But a string made with new is a separate object, so it says false. Double equals asks whether two names point to the same object. To compare the text itself, always use equals. Why immutable? A string can be shared freely, and a map key keeps the same hash code for life, which the hash tables of chapter 14 rely on.
Quick Check
A Discarded toUpperCase Result
Quick check. This program calls toUpperCase on x, then builds y by adding an exclamation mark. What does it print? Pause and predict. It prints data, then data with an exclamation mark. The call built an upper-case copy, but nothing kept it, so it was thrown away. x still names the original. To keep the change, assign it: x equals x dot toUpperCase.
StringBuilder
Editing Text in a Changeable Buffer
So how do we edit text without making a new string each time? A StringBuilder keeps its characters in an array it can change. Edit the builder as much as you like. Then call toString once, at the end, to get the final String. Run it. Append gives cats. Insert at the front gives big cats. Set the first character, and it's a capital B. Delete index three, and the space goes. Reverse turns the whole text around. Appending is cheap. But insert and delete shift every later character, so they cost order n.
Capacity Growth
Why Appending Costs Order One
Why is appending cheap? A new builder has room for 16 characters. When it fills, Java allocates an array about twice as large, and copies the characters across. It's the same trick a resizable list uses. This program appends a hundred thousand characters, and counts each time the buffer is replaced. Capacity runs 16, 34, 70, 142, and on. A hundred thousand characters needed only 13 reallocations. The total copying stays under about twice the final length, so each append costs order one, on average. Inserting at the front is different. In one test, a hundred thousand front inserts took about 136 times as long as the appends.
Characters
Chars Are Numbers
Characters are numbers. A Java char is a 16-bit code. Letters are numbered in alphabetical order, and digits in numeric order. So arithmetic on them means something. The digit character seven, minus the character zero, is the number seven. c minus a is two. And a plus three, cast back to a char, is d. Capital A is 65, and lower-case a is 97. Every capital letter has a smaller code than every lower-case one. Unicode gives every character a code point, over 1.1 million of them. A single char holds only codes up to 65,535. A bigger one, like the smiling-face emoji, takes two chars, called a surrogate pair. So length reports four for a three-character string. Code point count reports the true three.
Comparison
Dictionary Order by Character Code
Strings compare like words in a dictionary, but by character code. Scan from the left until they differ. The smaller character there decides. If one string runs out first, it's a prefix of the other, and it comes first. compareTo returns a difference, so negative means the first string comes first. Apple against apricot gives minus two, since p is two less than r. Capital Apple against lower-case apple gives minus 32. App against apple gives minus two, the difference in lengths. And the string 10 comes before the string 9, since the character 1 is smaller than 9. Sort seven words in this natural order. Digits come first, then capitals, so Zebra lands before apple. Ignoring case puts Zebra last.
Answer
The File Names Explained
And that answers the file names. file10 and file2 first differ at their fifth character: one against two. One is smaller, so file10 comes first. The number ten never enters into it. A rule that sorts the way people expect has to read each run of digits, as one whole number.
Quick Check
Sorting b9, B2, and b10
Quick check. Three tags: b9, capital B2, and b10. Arrays.sort uses the natural order. What order comes out? Pause and predict. Capital B2 first, then b10, then b9. Capital B has a smaller code than lower-case b. Then b10 and b9 differ at the second character, and one is smaller than nine. Numeric value never enters into it.
Hidden Cost
Plus-Equals in a Loop Is Quadratic
Because a string can't change, an operation usually costs as much as building its result. length and charAt are constant time. substring copies the piece it returns. And plus builds a new string holding both sides. A single expression, like hello plus a name, is fine. The trouble is repeating s plus-equals x inside a loop. Every pass copies all the characters so far. After n passes, that's n times n plus one, over two characters: quadratic. In one test, 10,000 appends with plus-equals took 16 milliseconds. 200,000 took about 2.9 seconds: 181 times longer, for 20 times the work. A StringBuilder did the 200,000 in under half a millisecond.
Better Loop
Walk With an Index, Not Substring
The same trap hides in substring. Chopping off the first character, again and again, copies everything that's left on every pass. Walking with an index copies nothing. Both loops here add up the same character codes, and they print the same total. In one test on a hundred thousand characters, chopping took about 638 milliseconds. Walking took a quarter of a millisecond.
Everyday Tasks
Reversing, Palindromes, Counting, and Parsing
With these tools, most everyday text tasks take one pass. A builder reverses stressed into desserts. A palindrome test compares characters from both ends, moving inward. With spaces and case removed, never odd or even reads the same both ways. Letter counts use an array of 26, where the character itself picks the counter. Mississippi has four i's and four s's. Split cuts a sentence into words, here six, and join glues them back with dashes. Parsing builds a number digit by digit: ten times the value so far, plus the next digit. Adding one proves it's a real number. And parseInt rejects text that isn't a number, with a NumberFormatException.
Key Takeaways
Java Strings in Brief
To sum up. Strings are immutable. Compare them with equals, never with double equals. Build text in a StringBuilder: appending costs order one on average. Chars are numbers, and comparison goes character by character. So 10 sorts before 9, and capitals before lower case. Plus-equals and substring in a loop are quadratic. Walk with an index instead.
About Data Structures and Algorithms at UPI Study
Data Structures and Algorithms (Computer Science 251) is a self-paced online course of 87 video lessons in 17 chapters, from Java and object-oriented design to arrays, linked lists, recursion, stacks and queues, trees, heaps, hash tables, sorting and graphs. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: Discrete Math vs Data Structures and Algorithms · Intro to Java vs Data Structures and Algorithms
Why take it here
Why students take Data Structures and Algorithms with UPI Study
Where the credit goes
Universities that work with NCCRS
Data Structures and Algorithms carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Strings: Why Text Needs Its Own Data Handling
What is the difference between == and equals for Java strings?
Why are strings immutable in Java?
Why does Java sort file10 before file2?
Why is using += to build a string in a loop slow?
About the Data Structures and Algorithms course
How many college credits is Data Structures and Algorithms?
How much does Data Structures and Algorithms cost and what is included?
Which universities accept UPI Study credits?
How long does Data Structures and Algorithms take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Data Structures and Algorithms.
87 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →