Java Basics: Your First Programs
Strings and Text
In this lesson you will
- Use common String methods
- Compare strings correctly with equals, not ==
- Build text efficiently with StringBuilder and format it
Introduction
Text is everywhere: names, messages, file contents. In Java, text is an object of the class String. It has many useful methods, and a few traps that catch every beginner. Let's learn both.
String methods
Java
public class Main {
public static void main(String[] args) {
String text = " Hello, Java World ";
System.out.println(text.length());
System.out.println(text.trim());
System.out.println(text.toUpperCase());
System.out.println(text.trim().toLowerCase());
System.out.println(text.trim().charAt(0));
System.out.println(text.indexOf("Java"));
System.out.println(text.contains("World"));
System.out.println(text.trim().substring(7));
System.out.println(text.trim().replace("Java", "Python"));
}
}21
Hello, Java World
HELLO, JAVA WORLD
hello, java world
H
9
true
Java World
Hello, Python WorldPositions start at 0. substring(7) takes everything from position 7 onwards, and substring(0, 5) takes positions 0 to 4 (the end is not included).
Strings are immutable
A String can never change after it is created. Methods like toUpperCase() return a new String and leave the original alone. A common mistake is to forget to use the result:
Java
public class Main {
public static void main(String[] args) {
String name = "asha";
name.toUpperCase(); // result thrown away
System.out.println(name);
name = name.toUpperCase(); // keep the result
System.out.println(name);
}
}asha
ASHAQuick quiz
What does text.toUpperCase() do to the original String text?
Comparing strings: equals, not ==
This is the most important String rule in Java. == checks whether two variables refer to the same object. equals() checks whether the text is the same.
Java
public class Main {
public static void main(String[] args) {
String a = "java";
String b = new String("java");
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println("JAVA".equalsIgnoreCase(a));
System.out.println("apple".compareTo("banana") < 0);
}
}false
true
true
truea and b hold the same letters, but == says false, because they are two different objects. Always compare text with .equals(). compareTo gives a negative number if the first comes before the second alphabetically.
Joining and splitting
Java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String first = "Ada";
String last = "Lovelace";
System.out.println(first + " " + last);
System.out.println(first.concat("!"));
System.out.println(String.join("-", "a", "b", "c"));
String csv = "red,green,blue";
String[] colours = csv.split(",");
System.out.println(colours.length);
System.out.println(Arrays.toString(colours));
System.out.println("ha".repeat(3));
System.out.println("".isEmpty() + " " + " ".isBlank());
}
}Ada Lovelace
Ada!
a-b-c
3
[red, green, blue]
hahaha
true trueStringBuilder
Because Strings cannot change, building a long text with + in a loop creates many throwaway objects. A StringBuilder is a text you can change, which is much more efficient.
Java
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i);
if (i < 5) {
sb.append(", ");
}
}
System.out.println(sb.toString());
System.out.println(sb.reverse());
System.out.println(sb.length());
}
}1, 2, 3, 4, 5
5 ,4 ,3 ,2 ,1
13Formatting output
String.format (or System.out.printf) builds text from a template with placeholders. Common ones: %s for text, %d for whole numbers, %.2f for a decimal with 2 places, %n for a new line.
Java
public class Main {
public static void main(String[] args) {
String name = "Asha";
int items = 3;
double total = 12.5;
System.out.printf("%s bought %d items for %.2f%n", name, items, total);
System.out.println(String.format("|%8s|%-8s|", "right", "left"));
System.out.println(String.format("%05d", 42));
System.out.println(String.format("%,d", 1234567));
}
}Asha bought 3 items for 12.50
| right|left |
00042
1,234,567Text blocks
For several lines of text, use triple quotes (Java 15 and newer). Line breaks and the indentation relative to the closing quotes are kept.
Java
public class Main {
public static void main(String[] args) {
String poem = """
Roses are red,
Violets are blue,
Java is fun,
And so are you.
""";
System.out.print(poem);
}
}Roses are red,
Violets are blue,
Java is fun,
And so are you.Quick quiz
How should you check whether two Strings contain the same text?
Try it yourself
On your computer, write a program with a method static boolean isPalindrome(String word) that returns true when the word reads the same backwards. Hint: build a reversed copy with new StringBuilder(word).reverse().toString() and compare with equals. Test it with "level" and "java".
Summary
- Strings are objects with methods such as
length,substring,indexOf,replace,splitandtrim. They never change: methods return new Strings. - Compare text with
equals(), not==. StringBuilderbuilds text efficiently in loops.String.formatandprintfuse placeholders like%s,%dand%.2f. Text blocks"""hold multi-line text.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading