In Java, text is stored in objects of the String class. This lesson covers the most important methods for working with text, comparing strings, working with single characters, splitting text into words, and the StringBuilder class for building text quickly.
Before you start: what you need to know first – arrays, loops. How to learn: type in and run each example, and try to solve the tasks at the end on your own first; open the hint and the solution only after that. All the programs are in Java (Java 17 or newer); each one has been compiled and run and gives the output shown.
String: creating, length and characters
A string is a sequence of characters. Its length is given by the length() method, and the character at position i by the charAt(i) method. Positions are counted from 0.
public class Main {
public static void main(String[] args) {
String word = "Programming";
System.out.println("Length: " + word.length());
System.out.println("First character: " + word.charAt(0));
System.out.println("Last character: " + word.charAt(word.length() - 1));
// going through all the characters
int vowels = 0;
for (int i = 0; i < word.length(); i++) {
char c = Character.toLowerCase(word.charAt(i));
if ("aeiou".indexOf(c) >= 0)
vowels++;
}
System.out.println("Vowels: " + vowels);
}
}
Output:
Length: 11
First character: P
Last character: g
Vowels: 3
Accessing a position out of range (e.g. charAt(11) for a word of 11 letters) causes the error StringIndexOutOfBoundsException.
The most important String methods
Method
Result for s = "Good day"
s.toUpperCase()
"GOOD DAY"
s.toLowerCase()
"good day"
s.indexOf("day")
5 (−1 if it does not exist)
s.contains("ood")
true
s.substring(5)
"day" – from position 5 to the end
s.substring(0, 4)
"Good" – positions 0…3
s.replace('o', 'a')
"Gaad day"
s.startsWith("Go")
true
" x ".trim()
"x" – without spaces at the ends
s.isEmpty()
false
A String is immutable: no method changes an existing string, it returns a new one instead. That is why the result must be saved:
public class Main {
public static void main(String[] args) {
String s = "Good day";
s.toUpperCase(); // the result is lost – s does not change
System.out.println(s);
s = s.toUpperCase(); // the new string is assigned to the variable
System.out.println(s);
System.out.println(s.substring(0, 4) + "!" + " (" + s.indexOf("DAY") + ")");
}
}
Output:
Good day
GOOD DAY
GOOD! (5)
Comparing strings: equals, not ==
With objects, the == operator checks whether they are the same objects in memory, not whether they have the same content. Content is compared with the equals method, and alphabetical order with the compareTo method.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.next(); // the user enters: java
String b = "java";
System.out.println(a == b); // false: different objects
System.out.println(a.equals(b)); // true: the same content
System.out.println("Java".equalsIgnoreCase(b)); // true: ignores upper/lower case
// compareTo: negative if the first comes earlier in the alphabet, 0 if equal, positive otherwise
System.out.println("Ana".compareTo("Mark") < 0); // true
System.out.println("Zoe".compareTo("Ana") > 0); // true
}
}
Input:java
Output:
false
true
true
true
true
This is one of the most common beginner mistakes: if (answer == "yes") often does not work. Always write if (answer.equals("yes")).
Working with characters: the Character class
The Character class has methods for checking and changing a single character: isDigit, isLetter, isUpperCase, toUpperCase… A digit is turned into a number by subtracting the character '0'.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String password = sc.next();
int digits = 0, upper = 0, lower = 0, digitSum = 0;
for (char c : password.toCharArray()) { // for-each through an array of characters
if (Character.isDigit(c)) {
digits++;
digitSum += c - '0'; // '7' - '0' = 7
} else if (Character.isUpperCase(c)) {
upper++;
} else if (Character.isLowerCase(c)) {
lower++;
}
}
System.out.println("digits=" + digits + " upper=" + upper + " lower=" + lower + " digit sum=" + digitSum);
boolean strong = password.length() >= 8 && digits > 0 && upper > 0 && lower > 0;
System.out.println(strong ? "Strong password" : "Weak password");
}
}
The split method splits a string into an array of parts by the given separator. The separator is a regular expression: " " is one space, and "\\s+" one or more spaces.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String sentence = sc.nextLine().trim();
String[] words = sentence.split("\\s+"); // one or more spaces
System.out.println("Number of words: " + words.length);
String longest = "";
for (String w : words)
if (w.length() > longest.length())
longest = w;
System.out.println("Longest word: " + longest);
// joining back together: String.join
System.out.println(String.join("-", words));
}
}
Input:Java is a really interesting language
Output:
Number of words: 6
Longest word: interesting
Java-is-a-really-interesting-language
For numbers in one line: String[] d = line.split(" "); int x = Integer.parseInt(d[0]);.
StringBuilder: building text quickly
Since a String is immutable, every s = s + "x" creates a new string and copies all of the old content. In a loop with 100 000 repetitions that is slow. The StringBuilder class stores text that can be changed: append adds to the end, reverse reverses, insert inserts, toString returns a String.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) {
sb.append(i);
if (i < n) sb.append(", ");
}
System.out.println(sb); // println calls toString()
String word = sc.next();
String reversed = new StringBuilder(word).reverse().toString();
System.out.println(reversed);
System.out.println(word.equalsIgnoreCase(reversed) ? "palindrome" : "not a palindrome");
}
}
Input:5 and Ana
Output:
1, 2, 3, 4, 5
anA
palindrome
Practice tasks
Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.
TASK 01Difficulty: medium
A shift cipher
The Caesar cipher shifts every letter of the English alphabet by k places (after z comes a); other characters do not change, and upper-case letters stay upper-case. Read k (0–25), then one line of text. Print the encrypted text.
Example
Input
3
Hello, world!
Output
Khoor, zruog!
Hint
For a lower-case letter c: (char) ('a' + (c - 'a' + k) % 26); for an upper-case one the same with 'A'. Build the result in a StringBuilder. After nextInt() call an empty nextLine().
Solution (Java)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
sc.nextLine(); // the rest of the line after the number
String text = sc.nextLine();
StringBuilder sb = new StringBuilder();
for (char c : text.toCharArray()) {
if (c >= 'a' && c <= 'z')
sb.append((char) ('a' + (c - 'a' + k) % 26));
else if (c >= 'A' && c <= 'Z')
sb.append((char) ('A' + (c - 'A' + k) % 26));
else
sb.append(c);
}
System.out.println(sb);
}
}
TASK 02Difficulty: medium
Counting words
Read one line of text and one word r (on the next line). Print how many times the word r appears in the text as a whole word, regardless of upper and lower case. Punctuation marks (.,!?) are ignored.
Example
Input
Java is a language. JAVA runs everywhere, java!
java
Output
3
Hint
Remove the punctuation with replaceAll("[.,!?]", " "), split into words with split("\\s+") and compare with equalsIgnoreCase.
Solution (Java)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String text = sc.nextLine();
String target = sc.nextLine().trim();
String[] words = text.replaceAll("[.,!?]", " ").trim().split("\\s+");
int count = 0;
for (String w : words)
if (w.equalsIgnoreCase(target))
count++;
System.out.println(count);
}
}
TASK 03Difficulty: harder
Compression
Read a word made of lower-case letters. Replace every group of consecutive identical letters with the letter and the number of repetitions (if the number is 1, only the letter is printed). E.g. aaabccdddd → a3bc2d4.
Example 1
Input
aaabccdddd
Output
a3bc2d4
Example 2
Input
abc
Output
abc
Hint
Go through the word and count how many times the current character repeats; when the character changes (or you reach the end), add the character to the StringBuilder and, if the count is greater than 1, the count.
Solution (Java)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < s.length()) {
char c = s.charAt(i);
int j = i;
while (j < s.length() && s.charAt(j) == c) // the end of a group of identical characters
j++;
sb.append(c);
if (j - i > 1)
sb.append(j - i);
i = j;
}
System.out.println(sb);
}
}
Common mistakes and tips
Compare strings with equals, never with ==.
String methods do not change the string – save the result: s = s.trim();.
substring(a, b) takes the characters from a to b − 1; the length of the result is b − a.
In a loop that builds a long text use StringBuilder, not +.
In split a dot must be written as "\\.", because a plain dot in a regular expression means "any character".
Check your knowledge
Open the quiz
Strings in Java
1. How do you check whether the strings a and b have the same content?
2. What does "Java".substring(1, 3) return?
3. What is the result of "abc".indexOf('x')?
4. Why is StringBuilder used in a loop?
Podešavanja kolačića
Koristimo kolačiće da bismo vam pružili najbolje moguće iskustvo. Takođe nam omogućavaju da analiziramo ponašanje korisnika kako bismo stalno poboljšavali veb lokaciju za vas.