Learn/Java/8. Strings and a small project
Lesson 8 of 15
Sign in

Java, lesson 8

Strings and a small project

Text is everywhere: names, commands, file lines. Java's String class has a large toolbox. One rule underlies all of it: strings are immutable. Methods like toUpperCase or replace never change the original; they return a new string, which you must store or use.

Looking inside a string

Changing and splitting

Compare text with equals or equalsIgnoreCase, never ==. To sort words alphabetically, a.compareTo(b) returns a negative number, zero or a positive number.

Characters

A is a single UTF-16 code unit. The class has handy tests:

2 exercises to try what you just read.

Exercise 1

Palindrome checker

Press Ctrl Enter or Check to test your code.

Exercise 2

Receipt printer

Press Ctrl Enter or Check to test your code.

char
Character

Building strings efficiently

Joining strings with + inside a loop creates a brand-new string every time. For many pieces, use a StringBuilder, which is a mutable buffer:

String.format works like printf but returns the string instead of printing it, which is handy for building aligned output: String.format("%-8s%5.2f", name, price) pads the name to 8 characters on the left and the price to 5 on the right.

Putting it together

The second exercise below is a small project. It uses input reading (lesson 3), loops (5), methods (6), a collection (7) and string tools from this lesson. Plan before you type: what do you read, what do you keep, and what do you print at the end?

Further reading

  • Strings (dev.java)
  • StringBuilder (dev.java)
  • String API

Read one line of text. Ignoring case and every character that is not a letter or digit, decide whether it reads the same forwards and backwards. Print Palindrome or Not a palindrome. A line with no letters or digits at all counts as a palindrome.

Sample input:

Sample output:

Each input line is a purchase in the form name,quantity,unit price, for example apple,3,0.50. Blank lines should be skipped. For each purchase, print the name in upper case, x and the quantity, and the line total with two decimals, separated by single spaces. After all purchases, print the total number of items and the grand total.

Write a helper method static String formatLine(String name, int qty, double lineTotal) that builds one receipt line.

Sample input:

Sample output:

With no purchases at all, print just Items: 0 and Total: 0.00.

String word = "hello";
word.toUpperCase();              // result thrown away, word is still "hello"
word = word.toUpperCase();       // now word is "HELLO"
String s = "Java rocks";
s.length();            // 10
s.charAt(0);           // 'J'   (a char; indexes start at 0)
s.indexOf("rocks");    // 5     (-1 if not found)
s.contains("ava");     // true
s.startsWith("Ja");    // true
s.substring(5);        // "rocks"       from index 5 to the end
s.substring(0, 4);     // "Java"        from 0 up to, not including, 4
"  padded  ".strip();          // "padded"  (strip is the Unicode-aware trim)
"a-b-c".replace("-", "+");     // "a+b+c"
"Shout".toUpperCase();         // "SHOUT"
"x,y,z".split(",");            // ["x", "y", "z"]
String.join(" | ", List.of("a", "b"));  // "a | b"
"ab".repeat(3);                // "ababab"
"   ".isBlank();               // true
for (char c : "R2-D2".toCharArray()) {
    if (Character.isLetterOrDigit(c)) {
        System.out.print(Character.toLowerCase(c));   // r2d2
    }
}
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 3; i++) {
    sb.append(i).append("! ");
}
System.out.println(sb.toString().strip());   // 1! 2! 3!
System.out.println(new StringBuilder("stressed").reverse()); // desserts
Was it a car or a cat I saw?
Palindrome
apple,3,0.50
bread,1,2.25
milk,2,1.10
APPLE x3 1.50
BREAD x1 2.25
MILK x2 2.20
Items: 6
Total: 5.95