Strings and Text Values
Create and combine String values, use common `String` methods, compare text with `equals()`, and write escape sequences and text blocks.
আপনি একটি free preview lesson দেখছেন।
Lesson Overview
Almost every program works with text: user names, email addresses, course titles, error messages, search queries. In Java, we use String to represent text:
String courseName = "Java and OOP Foundation";
String is not a primitive data type. It is a class from the Java standard library, and it behaves differently from the numbers we met in the previous lesson: it can be missing (null), it is compared with .equals(), and it never changes after it is created. This lesson shows how to work with text safely.
Learning Objectives
After completing this lesson, you will be able to:
- Create String variables
- Distinguish between empty, blank, and
null - Concatenate Strings
- Access String length and characters
- Use common String methods
- Compare String content using
.equals() - Understand what String immutability means
- Use escape sequences
- Use text blocks for multi-line text
What Is String?
String represents text:
String studentName = "Sakib";
String courseName = "Java Foundation";
String email = "[email protected]";
In String courseName = "Java Foundation";:
String— typecourseName— variable name"Java Foundation"— String value
String Is Not Primitive
Java's primitive types are byte, short, int, long, float, double, char and boolean. String is not part of this list. String is a class, and a String variable is a reference-type variable. However, Java provides convenient syntax for String literals such as "Java Foundation".
String Literals and Variables
Text written inside double quotes is a String literal, for example "Java", "Welcome to Tarkev" or "". The last value is an empty String.
As with any variable, you can declare and initialize in one statement (String name = "Sakib";) or declare first (String name;) and assign later (name = "Sakib";).
Empty, Blank, and null
An empty String contains no characters, so its length is 0. A blank String is empty or contains only whitespace, such as "", " " or " ". Java checks these with two methods: isEmpty() checks whether the length is 0, and isBlank() checks whether the String is empty or contains only whitespace:
String emptyValue = "";
String blankValue = " ";
System.out.println(emptyValue.length());
System.out.println(emptyValue.isEmpty());
System.out.println(blankValue.isEmpty());
System.out.println(emptyValue.isBlank());
System.out.println(blankValue.isBlank());
Output:
0
true
false
true
true
A String of spaces is not empty, but it is blank. When checking that a user typed something, isBlank() is usually the check you want.
null
null means that the variable currently does not reference a String object. String courseName = null; is not an empty String:
String emptyValue = "";
String missingValue = null;
"" → A String exists, but it contains no characters
null → There is no String object reference
Calling a Method on null
The following code will fail at runtime, because courseName does not reference a String object. This causes a NullPointerException:
String courseName = null;
System.out.println(courseName.length());
This is why understanding the difference between null and an empty String is important.
String Concatenation
Combining multiple Strings is called concatenation. In Java, the + operator can be used:
String firstName = "Sakib";
String lastName = "Sami";
String fullName = firstName + " " + lastName;
System.out.println(fullName);
Output:
Sakib Sami
Concatenating Text and Other Values
String courseName = "Java Foundation";
int durationInWeeks = 8;
System.out.println(
"Course: " + courseName
+ ", Duration: " + durationInWeeks + " weeks");
Output:
Course: Java Foundation, Duration: 8 weeks
Concatenation and Calculation
Look at this code:
System.out.println("Total: " + 10 + 20);
Output:
Total: 1020
because evaluation happens from left to right:
"Total: " + 10
→ "Total: 10"
"Total: 10" + 20
→ "Total: 1020"
Use parentheses if the calculation should happen first:
System.out.println("Total: " + (10 + 20));
Output:
Total: 30
Length and Characters
To get the length of a String, use length():
String language = "Java";
System.out.println(language.length());
Output:
4
For simple Latin text, you can think of this as the character count. Technically, Java's String.length() counts UTF-16 code units.
String Index
String positions (indexes) start from 0, so in "Java" the J is at index 0 and the last a is at index 3:
String: Java
Index: 0123
charAt()
To get the character at a specific position, use charAt(). The last index is length - 1:
String language = "Java";
char firstCharacter = language.charAt(0);
char lastCharacter = language.charAt(language.length() - 1);
System.out.println(firstCharacter);
System.out.println(lastCharacter);
Output:
J
a
Invalid Index
The valid indexes of "Java" are 0, 1, 2 and 3, so this will fail at runtime:
String language = "Java";
language.charAt(4);
Common String Methods
substring()
You can use substring() to extract part of a String. The start index 0 is included and the end index 4 is excluded. With only a start index, it returns everything from that index to the end:
String value = "Java Foundation";
String language = value.substring(0, 4);
String secondPart = value.substring(5);
System.out.println(language);
System.out.println(secondPart);
Output:
Java
Foundation
toUpperCase() and toLowerCase()
String language = "Java";
System.out.println(language.toUpperCase());
System.out.println(language.toLowerCase());
Output:
JAVA
java
strip()
strip() removes whitespace from the beginning and end of a String:
String name = " Sakib ";
String cleanName = name.strip();
System.out.println(cleanName);
Output:
Sakib
Whitespace in the middle is not removed:
String name = "Sakib Sami";
System.out.println(name.strip());
Output:
Sakib Sami
contains()
contains() checks whether specific text exists inside a String. It is case-sensitive:
String courseName = "Java and OOP Foundation";
System.out.println(courseName.contains("OOP"));
System.out.println(courseName.contains("oop"));
Output:
true
false
startsWith() and endsWith()
These check the beginning and end of a String, for example a course name and a file name:
String courseName = "Java Foundation";
String fileName = "Main.java";
System.out.println(courseName.startsWith("Java"));
System.out.println(fileName.endsWith(".java"));
Output:
true
true
replace()
To replace text in a String:
String message = "I am learning Python";
String updatedMessage = message.replace("Python", "Java");
System.out.println(updatedMessage);
Output:
I am learning Java
Summary of Methods
| Method | Purpose |
|---|---|
length() | Returns the length |
charAt(index) | Returns the character at a specific position |
substring() | Returns part of a String |
toUpperCase() | Returns an uppercase version |
toLowerCase() | Returns a lowercase version |
strip() | Removes surrounding whitespace |
contains() | Checks whether text exists |
startsWith() | Checks a prefix |
endsWith() | Checks a suffix |
replace() | Replaces text |
isEmpty() | Checks whether the length is 0 |
isBlank() | Checks whether the String is empty or whitespace-only |
Comparing Strings
Use .equals() to compare the content of two Strings. Case matters, so "Java" and "java" are not equal; .equalsIgnoreCase() compares while ignoring case:
String firstLanguage = "Java";
String secondLanguage = "Java";
String lowercaseLanguage = "java";
System.out.println(firstLanguage.equals(secondLanguage));
System.out.println(firstLanguage.equals(lowercaseLanguage));
System.out.println(firstLanguage.equalsIgnoreCase(lowercaseLanguage));
Output:
true
false
true
Do Not Use == to Compare String Content
Look at the following example:
String firstValue = new String("Java");
String secondValue = new String("Java");
System.out.println(firstValue == secondValue);
System.out.println(firstValue.equals(secondValue));
Output:
false
true
because:
==compares whether the references point to the same object.equals()compares String content
Therefore, for String content use firstValue.equals(secondValue).
String Is Immutable
Java String is immutable. This means:
After a String object is created, its existing content cannot be changed.
Look at this code:
String language = "Java";
language.toUpperCase();
System.out.println(language);
Output:
Java
Why? toUpperCase() does not modify the original String. It returns a new String.
Store the Returned String
String language = "Java";
language = language.toUpperCase();
System.out.println(language);
Output:
JAVA
Remember the same behavior for methods such as strip(), replace(), and toLowerCase().
Escape Sequences
Escape sequences are used to represent special characters inside String literals. Common escape sequences:
| Escape | Meaning |
|---|---|
\n | New line |
\t | Tab |
\" | Double quote |
\\ | Backslash |
Here \n breaks the line, \" puts double quotes inside the text, and \\ writes the backslashes of the Windows path C:\Java\Projects:
System.out.println("Java\nFoundation");
System.out.println("He said, \"Learn Java.\"");
String path = "C:\\Java\\Projects";
System.out.println(path);
Output:
Java
Foundation
He said, "Learn Java."
C:\Java\Projects
\t inserts a tab, which is handy for lining up simple columns:
System.out.println("Name\tScore");
System.out.println("Sakib\t90");
Text Blocks
Java supports text blocks for writing readable multi-line text:
String message = """
Java and OOP Foundation
Language: Bangla
Level: Beginner
""";
System.out.println(message);
Output:
Java and OOP Foundation
Language: Bangla
Level: Beginner
Because the closing """ is on its own line, the text block ends with a line break. println() adds one more, so an empty line follows the output. Text blocks are useful for multi-line messages and for pasting formats such as JSON, SQL or HTML into code.
String and char
String and char are different types:
char grade = 'A';
String courseName = "Java";
char | String |
|---|---|
| Primitive type | Reference type |
| Single UTF-16 code unit | Text sequence |
| Single quotes | Double quotes |
'A' | "A" |
There Is No Empty char
Invalid:
char value = '';
But an empty String is valid:
String value = "";
Complete Example
public class Main {
public static void main(String[] args) {
String rawCourseName = " Java and OOP Foundation ";
String courseName = rawCourseName.strip();
System.out.println("Course: " + courseName);
System.out.println("Length: " + courseName.length());
System.out.println(
"Starts with Java: " + courseName.startsWith("Java"));
System.out.println("Contains OOP: " + courseName.contains("OOP"));
System.out.println("Uppercase: " + courseName.toUpperCase());
}
}
Output:
Course: Java and OOP Foundation
Length: 23
Starts with Java: true
Contains OOP: true
Uppercase: JAVA AND OOP FOUNDATION
Predict the Result
Question 1
System.out.println("Java " + 2 + 1);
System.out.println(2 + 1 + " Java");
What does this print?
Answer
Java 21
3 Java
+ works from left to right. In the first line the text comes first, so each number is joined as text. In the second line 2 + 1 is calculated before any text appears.
Question 2
String message = "I like Python";
message.replace("Python", "Java");
System.out.println(message);
What does this print?
Answer
I like Python. Strings are immutable: replace() returns a new String, and that result is thrown away because it is not assigned to anything.
Question 3
String course = "Java Basics";
System.out.println(course.substring(5).length());
System.out.println(course.charAt(course.length() - 1));
What does this print?
Answer
6
s
substring(5) returns "Basics", which has six characters. The last index is length() - 1, which is 10, and the character there is s.
Question 4
String saved = "Sakib";
String typed = " sakib ";
System.out.println(saved.equals(typed.strip()));
System.out.println(saved.equalsIgnoreCase(typed.strip()));
What does this print?
Answer
false
true
After strip() the typed text is "sakib". equals() is case-sensitive, so "Sakib" and "sakib" differ; equalsIgnoreCase() ignores case.
Question 5
char grade = "A";
Will it compile?
Answer
No: incompatible types: String cannot be converted to char. Double quotes make a String, even with one character. A char needs single quotes: 'A'.
Common Mistakes
Using Single Quotes for a String
Wrong:
String language = 'Java';
Correct:
String language = "Java";
Comparing Content With ==
firstValue == secondValue compiles and sometimes even gives the expected answer, which makes the bug hard to spot. It compares references, not content (see Comparing Strings above); use firstValue.equals(secondValue).
Ignoring the Returned String
Calling value.toUpperCase(); on its own changes nothing: the new String is returned and thrown away, so value still prints java. Store the result with value = value.toUpperCase();. The same applies to strip(), replace() and every other String method that "changes" text.
Using length() as the Last Index
value.charAt(value.length()) fails at runtime with StringIndexOutOfBoundsException, because indexes start at 0. The last character is at value.length() - 1.
Concatenation Instead of Addition
"Result: " + 10 + 20 prints Result: 1020, because the text comes first and each number is joined as text. Write "Result: " + (10 + 20) to print Result: 30.
Practice Exercise 1: Create Strings
Solutions: lesson 1.23.
Create String variables for the following information:
- Student name
- Course name
- Email address
- Country
- Error message
Practice Exercise 2: Empty, Blank, or null?
Classify each value:
String firstValue = "";
String secondValue = " ";
String thirdValue = null;
String fourthValue = "Java";
Practice Exercise 3: Length and Index
For String language = "Java";, answer:
- What is the length?
- What is the index of the first character?
- What is the index of the last character?
- What does
charAt(2)return?
Practice Exercise 4: Concatenation
Use these variables:
String firstName = "Sakib";
String lastName = "Sami";
Expected output:
Full name: Sakib Sami
Practice Exercise 5: Normalize Text
Use strip() and toUpperCase() on this input:
String rawName = " md sakib ";
to produce:
MD SAKIB
Practice Exercise 6: Compare Strings
Using these variables, print the .equals() result and the .equalsIgnoreCase() result:
String firstValue = "Java";
String secondValue = "java";
Practice Exercise 7: Fix the Immutability Issue
String language = "java";
language.toUpperCase();
System.out.println(language);
Expected output:
JAVA
Practice Exercise 8: Escape Sequence
Use a String to produce:
Course: "Java Foundation"
Path: C:\Java\Projects
Practice Exercise 9: Text Block
Use a text block to produce:
Course: Java and OOP Foundation
Language: Bangla
Level: Beginner
Knowledge Check
Question 1
What is String?
Question 2
Is String a primitive type?
Question 3
Which quotation marks are used for String literals?
Question 4
What is the difference between an empty String and null?
Question 5
What is the difference between isEmpty() and isBlank()?
Question 6
Which operator can be used for String concatenation?
Question 7
Where does a String index start?
Question 8
What does charAt() do?
Question 9
In substring(0, 4), is index 4 included?
Question 10
Which method should be used to compare String content?
Question 11
What is the difference between == and .equals()?
Question 12
What does it mean that String is immutable?
Question 13
Does toUpperCase() modify the original String?
Question 14
What does strip() do?
Question 15
What are text blocks used for?
Question 16
What is the main difference between String and char?
Knowledge Check Answers
Answer 1
String is a Java class used to represent a sequence of text.
Answer 2
No. String is a reference type.
Answer 3
Double quotes, as in "Java".
Answer 4
An empty String is a valid zero-length String object. null means that the variable does not reference a String object.
Answer 5
isEmpty() checks whether the length is 0. isBlank() checks whether the String is empty or contains only whitespace.
Answer 6
+
Answer 7
The index starts from 0.
Answer 8
It returns the char value at a specific index.
Answer 9
No. The end index is excluded.
Answer 10
equals()
Answer 11
== compares reference identity. .equals() compares String content.
Answer 12
The content of an existing String object cannot be changed.
Answer 13
No. It returns a new String.
Answer 14
It removes whitespace from the beginning and end of a String and returns a new String.
Answer 15
Text blocks are used to write readable multi-line Strings.
Answer 16
char is a primitive type that represents a single UTF-16 code unit. String is a reference type that represents a sequence of text.
Lesson Summary
Stringrepresents text. It is a class from the Java standard library, not a primitive type.- An empty String
""has no characters, a blank String is empty or whitespace-only, andnullmeans there is no String object reference. - The
+operator concatenates Strings from left to right, so use parentheses when a calculation should happen first. - String indexes start at
0, and methods such aslength(),charAt(),substring(),strip()andreplace()help you work with text. - Use
.equals()to compare String content;==compares references. - Strings are immutable, so store the String a method returns, such as
language = language.toUpperCase();. - Escape sequences represent special characters inside String literals, and text blocks make multi-line text readable.
আগে ভাবুন
শীঘ্রই আসছেCheckpoint প্রশ্ন, যেখানে lesson উত্তর দেখানোর আগে আপনাকে একটি উত্তর বেছে নিতে হবে।