Programming and Java Fundamentals
Strings and Text Values
You are viewing a free preview lesson.
Lesson Overview
Text data is used almost everywhere in software applications.
For example:
- User name
- Email address
- Course title
- Product description
- Error message
- Search query
- Notification
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.
In this lesson, we will learn:
- What
Stringis - String literals
- Empty, blank, and
null - String concatenation
- String length and character access
- Common String methods
- String comparison
- String immutability
- Escape sequences
- Text blocks
- The difference between
Stringandchar
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]";
Here:
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
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:
"Java Foundation"
String Literal
Text written inside double quotes is a String literal.
"Java"
"Welcome to LiveKlass"
""
The last value is an empty String.
String Variable
To declare a variable:
String name;
To initialize it:
String name = "Sakib";
or:
String name;
name = "Sakib";
Empty String
An empty String contains no characters.
String value = "";
Length:
System.out.println(value.length());
Output:
0
Blank String
A blank String can be empty or contain only whitespace.
Examples:
""
" "
" "
You can check this using Java's isBlank() method:
String value = " ";
System.out.println(value.isBlank());
Output:
true
Difference Between Empty and Blank
String emptyValue = "";
String blankValue = " ";
System.out.println(emptyValue.isEmpty());
System.out.println(blankValue.isEmpty());
Output:
true
false
But:
System.out.println(emptyValue.isBlank());
System.out.println(blankValue.isBlank());
Output:
true
true
Difference:
isEmpty()→ checks whether the length is0isBlank()→ checks whether the String is empty or contains only whitespace
null
null means that the variable currently does not reference a String object.
String courseName = null;
This is not an empty String.
String emptyValue = "";
String missingValue = null;
Difference:
"" → 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:
String courseName = null;
System.out.println(courseName.length());
because courseName does not reference a String object.
This can cause a NullPointerException.
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()
To get the length of a String:
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 start from 0.
String: Java
Index: 0123
| Character | Index |
|---|---|
J | 0 |
a | 1 |
v | 2 |
a | 3 |
charAt()
To get the character at a specific position:
String language = "Java";
char firstCharacter = language.charAt(0);
System.out.println(firstCharacter);
Output:
J
Last Character
The last index is:
length - 1
Example:
String language = "Java";
char lastCharacter =
language.charAt(language.length() - 1);
System.out.println(lastCharacter);
Output:
a
Invalid Index
String language = "Java";
language.charAt(4);
This will fail at runtime.
The valid indexes are:
0
1
2
3
substring()
You can use substring() to extract part of a String.
String value = "Java Foundation";
String language = value.substring(0, 4);
System.out.println(language);
Output:
Java
Here:
- Start index
0is included - End index
4is excluded
From an Index to the End
String value = "Java Foundation";
String secondPart = value.substring(5);
System.out.println(secondPart);
Output:
Foundation
toUpperCase() and toLowerCase()
String language = "Java";
System.out.println(language.toUpperCase());
System.out.println(language.toLowerCase());
Output:
JAVA
java
strip()
To remove 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()
Checks whether specific text exists inside a String.
String courseName = "Java and OOP Foundation";
System.out.println(courseName.contains("OOP"));
Output:
true
It is case-sensitive.
System.out.println(courseName.contains("oop"));
Output:
false
startsWith() and endsWith()
String courseName = "Java Foundation";
System.out.println(
courseName.startsWith("Java")
);
Output:
true
File name example:
String fileName = "Main.java";
System.out.println(
fileName.endsWith(".java")
);
Output:
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
Common String 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.
String firstLanguage = "Java";
String secondLanguage = "Java";
System.out.println(
firstLanguage.equals(secondLanguage)
);
Output:
true
Case Matters
String firstLanguage = "Java";
String secondLanguage = "java";
System.out.println(
firstLanguage.equals(secondLanguage)
);
Output:
false
Compare While Ignoring Case
System.out.println(
firstLanguage.equalsIgnoreCase(secondLanguage)
);
Output:
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 |
New Line
System.out.println("Java\nFoundation");
Output:
Java
Foundation
Tab
System.out.println("Name\tScore");
System.out.println("Sakib\t90");
Double Quote
System.out.println(
"He said, \"Learn Java.\""
);
Output:
He said, "Learn Java."
Backslash
Windows path:
C:\Java\Projects
Java String:
String path = "C:\\Java\\Projects";
Text Blocks
Java supports text blocks for writing readable multi-line text.
String message = """
Java and OOP Foundation
Language: Bangla
Level: Beginner
""";
Print:
System.out.println(message);
Output:
Java and OOP Foundation
Language: Bangla
Level: Beginner
Text blocks can be useful for:
- Multi-line messages
- JSON
- SQL
- HTML
- Test data
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 = "";
Common Errors
Using Single Quotes for a String
Wrong:
String language = 'Java';
Correct:
String language = "Java";
Calling a Method on null
Wrong:
String value = null;
System.out.println(value.length());
This can cause a NullPointerException at runtime.
Comparing Content With ==
Avoid:
firstValue == secondValue
To compare content:
firstValue.equals(secondValue)
Ignoring the Returned String
Wrong expectation:
String value = "java";
value.toUpperCase();
System.out.println(value);
Output:
java
Correct:
value = value.toUpperCase();
Invalid Index
String value = "Java";
value.charAt(4);
This will fail at runtime.
Valid last index:
3
Concatenation Instead of Addition
System.out.println("Result: " + 10 + 20);
Output:
Result: 1020
Correct:
System.out.println(
"Result: " + (10 + 20)
);
Output:
Result: 30
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()
);
}
}
Possible output:
Course: Java and OOP Foundation
Length: 23
Starts with Java: true
Contains OOP: true
Uppercase: JAVA AND OOP FOUNDATION
Important Terms
String
A Java class used to represent a sequence of text.
String Literal
Text written inside double quotes.
"Java"
Empty String
A zero-length String.
""
Blank String
An empty or whitespace-only String.
null
The absence of an object reference.
Concatenation
Combining Strings and other values.
Index
A position inside a String, starting from 0.
Immutability
The property that an existing String object's content cannot be changed.
Escape Sequence
Syntax used to represent special characters inside a String.
Text Block
Syntax used to write multi-line Strings.
Practice Exercise 1: Create Strings
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
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
String firstName = "Sakib";
String lastName = "Sami";
Expected output:
Full name: Sakib Sami
Practice Exercise 5: Predict the Output
System.out.println("Result: " + 10 + 20);
System.out.println("Result: " + (10 + 20));
Practice Exercise 6: Normalize Text
Input:
String rawName = " md sakib ";
Use strip() and toUpperCase() to produce:
MD SAKIB
Practice Exercise 7: Compare Strings
String firstValue = "Java";
String secondValue = "java";
Print:
- The
.equals()result - The
.equalsIgnoreCase()result
Practice Exercise 8: Fix the Immutability Issue
String language = "java";
language.toUpperCase();
System.out.println(language);
Expected output:
JAVA
Practice Exercise 9: Escape Sequence
Use a String to produce:
Course: "Java Foundation"
Path: C:\Java\Projects
Practice Exercise 10: 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:
"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
In this lesson, we learned:
Stringrepresents textStringis not a primitive type- String literals are written inside double quotes
- Empty String, blank String, and
nullare different - Calling a method on
nullcan cause aNullPointerException +can be used to concatenate Strings- Parentheses help control the order of calculation and concatenation
length()returns the length of a String- String indexes start from
0 charAt()returns the character at a specific positionsubstring()returns part of a Stringstrip()removes surrounding whitespacecontains(),startsWith(), andendsWith()help inspect Stringsreplace()returns a new modified String.equals()should be used to compare String content.equalsIgnoreCase()can be used for case-insensitive comparison==should not be used for String content comparison- String is immutable
- String methods generally return new Strings instead of modifying the original
- Escape sequences represent special characters
- Text blocks help write readable multi-line text
Stringandcharare different types