Summary - String basics
- Java course
- Beginner
- Lesson 35/116
- 5 min
Combine length, substring and format to write a business card.
Summary - String basics
In this group you learned String methods:
- length/charAt: length and character access
- equals/equalsIgnoreCase: content comparison
- indexOf/substring: search and slice
- toUpperCase/trim: transformation
- String.format: formatting
These methods are the basic tools to process, search, transform and format string data. Now combine them and write a business card.
Practice Write a business card
Write a Main class with a main method. Assign "Alex" to String name and "Engineer" to String title. Assign name + " - " + title to String card. Print card and card.length() with println.
Sample solution
public class Main {
public static void main(String[] args) {
String name = "Alex";
String title = "Engineer";
String card = name + " - " + title;
System.out.println(card);
System.out.println(card.length());
}
}Expected output
Alex - Engineer 15
Tips
A few tips from this group:
- Always use
equalsfor String comparison;==is not reliable. - Trim user input that may have extra spaces first.
- Check
indexOfresult against-1. - Strings are immutable; assign transformations to a new variable.
- Use
String.formatto format output.
Combined with conditionals and loops, these basics let you write powerful programs.
Practice Business card with String.format
Write a Main class with a main method. Assign "Alex" to String name and 28 to int age. Assign String.format("%s - %d", name, age) to String card. Print card with println.
Sample solution
public class Main {
public static void main(String[] args) {
String name = "Alex";
int age = 28;
String card = String.format("%s - %d", name, age);
System.out.println(card);
}
}Expected output
Alex - 28
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the methods
| Term | Meaning |
|---|---|
length() |
Length |
equals() |
Compare |
substring() |
Slice |
format() |
Format |
2 Complete the substring call
String first = name.____(0, 1);
String first = name.substring(0, 1);
Explanation: substring(0, 1) gives the first character.