Lesson 11 / 140
লিখিত lesson · 14 মিনিট

Strings and Text Values

Create and combine String values, use common `String` methods, compare text with `equals()`, and write escape sequences and text blocks.

Preview

আপনি একটি 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:

java
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:

java
String studentName = "Sakib";
String courseName = "Java Foundation";
String email = "[email protected]";

In String courseName = "Java Foundation";:

  • String — type
  • courseName — 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:

java
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:

text
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:

java
String emptyValue = "";
String missingValue = null;
text
""   → 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:

java
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:

java
String firstName = "Sakib";
String lastName = "Sami";
String fullName = firstName + " " + lastName;
System.out.println(fullName);

Output:

text
Sakib Sami

Concatenating Text and Other Values

java
String courseName = "Java Foundation";
int durationInWeeks = 8;
System.out.println(
        "Course: " + courseName
        + ", Duration: " + durationInWeeks + " weeks");

Output:

text
Course: Java Foundation, Duration: 8 weeks

Concatenation and Calculation

Look at this code:

java
System.out.println("Total: " + 10 + 20);

Output:

text
Total: 1020

because evaluation happens from left to right:

text
"Total: " + 10
→ "Total: 10"

"Total: 10" + 20
→ "Total: 1020"

Use parentheses if the calculation should happen first:

java
System.out.println("Total: " + (10 + 20));

Output:

text
Total: 30

Length and Characters

To get the length of a String, use length():

java
String language = "Java";
System.out.println(language.length());

Output:

text
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:

text
String: Java
Index:  0123

charAt()

To get the character at a specific position, use charAt(). The last index is length - 1:

java
String language = "Java";
char firstCharacter = language.charAt(0);
char lastCharacter = language.charAt(language.length() - 1);
System.out.println(firstCharacter);
System.out.println(lastCharacter);

Output:

text
J
a

Invalid Index

The valid indexes of "Java" are 0, 1, 2 and 3, so this will fail at runtime:

java
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:

java
String value = "Java Foundation";
String language = value.substring(0, 4);
String secondPart = value.substring(5);
System.out.println(language);
System.out.println(secondPart);

Output:

text
Java
Foundation

toUpperCase() and toLowerCase()

java
String language = "Java";
System.out.println(language.toUpperCase());
System.out.println(language.toLowerCase());

Output:

text
JAVA
java

strip()

strip() removes whitespace from the beginning and end of a String:

java
String name = "   Sakib   ";
String cleanName = name.strip();
System.out.println(cleanName);

Output:

text
Sakib

Whitespace in the middle is not removed:

java
String name = "Sakib Sami";
System.out.println(name.strip());

Output:

text
Sakib Sami

contains()

contains() checks whether specific text exists inside a String. It is case-sensitive:

java
String courseName = "Java and OOP Foundation";
System.out.println(courseName.contains("OOP"));
System.out.println(courseName.contains("oop"));

Output:

text
true
false

startsWith() and endsWith()

These check the beginning and end of a String, for example a course name and a file name:

java
String courseName = "Java Foundation";
String fileName = "Main.java";
System.out.println(courseName.startsWith("Java"));
System.out.println(fileName.endsWith(".java"));

Output:

text
true
true

replace()

To replace text in a String:

java
String message = "I am learning Python";
String updatedMessage = message.replace("Python", "Java");
System.out.println(updatedMessage);

Output:

text
I am learning Java

Summary of Methods

MethodPurpose
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:

java
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:

text
true
false
true

Do Not Use == to Compare String Content

Look at the following example:

java
String firstValue = new String("Java");
String secondValue = new String("Java");
System.out.println(firstValue == secondValue);
System.out.println(firstValue.equals(secondValue));

Output:

text
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:

java
String language = "Java";
language.toUpperCase();
System.out.println(language);

Output:

text
Java

Why? toUpperCase() does not modify the original String. It returns a new String.

Store the Returned String

java
String language = "Java";
language = language.toUpperCase();
System.out.println(language);

Output:

text
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:

EscapeMeaning
\nNew line
\tTab
\"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:

java
System.out.println("Java\nFoundation");
System.out.println("He said, \"Learn Java.\"");
String path = "C:\\Java\\Projects";
System.out.println(path);

Output:

text
Java
Foundation
He said, "Learn Java."
C:\Java\Projects

\t inserts a tab, which is handy for lining up simple columns:

java
System.out.println("Name\tScore");
System.out.println("Sakib\t90");

Text Blocks

Java supports text blocks for writing readable multi-line text:

java
String message = """
        Java and OOP Foundation
        Language: Bangla
        Level: Beginner
        """;
System.out.println(message);

Output:

text
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:

java
char grade = 'A';
String courseName = "Java";
charString
Primitive typeReference type
Single UTF-16 code unitText sequence
Single quotesDouble quotes
'A'"A"

There Is No Empty char

Invalid:

java
char value = '';

But an empty String is valid:

java
String value = "";

Complete Example

java
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:

text
Course: Java and OOP Foundation
Length: 23
Starts with Java: true
Contains OOP: true
Uppercase: JAVA AND OOP FOUNDATION

Predict the Result

Question 1

java
System.out.println("Java " + 2 + 1);
System.out.println(2 + 1 + " Java");

What does this print?

Answer

text
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

java
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

java
String course = "Java Basics";
System.out.println(course.substring(5).length());
System.out.println(course.charAt(course.length() - 1));

What does this print?

Answer

text
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

java
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

text
false
true

After strip() the typed text is "sakib". equals() is case-sensitive, so "Sakib" and "sakib" differ; equalsIgnoreCase() ignores case.

Question 5

java
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:

java
String language = 'Java';

Correct:

java
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:

  1. Student name
  2. Course name
  3. Email address
  4. Country
  5. Error message

Practice Exercise 2: Empty, Blank, or null?

Classify each value:

java
String firstValue = "";
String secondValue = "   ";
String thirdValue = null;
String fourthValue = "Java";

Practice Exercise 3: Length and Index

For String language = "Java";, answer:

  1. What is the length?
  2. What is the index of the first character?
  3. What is the index of the last character?
  4. What does charAt(2) return?

Practice Exercise 4: Concatenation

Use these variables:

java
String firstName = "Sakib";
String lastName = "Sami";

Expected output:

text
Full name: Sakib Sami

Practice Exercise 5: Normalize Text

Use strip() and toUpperCase() on this input:

java
String rawName = "   md sakib   ";

to produce:

text
MD SAKIB

Practice Exercise 6: Compare Strings

Using these variables, print the .equals() result and the .equalsIgnoreCase() result:

java
String firstValue = "Java";
String secondValue = "java";

Practice Exercise 7: Fix the Immutability Issue

java
String language = "java";
language.toUpperCase();
System.out.println(language);

Expected output:

text
JAVA

Practice Exercise 8: Escape Sequence

Use a String to produce:

text
Course: "Java Foundation"
Path: C:\Java\Projects

Practice Exercise 9: Text Block

Use a text block to produce:

text
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

  • String represents 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, and null means 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 as length(), charAt(), substring(), strip() and replace() 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 উত্তর দেখানোর আগে আপনাকে একটি উত্তর বেছে নিতে হবে।