Programming and Java Fundamentals
Strings and Text Values
আপনি একটি free preview lesson দেখছেন।
Lesson Overview
Software application-এ text data অত্যন্ত গুরুত্বপূর্ণ।
উদাহরণ:
- User-এর নাম
- Email address
- Course title
- Product description
- Error message
- Address
- Search query
- API response
- Notification content
Java-তে text value represent করার জন্য সাধারণত String ব্যবহার করা হয়।
String primitive data type নয়। এটি Java standard library-এর একটি class। তবে Java-তে এত বেশি ব্যবহার করা হয় যে এটি অনেক সময় primitive type-এর মতো সহজ মনে হয়।
এই lesson-এ আমরা শিখব:
Stringকী- String literal
- String variable
- Empty String এবং blank String
null- String concatenation
- String length
- Character access
- Common String methods
- String comparison
==এবং.equals()-এর পার্থক্য- String immutability
- Escape sequence
- Text block
Stringএবংchar-এর পার্থক্য- Common String-related error
Learning Objectives
এই lesson শেষ করার পর আপনি পারবেন:
Stringকী, তা ব্যাখ্যা করতে- String variable declare এবং initialize করতে
- String literal ব্যবহার করতে
- Empty, blank এবং
nullString-এর পার্থক্য বুঝতে - একাধিক String concatenate করতে
- String-এর length বের করতে
- নির্দিষ্ট character access করতে
- Common String method ব্যবহার করতে
- String content compare করতে
==এবং.equals()-এর পার্থক্য ব্যাখ্যা করতে- String immutable হওয়ার অর্থ বুঝতে
- Escape sequence ব্যবহার করতে
- Multi-line text-এর জন্য text block ব্যবহার করতে
- Common String error শনাক্ত এবং fix করতে
What Is a String?
String হলো character-এর একটি sequence, যা text represent করে।
Example:
String courseName = "Java and OOP Foundation";
এখানে:
Stringহলো typecourseNameহলো variable name"Java and OOP Foundation"হলো String value
আরও example:
String studentName = "Sakib";
String email = "hello@liveklass.io";
String message = "Welcome to Java";
String country = "Bangladesh";
Is String a Primitive Type?
না।
Java-এর primitive type হলো:
byte
short
int
long
float
double
char
boolean
String একটি class।
Example:
String courseName = "Java Foundation";
এখানে courseName একটি reference-type variable।
তবে Java String literal-এর জন্য special syntax দেয়:
"Java Foundation"
এই কারণে String ব্যবহার করা তুলনামূলক সহজ।
String Literal
Double quotation marks-এর মধ্যে লেখা text-কে String literal বলা হয়।
Example:
"Java"
"Welcome to LiveKlass"
"Backend Development"
""
শেষ exampleটি empty String।
Declaring a String Variable
String name;
এখানে variable declare করা হয়েছে, কিন্তু value assign করা হয়নি।
Initialization:
String name = "Sakib";
Declaration এবং assignment আলাদাভাবে:
String name;
name = "Sakib";
Printing String Values
public class Main {
public static void main(String[] args) {
String courseName = "Java and OOP Foundation";
System.out.println(courseName);
}
}
Output:
Java and OOP Foundation
String Is Case-Sensitive
String content comparison-এ uppercase এবং lowercase আলাদা।
String firstValue = "Java";
String secondValue = "java";
Text দুটি দেখতে similar হলেও content exactভাবে same নয়।
Java
java
J এবং j আলাদা character।
Empty String
Empty String-এর মধ্যে কোনো character থাকে না।
String value = "";
এর length:
System.out.println(value.length());
Output:
0
Empty String একটি valid String object।
String Containing a Space
String value = " ";
এটি empty নয়।
এর মধ্যে একটি space character আছে।
System.out.println(value.length());
Output:
1
Difference:
String emptyValue = "";
String spaceValue = " ";
emptyValue length = 0
spaceValue length = 1
Blank String
Blank String এমন String, যার মধ্যে শুধু whitespace থাকতে পারে।
Examples:
""
" "
" "
"\t"
"\n"
Java-এর isBlank() method whitespace-only String শনাক্ত করতে পারে।
String value = " ";
System.out.println(value.isBlank());
Output:
true
Empty vs Blank
String firstValue = "";
String secondValue = " ";
Check:
System.out.println(firstValue.isEmpty());
System.out.println(firstValue.isBlank());
System.out.println(secondValue.isEmpty());
System.out.println(secondValue.isBlank());
Output:
true
true
false
true
Difference:
isEmpty()শুধু length0কি না check করেisBlank()empty বা whitespace-only কি না check করে
What Is null?
null বোঝায় variable বর্তমানে কোনো object reference করছে না।
Example:
String courseName = null;
এটি empty String নয়।
Difference:
String firstValue = "";
String secondValue = null;
firstValueএকটি valid empty String objectsecondValueকোনো String object reference করছে না
Empty String vs null
| Value | Meaning |
|---|---|
"" | String আছে, কিন্তু character নেই |
" " | String আছে এবং একটি space আছে |
null | কোনো String object reference নেই |
Calling a Method on null
Wrong:
String courseName = null;
System.out.println(courseName.length());
Runtime-এ NullPointerException হবে।
কারণ courseName কোনো String object reference করছে না।
Correct approach:
String courseName = null;
if (courseName != null) {
System.out.println(courseName.length());
}
Condition পরবর্তী lesson-এ বিস্তারিত শেখানো হবে।
Prefer Meaningful Initial Values
সব situation-এ null ব্যবহার করা প্রয়োজন নেই।
Example:
String courseName = "";
তবে empty String এবং missing value-এর meaning আলাদা হতে পারে।
Design করার সময় সিদ্ধান্ত নিতে হবে:
- Value absent হলে
null - Value present কিন্তু empty হলে
"" - User whitespace দিলে blank String
Real application-এ validation-এর সময় এই difference গুরুত্বপূর্ণ।
String Concatenation
একাধিক String বা value combine করাকে concatenation বলা হয়।
Java-তে + operator ব্যবহার করা যায়।
String firstName = "Sakib";
String lastName = "Sami";
String fullName = firstName + " " + lastName;
Output:
System.out.println(fullName);
Sakib Sami
Concatenating Text and Variables
String courseName = "Java Foundation";
System.out.println("Course: " + courseName);
Output:
Course: Java Foundation
Concatenating Multiple Values
String studentName = "Sakib";
int age = 20;
boolean active = true;
String information =
"Name: " + studentName
+ ", Age: " + age
+ ", Active: " + active;
System.out.println(information);
Output:
Name: Sakib, Age: 20, Active: true
Concatenation Is Evaluated Left to Right
Consider:
System.out.println("Total: " + 10 + 20);
Output:
Total: 1020
কেন?
Execution:
"Total: " + 10
→ "Total: 10"
"Total: 10" + 20
→ "Total: 1020"
Force the Calculation with Parentheses
System.out.println("Total: " + (10 + 20));
Output:
Total: 30
Parentheses-এর মধ্যে calculation আগে হয়েছে।
Numeric Addition Before String Concatenation
int firstNumber = 10;
int secondNumber = 20;
System.out.println(firstNumber + secondNumber + " is the total");
Output:
30 is the total
কারণ প্রথমে:
10 + 20 = 30
তারপর String concatenation হয়েছে।
Building Readable Output
Poor:
System.out.println("Course:" + courseName + "Duration:" + duration);
Possible output:
Course:Java FoundationDuration:8
Better:
System.out.println(
"Course: " + courseName
+ ", Duration: " + duration + " weeks"
);
Output:
Course: Java Foundation, Duration: 8 weeks
The length() Method
String-এর character count বের করতে length() ব্যবহার করা হয়।
String language = "Java";
int length = language.length();
System.out.println(length);
Output:
4
Characters:
J a v a
1 2 3 4
Spaces Are Counted
String courseName = "Java Foundation";
System.out.println(courseName.length());
Output:
15
Space-ও একটি character হিসেবে count হয়।
Empty String Length
String value = "";
System.out.println(value.length());
Output:
0
String Index
String-এর প্রতিটি character-এর একটি index থাকে।
Index শুরু হয়:
0
Example:
String: Java
Index: 0123
| Character | Index |
|---|---|
J | 0 |
a | 1 |
v | 2 |
a | 3 |
The charAt() Method
নির্দিষ্ট index-এর character পেতে charAt() ব্যবহার করা হয়।
String language = "Java";
char firstCharacter = language.charAt(0);
char secondCharacter = language.charAt(1);
System.out.println(firstCharacter);
System.out.println(secondCharacter);
Output:
J
a
Accessing the Last Character
Last index:
length - 1
Example:
String language = "Java";
char lastCharacter =
language.charAt(language.length() - 1);
System.out.println(lastCharacter);
Output:
a
Invalid String Index
String language = "Java";
System.out.println(language.charAt(4));
Runtime error হবে।
Valid index:
0 to 3
কারণ length 4, কিন্তু last index 3।
Possible exception:
StringIndexOutOfBoundsException
The substring() Method
String-এর একটি অংশ বের করতে substring() ব্যবহার করা হয়।
String language = "Java Programming";
String firstPart = language.substring(0, 4);
System.out.println(firstPart);
Output:
Java
Start Index Included, End Index Excluded
substring(0, 4)
এখানে:
- Index
0included - Index
4excluded
Characters:
J a v a
0 1 2 3
Substring from an Index to the End
String value = "Java Programming";
String secondPart = value.substring(5);
System.out.println(secondPart);
Output:
Programming
The toUpperCase() Method
String language = "Java";
String upperCaseValue = language.toUpperCase();
System.out.println(upperCaseValue);
Output:
JAVA
The toLowerCase() Method
String language = "Java";
String lowerCaseValue = language.toLowerCase();
System.out.println(lowerCaseValue);
Output:
java
The trim() Method
trim() String-এর শুরু এবং শেষের কিছু traditional whitespace remove করে।
String name = " Sakib ";
String trimmedName = name.trim();
System.out.println(trimmedName);
Output:
Sakib
Middle space remove হয় না।
String name = "Sakib Sami";
System.out.println(name.trim());
Output:
Sakib Sami
The strip() Method
Modern Java-তে strip() Unicode-aware whitespace remove করতে পারে।
String value = " Java ";
System.out.println(value.strip());
Output:
Java
Related methods:
strip()
stripLeading()
stripTrailing()
stripLeading()
শুরুর whitespace remove করে।
String value = " Java ";
System.out.println(value.stripLeading());
Ending spaces remain করতে পারে।
stripTrailing()
শেষের whitespace remove করে।
String value = " Java ";
System.out.println(value.stripTrailing());
Starting spaces remain করতে পারে।
The contains() Method
String-এর মধ্যে নির্দিষ্ট sequence আছে কি না check করে।
String courseName = "Java and OOP Foundation";
boolean containsJava = courseName.contains("Java");
System.out.println(containsJava);
Output:
true
Case-sensitive:
System.out.println(courseName.contains("java"));
Output:
false
The startsWith() Method
String courseName = "Java Foundation";
System.out.println(courseName.startsWith("Java"));
Output:
true
The endsWith() Method
String fileName = "Main.java";
System.out.println(fileName.endsWith(".java"));
Output:
true
Practical use:
- File extension check
- URL pattern check
- Prefix validation
- Domain validation
The replace() Method
Text replace করতে replace() ব্যবহার করা যায়।
String message = "I am learning Python";
String updatedMessage =
message.replace("Python", "Java");
System.out.println(updatedMessage);
Output:
I am learning Java
Original String change হয় না।
Replacing Characters
String value = "Java";
String updatedValue = value.replace('a', 'o');
System.out.println(updatedValue);
Output:
Jovo
সব matching character replace হয়েছে।
The indexOf() Method
নির্দিষ্ট character বা text প্রথম কোথায় আছে, তার index return করে।
String language = "Java";
System.out.println(language.indexOf('a'));
Output:
1
a প্রথম index 1-এ পাওয়া গেছে।
Searching for Text
String courseName = "Java and OOP Foundation";
System.out.println(courseName.indexOf("OOP"));
Output:
9
Value Not Found
String language = "Java";
System.out.println(language.indexOf("Python"));
Output:
-1
-1 বোঝায় value পাওয়া যায়নি।
The lastIndexOf() Method
শেষ occurrence-এর index return করে।
String language = "Java";
System.out.println(language.lastIndexOf('a'));
Output:
3
The isEmpty() Method
String-এর length 0 কি না check করে।
String value = "";
System.out.println(value.isEmpty());
Output:
true
The isBlank() Method
String empty বা শুধু whitespace কি না check করে।
String value = " ";
System.out.println(value.isBlank());
Output:
true
The repeat() Method
String একাধিকবার repeat করতে ব্যবহার করা যায়।
String separator = "=".repeat(20);
System.out.println(separator);
Output:
====================
আরেকটি example:
System.out.println("Java ".repeat(3));
Output:
Java Java Java
The concat() Method
String concatenate করার জন্য concat() ব্যবহার করা যায়।
String firstName = "Sakib";
String lastName = "Sami";
String fullName =
firstName.concat(" ").concat(lastName);
System.out.println(fullName);
Output:
Sakib Sami
সাধারণ code-এ + operator বেশি readable হতে পারে।
Common String Methods
| Method | Purpose |
|---|---|
length() | Character count |
charAt(index) | নির্দিষ্ট character |
substring() | String-এর অংশ |
toUpperCase() | Uppercase |
toLowerCase() | Lowercase |
trim() | Basic surrounding whitespace remove |
strip() | Unicode-aware surrounding whitespace remove |
contains() | Text আছে কি না |
startsWith() | Prefix check |
endsWith() | Suffix check |
replace() | Text replace |
indexOf() | First matching index |
lastIndexOf() | Last matching index |
isEmpty() | Length 0 কি না |
isBlank() | Empty বা whitespace-only কি না |
repeat() | Repeat করা |
concat() | String combine করা |
Comparing Strings
String content compare করার জন্য .equals() ব্যবহার করা উচিত।
String firstLanguage = "Java";
String secondLanguage = "Java";
boolean same =
firstLanguage.equals(secondLanguage);
System.out.println(same);
Output:
true
Case-Sensitive Comparison
String firstLanguage = "Java";
String secondLanguage = "java";
System.out.println(
firstLanguage.equals(secondLanguage)
);
Output:
false
Case-Insensitive Comparison
String firstLanguage = "Java";
String secondLanguage = "java";
System.out.println(
firstLanguage.equalsIgnoreCase(secondLanguage)
);
Output:
true
Why Not Use == for String Content?
== reference compare করতে পারে, content নয়।
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
Explanation:
==check করে references একই object নির্দেশ করছে কি না.equals()check করে String content একই কি না
String Pool
String literal Java-এর String pool-এ reuse হতে পারে।
String firstValue = "Java";
String secondValue = "Java";
System.out.println(firstValue == secondValue);
Output অনেক ক্ষেত্রে:
true
কারণ দুটি literal একই pooled String reference করতে পারে।
তবে এই behaviour-এর ওপর content comparison depend করা উচিত নয়।
Always use:
firstValue.equals(secondValue)
Safe String Comparison with Possible null
Risky:
String status = null;
System.out.println(status.equals("ACTIVE"));
Runtime-এ NullPointerException হবে।
Safer:
System.out.println("ACTIVE".equals(status));
যদি status null হয়, result:
false
কারণ literal "ACTIVE" null নয়।
Using Objects.equals()
Java utility method:
Objects.equals(firstValue, secondValue)
Example:
import java.util.Objects;
public class Main {
public static void main(String[] args) {
String firstValue = null;
String secondValue = null;
System.out.println(
Objects.equals(firstValue, secondValue)
);
}
}
Output:
true
এটি null-safe comparison দেয়।
String Immutability
Java String immutable।
এর অর্থ:
String object তৈরি হওয়ার পর তার content পরিবর্তন করা যায় না।
Example:
String language = "Java";
language.toUpperCase();
System.out.println(language);
Output:
Java
toUpperCase() original String change করেনি।
Store the Returned String
String language = "Java";
language = language.toUpperCase();
System.out.println(language);
Output:
JAVA
toUpperCase() একটি নতুন String return করেছে, সেটি variable-এ assign করা হয়েছে।
More Immutability Examples
String message = "Hello";
message.concat(" Java");
System.out.println(message);
Output:
Hello
Correct:
message = message.concat(" Java");
System.out.println(message);
Output:
Hello Java
Why Is String Immutable?
String immutable হওয়ার সুবিধা:
- Thread safety improve হয়
- String pool safe থাকে
- Hash-based collection reliable হয়
- Security-sensitive value stable থাকে
- Shared String accidentally change হয় না
- Caching সহজ হয়
String immutability Java design-এর গুরুত্বপূর্ণ অংশ।
Repeated Concatenation and Performance
ছোট concatenation-এর জন্য + ব্যবহার করা ভালো।
String fullName = firstName + " " + lastName;
কিন্তু loop-এর মধ্যে অনেকবার String concatenate করলে অনেক intermediate String object তৈরি হতে পারে।
Example:
String result = "";
for (int i = 0; i < 1000; i++) {
result = result + i;
}
এই ধরনের case-এ StringBuilder বেশি efficient হতে পারে।
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 1000; i++) {
builder.append(i);
}
String result = builder.toString();
StringBuilder future lesson বা module-এ বিস্তারিত শেখানো হবে।
Escape Sequences
String literal-এর মধ্যে special character লেখার জন্য escape sequence ব্যবহার করা হয়।
Escape sequence backslash দিয়ে শুরু হয়:
\
New Line: \n
System.out.println("Java\nFoundation");
Output:
Java
Foundation
Tab: \t
System.out.println("Name\tScore");
System.out.println("Sakib\t90");
Possible output:
Name Score
Sakib 90
Double Quote: \"
System.out.println(
"He said, \"Learn Java.\""
);
Output:
He said, "Learn Java."
Backslash: \\
System.out.println(
"C:\\Java\\Projects"
);
Output:
C:\Java\Projects
Carriage Return: \r
String value = "Hello\rJava";
Behaviour environment অনুযায়ী ভিন্নভাবে display হতে পারে।
সাধারণ text formatting-এর জন্য \n বেশি predictable।
Backspace: \b
String value = "Javaa\b";
Console rendering environment অনুযায়ী result ভিন্ন হতে পারে।
Common Escape Sequences
| Escape | Meaning |
|---|---|
\n | New line |
\t | Tab |
\" | Double quote |
\' | Single quote |
\\ | Backslash |
\r | Carriage return |
\b | Backspace |
File Path Example
Windows path:
C:\Users\Sakib\Projects
Java String:
String path =
"C:\\Users\\Sakib\\Projects";
কারণ single backslash escape sequence শুরু করতে পারে।
URL Does Not Need Escaped Forward Slashes
String website = "https://liveklass.io";
Forward slash / escape করার প্রয়োজন নেই।
Multi-Line String Before Text Blocks
Text block ছাড়া multi-line content:
String message =
"Java and OOP Foundation\n"
+ "Language: Bangla\n"
+ "Level: Beginner";
Output:
Java and OOP Foundation
Language: Bangla
Level: Beginner
এটি valid, কিন্তু বড় multi-line text-এর জন্য verbose হতে পারে।
Text Blocks
Modern Java-তে multi-line String লেখার জন্য text block ব্যবহার করা যায়।
Syntax:
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 Block Opening and Closing
Text block triple double quotes ব্যবহার করে:
"""
Example:
String html = """
<h1>Java Foundation</h1>
<p>Learn Java in Bangla.</p>
""";
Text Block for JSON
String json = """
{
"course": "Java Foundation",
"language": "Bangla",
"available": true
}
""";
System.out.println(json);
Text block JSON, SQL, HTML এবং formatted message-এর জন্য useful।
Text Block Indentation
Java common indentation remove করতে পারে।
Example:
String message = """
First line
Second line
Third line
""";
Output cleanভাবে aligned হতে পারে।
Text block-এর exact indentation rule বুঝতে practice করা দরকার।
String and char
String এবং char আলাদা type।
char grade = 'A';
String gradeText = "A";
Difference:
char | String |
|---|---|
| Primitive type | Reference type |
| Single UTF-16 code unit | Character sequence |
| Single quotes | Double quotes |
Example: 'A' | Example: "A" |
Empty Character Is Not Valid
Invalid:
char value = '';
কারণ char-এ একটি character প্রয়োজন।
কিন্তু empty String valid:
String value = "";
Converting char to String
char grade = 'A';
String gradeText =
String.valueOf(grade);
System.out.println(gradeText);
Output:
A
Alternative:
String gradeText = Character.toString(grade);
Converting String to char
String-এর প্রথম character:
String gradeText = "A";
char grade = gradeText.charAt(0);
তবে String empty হলে charAt(0) error করবে।
String Formatting with formatted()
Modern Java-তে template-like text তৈরি করতে formatted() ব্যবহার করা যায়।
String courseName = "Java Foundation";
int duration = 8;
String message =
"Course: %s, Duration: %d weeks"
.formatted(courseName, duration);
System.out.println(message);
Output:
Course: Java Foundation, Duration: 8 weeks
Common Format Specifiers
| Specifier | Meaning |
|---|---|
%s | String |
%d | Integer |
%f | Floating-point |
%b | Boolean |
%c | Character |
Example:
String result =
"Name: %s, Score: %d, Passed: %b"
.formatted("Sakib", 90, true);
System.out.println(result);
Output:
Name: Sakib, Score: 90, Passed: true
Decimal Formatting
double average = 81.666666;
String message =
"Average: %.2f".formatted(average);
System.out.println(message);
Output:
Average: 81.67
%.2f দুই decimal place দেখায়।
String.format()
Alternative:
String message = String.format(
"Course: %s, Duration: %d weeks",
"Java Foundation",
8
);
Output:
Course: Java Foundation, Duration: 8 weeks
Splitting a String
split() ব্যবহার করে String-কে multiple part-এ ভাগ করা যায়।
String languages = "Java,Go,Python";
String[] values = languages.split(",");
Conceptually:
values[0] = Java
values[1] = Go
values[2] = Python
Print:
System.out.println(values[0]);
System.out.println(values[1]);
System.out.println(values[2]);
Output:
Java
Go
Python
Array future lesson-এ বিস্তারিত শেখানো হবে।
Joining Strings
String.join() multiple String combine করতে পারে।
String result = String.join(
", ",
"Java",
"Go",
"Python"
);
System.out.println(result);
Output:
Java, Go, Python
Converting Other Values to String
Integer to String
int age = 30;
String ageText = String.valueOf(age);
Double to String
double price = 99.50;
String priceText = String.valueOf(price);
Boolean to String
boolean active = true;
String activeText = String.valueOf(active);
Automatic String Conversion During Concatenation
int age = 30;
String message = "Age: " + age;
Java age value text-এ convert করে concatenation করে।
Output:
Age: 30
Parsing String into Numbers
String থেকে number convert করতে wrapper method ব্যবহার করা হয়।
String ageText = "30";
int age = Integer.parseInt(ageText);
String priceText = "99.50";
double price = Double.parseDouble(priceText);
এগুলো type conversion lesson-এ বিস্তারিত শেখানো হবে।
Invalid Numeric Text
String ageText = "thirty";
int age = Integer.parseInt(ageText);
Runtime-এ NumberFormatException হবে।
কারণ "thirty" valid integer format নয়।
Example: Course Information
public class Main {
public static void main(String[] args) {
String courseName =
"Java and OOP Foundation";
String language = "Bangla";
String level = "Beginner";
int durationInWeeks = 8;
int lessonCount = 21;
String courseInformation =
"Course: " + courseName + "\n"
+ "Language: " + language + "\n"
+ "Level: " + level + "\n"
+ "Duration: "
+ durationInWeeks
+ " weeks\n"
+ "Lessons: " + lessonCount;
System.out.println(courseInformation);
}
}
Output:
Course: Java and OOP Foundation
Language: Bangla
Level: Beginner
Duration: 8 weeks
Lessons: 21
Example with Text Block
public class Main {
public static void main(String[] args) {
String courseName =
"Java and OOP Foundation";
String language = "Bangla";
int durationInWeeks = 8;
String template = """
Course: %s
Language: %s
Duration: %d weeks
""";
String result = template.formatted(
courseName,
language,
durationInWeeks
);
System.out.println(result);
}
}
Output:
Course: Java and OOP Foundation
Language: Bangla
Duration: 8 weeks
Example: Name Processing
public class Main {
public static void main(String[] args) {
String rawName = " Md Sakib ";
String cleanName = rawName.strip();
System.out.println(
"Original length: " + rawName.length()
);
System.out.println(
"Clean length: " + cleanName.length()
);
System.out.println(
"Uppercase: " + cleanName.toUpperCase()
);
System.out.println(
"Lowercase: " + cleanName.toLowerCase()
);
}
}
Example: Email Inspection
public class Main {
public static void main(String[] args) {
String email = "hello@liveklass.io";
boolean containsAt =
email.contains("@");
boolean validDomain =
email.endsWith("liveklass.io");
int atPosition =
email.indexOf('@');
System.out.println(
"Contains @: " + containsAt
);
System.out.println(
"Valid domain: " + validDomain
);
System.out.println(
"@ position: " + atPosition
);
}
}
Example: File Name Inspection
public class Main {
public static void main(String[] args) {
String fileName = "Main.java";
boolean javaFile =
fileName.endsWith(".java");
String className =
fileName.replace(".java", "");
System.out.println(
"Java file: " + javaFile
);
System.out.println(
"Class name: " + className
);
}
}
Output:
Java file: true
Class name: Main
Common Error: Using Single Quotes for String
Wrong:
String language = 'Java';
Correct:
String language = "Java";
Common Error: Using Double Quotes for char
Wrong:
char grade = "A";
Correct:
char grade = 'A';
Common Error: Calling Method on null
Wrong:
String value = null;
System.out.println(value.length());
Runtime-এ NullPointerException হবে।
Common Error: Comparing with ==
Risky:
String firstValue = new String("Java");
String secondValue = new String("Java");
System.out.println(firstValue == secondValue);
Content same হলেও result false হতে পারে।
Correct:
System.out.println(
firstValue.equals(secondValue)
);
Common Error: Ignoring Returned String
Wrong:
String value = "java";
value.toUpperCase();
System.out.println(value);
Output:
java
Correct:
value = value.toUpperCase();
Common Error: Invalid Index
String value = "Java";
System.out.println(value.charAt(4));
Valid last index 3।
Correct:
System.out.println(value.charAt(3));
Common Error: Wrong Substring Range
String value = "Java";
System.out.println(value.substring(3, 1));
Start index end index-এর চেয়ে বড়।
Runtime error হতে পারে।
Correct:
System.out.println(value.substring(1, 3));
Output:
av
Common Error: Empty String with charAt()
String value = "";
System.out.println(value.charAt(0));
Runtime error হবে, কারণ কোনো character নেই।
Check:
if (!value.isEmpty()) {
System.out.println(value.charAt(0));
}
Common Error: Concatenation Instead of Addition
System.out.println(
"Result: " + 10 + 20
);
Output:
Result: 1020
Correct:
System.out.println(
"Result: " + (10 + 20)
);
Output:
Result: 30
Common Error: Forgetting to Escape Quotes
Wrong:
String message =
"He said, "Learn Java."";
Correct:
String message =
"He said, \"Learn Java.\"";
Common Error: Windows Path
Wrong:
String path =
"C:\Java\Projects";
Backslash escape sequence হিসেবে interpret হতে পারে।
Correct:
String path =
"C:\\Java\\Projects";
Common Error: Assuming trim() Changes the Original
Wrong expectation:
String name = " Sakib ";
name.trim();
System.out.println(name);
Output এখনও spacesসহ থাকবে।
Correct:
name = name.trim();
String Validation Basics
Real application-এ user input validate করতে হয়।
Example:
String courseName = " ";
boolean missing =
courseName == null
|| courseName.isBlank();
এখানে check করা হচ্ছে:
- Value null কি না
- Empty বা whitespace-only কি না
Condition এবং logical operator পরবর্তী lessonগুলোতে বিস্তারিত শেখানো হবে।
Prefer .isBlank() for User Text
User শুধু spaces দিলে:
String userInput = " ";
isEmpty() false:
userInput.isEmpty()
কিন্তু isBlank() true:
userInput.isBlank()
Form validation-এর জন্য অনেক ক্ষেত্রে isBlank() বেশি useful।
Normalize Text Before Comparison
User input:
String input = " JAVA ";
Normalize:
String normalized =
input.strip().toLowerCase();
Result:
java
Comparison:
boolean isJava =
normalized.equals("java");
Locale Consideration
toLowerCase() এবং toUpperCase() কিছু language-specific case rule-এর ওপর নির্ভর করতে পারে।
Server-side normalization-এর ক্ষেত্রে explicit locale ব্যবহার করা যেতে পারে:
import java.util.Locale;
String normalized =
input.toLowerCase(Locale.ROOT);
Beginner হিসেবে basic toLowerCase() যথেষ্ট, তবে production code-এ locale-sensitive behaviour জানা গুরুত্বপূর্ণ।
String Method Chaining
একাধিক method chain করা যায়।
String value = " Java Foundation ";
String normalized =
value.strip().toUpperCase();
System.out.println(normalized);
Output:
JAVA FOUNDATION
Execution:
strip()- New String return
toUpperCase()- Final String assign
Readable Method Chaining
Long chain readableভাবে break করা যায়:
String normalized =
value
.strip()
.toLowerCase()
.replace(" ", "-");
Input:
Java Foundation
Output:
java-foundation
Important Terms
String
Character sequence represent করা Java class।
String Literal
Double quotes-এর মধ্যে লেখা text।
"Java"
Empty String
কোনো character নেই এমন String।
""
Blank String
Empty বা শুধু whitespace থাকা String।
null
কোনো object reference নেই।
Concatenation
একাধিক String বা value combine করা।
Index
String-এর character position, যা 0 থেকে শুরু হয়।
Immutability
Object তৈরি হওয়ার পর তার content পরিবর্তন না হওয়া।
String Pool
String literal reuse করার JVM-managed area।
Escape Sequence
String literal-এর মধ্যে special character represent করার syntax।
Text Block
Triple quotes ব্যবহার করে multi-line String লেখার syntax।
equals()
String content compare করে।
equalsIgnoreCase()
Case ignore করে String content compare করে।
substring()
String-এর একটি অংশ return করে।
strip()
String-এর শুরু ও শেষের Unicode whitespace remove করে।
isEmpty()
String-এর length 0 কি না check করে।
isBlank()
String empty বা whitespace-only কি না check করে।
Method Chaining
একটি returned object-এর ওপর ধারাবাহিকভাবে method call করা।
Practice Exercise 1: Create String Variables
নিচের information-এর জন্য String variable তৈরি করুন:
- Student name
- Course name
- Email address
- Country
- Error message
- Website URL
Meaningful camelCase name ব্যবহার করুন।
Practice Exercise 2: Empty, Blank, or Null
প্রতিটি value empty, blank নাকি null, তা লিখুন:
String firstValue = "";
String secondValue = " ";
String thirdValue = " ";
String fourthValue = null;
String fifthValue = "Java";
Practice Exercise 3: Predict the Length
Output predict করুন:
System.out.println("Java".length());
System.out.println("Java Foundation".length());
System.out.println("".length());
System.out.println(" ".length());
Practice Exercise 4: Character Index
String:
String language = "Java";
উত্তর দিন:
J-এর index কত?v-এর index কত?- Last character-এর index কত?
charAt(2)কী return করবে?charAt(4)করলে কী হবে?
Practice Exercise 5: First and Last Character
একটি program লিখুন, যা নিচের String-এর first এবং last character print করবে:
String courseName = "Foundation";
Expected output:
First character: F
Last character: n
Practice Exercise 6: Concatenation
Variables:
String firstName = "Sakib";
String lastName = "Sami";
Expected output:
Full name: Sakib Sami
Complete Java code লিখুন।
Practice Exercise 7: Addition or Concatenation
Output predict করুন:
System.out.println("Result: " + 10 + 20);
System.out.println("Result: " + (10 + 20));
System.out.println(10 + 20 + " is the result");
Practice Exercise 8: Normalize a Name
Input:
String rawName = " md sakib ";
Method ব্যবহার করে output তৈরি করুন:
MD SAKIB
Hint:
strip()toUpperCase()
Practice Exercise 9: Check File Extension
String fileName = "Course.java";
Program লিখুন, যা check করবে fileটি .java দিয়ে শেষ হয়েছে কি না।
Expected output:
Java file: true
Practice Exercise 10: Replace Text
Input:
String message = "I am learning Python";
Expected output:
I am learning Java
replace() ব্যবহার করুন।
Practice Exercise 11: Compare Strings
নিচের code-এর output predict করুন:
String firstValue = "Java";
String secondValue = "java";
System.out.println(
firstValue.equals(secondValue)
);
System.out.println(
firstValue.equalsIgnoreCase(secondValue)
);
Practice Exercise 12: == vs .equals()
নিচের code run করুন:
String firstValue =
new String("Java");
String secondValue =
new String("Java");
System.out.println(
firstValue == secondValue
);
System.out.println(
firstValue.equals(secondValue)
);
নিজের ভাষায় result explain করুন।
Practice Exercise 13: Fix the Immutability Issue
নিচের code uppercase output দিচ্ছে না:
String language = "java";
language.toUpperCase();
System.out.println(language);
Expected output:
JAVA
Code fix করুন।
Practice Exercise 14: Escape Sequences
একটি String statement ব্যবহার করে নিচের output তৈরি করুন:
Course: "Java Foundation"
Path: C:\Java\Projects
Hint:
\"\\\n
Practice Exercise 15: Text Block
Text block ব্যবহার করে নিচের output তৈরি করুন:
Course: Java and OOP Foundation
Language: Bangla
Level: Beginner
Duration: 8 weeks
Practice Exercise 16: Format a Result
Variables:
String studentName = "Sakib";
int totalMarks = 255;
double average = 85.0;
boolean passed = true;
formatted() ব্যবহার করে output তৈরি করুন:
Student: Sakib
Total: 255
Average: 85.00
Passed: true
Practice Exercise 17: Split a String
Input:
String languages = "Java,Go,Python";
split() ব্যবহার করে প্রতিটি language আলাদা line-এ print করুন।
Expected output:
Java
Go
Python
Practice Exercise 18: Join Strings
String.join() ব্যবহার করে নিচের output তৈরি করুন:
Java -> Spring Boot -> Backend
Values:
Java
Spring Boot
Backend
Practice Exercise 19: Safe Null Comparison
নিচের code fix করুন:
String status = null;
if (status.equals("ACTIVE")) {
System.out.println("Active");
}
Codeটি যেন NullPointerException না দেয়।
Practice Exercise 20: String Inspection Program
নিচের String ব্যবহার করুন:
String courseName =
"Java and OOP Foundation";
Programটি print করবে:
- Length
- First character
- Last character
- Contains
"OOP"কি না - Starts with
"Java"কি না - Ends with
"Foundation"কি না - Uppercase version
- Lowercase version
Practice Exercise 21: Validate User Input
Input:
String userInput = " ";
Program লিখুন, যা print করবে:
Input empty: false
Input blank: true
Practice Exercise 22: Convert Values to String
নিচের valueগুলো String-এ convert করুন:
int age = 30;
double price = 4990.50;
boolean active = true;
char grade = 'A';
String.valueOf() ব্যবহার করুন।
Practice Exercise 23: Parse Numeric Strings
String values:
String ageText = "30";
String priceText = "4990.50";
Convert করুন:
ageText→intpriceText→double
তারপর calculation করুন:
Age next year: 31
Price after adding 100: 5090.5
Practice Exercise 24: Explain the Error
নিচের code-এ কী error হতে পারে?
String value = "";
System.out.println(value.charAt(0));
Reason এবং safe version লিখুন।
Practice Exercise 25: Explain in Your Own Words
নিজের ভাষায় উত্তর দিন:
Stringকী?Stringকি primitive type?- Empty String এবং
null-এর পার্থক্য কী? - Blank String কী?
- String index কোথা থেকে শুরু হয়?
length()কী করে?charAt()কী করে?substring()-এর end index included কি?.equals()কেন ব্যবহার করা হয়?- String content compare করতে
==risky কেন? - String immutable হওয়ার অর্থ কী?
strip()এবংisBlank()কী কাজে লাগে?- Text block কেন useful?
Stringএবংchar-এর পার্থক্য কী?- Repeated concatenation-এর জন্য
StringBuilderকেন useful?
Knowledge Check
Question 1
String কী?
Question 2
String কি primitive data type?
Question 3
String literal কোন quotation mark ব্যবহার করে?
Question 4
Empty String কী?
Question 5
Blank String কী?
Question 6
null কী বোঝায়?
Question 7
null String-এর ওপর method call করলে কী হতে পারে?
Question 8
String concatenation-এর জন্য কোন operator ব্যবহার করা যায়?
Question 9
"Total: " + 10 + 20-এর result কী?
Question 10
Calculation আগে করাতে কী ব্যবহার করা যায়?
Question 11
String-এর length কোন method দেয়?
Question 12
String index কোথা থেকে শুরু হয়?
Question 13
Last character-এর index কীভাবে বের করা যায়?
Question 14
charAt() কী করে?
Question 15
substring(0, 4)-এ index 4 included কি?
Question 16
String content compare করার recommended method কী?
Question 17
Case ignore করে compare করার method কী?
Question 18
== String-এর ক্ষেত্রে কী compare করতে পারে?
Question 19
String immutable হওয়ার অর্থ কী?
Question 20
toUpperCase() কি original String modify করে?
Question 21
isEmpty() কী check করে?
Question 22
isBlank() কী check করে?
Question 23
contains() কি case-sensitive?
Question 24
indexOf() value না পেলে কী return করে?
Question 25
Multi-line String-এর modern syntax কী?
Question 26
Single backslash String-এ সরাসরি লেখার সমস্যা কী?
Question 27
String এবং char-এর quotation mark কীভাবে আলাদা?
Question 28
String method chain করা যায় কি?
Question 29
Repeated String concatenation-এর জন্য কোন class useful?
Question 30
String থেকে integer parse করার method কী?
Knowledge Check Answers
Answer 1
String হলো character sequence represent করা Java class।
Answer 2
না। String একটি reference type এবং class।
Answer 3
Double quotes:
"Java"
Answer 4
Zero character থাকা valid String:
""
Answer 5
Empty বা শুধু whitespace থাকা String-কে blank String বলা হয়।
Answer 6
null বোঝায় variable কোনো object reference করছে না।
Answer 7
NullPointerException হতে পারে।
Answer 8
+ operator।
Answer 9
Total: 1020
Answer 10
Parentheses:
"Total: " + (10 + 20)
Answer 11
length()
Answer 12
Index 0 থেকে শুরু হয়।
Answer 13
value.length() - 1
Answer 14
নির্দিষ্ট index-এর character return করে।
Answer 15
না। End index excluded।
Answer 16
equals()
Answer 17
equalsIgnoreCase()
Answer 18
== সাধারণত reference identity compare করে।
Answer 19
String object তৈরি হওয়ার পর তার content পরিবর্তন করা যায় না।
Answer 20
না। এটি নতুন String return করে।
Answer 21
String-এর length 0 কি না।
Answer 22
String empty বা whitespace-only কি না।
Answer 23
হ্যাঁ।
Answer 24
-1
Answer 25
Text block:
"""
Multi-line text
"""
Answer 26
Backslash escape sequence শুরু করে। Literal backslash-এর জন্য \\ লিখতে হয়।
Answer 27
String double quotes এবং char single quotes ব্যবহার করে।
Answer 28
হ্যাঁ।
Example:
value.strip().toLowerCase()
Answer 29
StringBuilder
Answer 30
Integer.parseInt()
Lesson Summary
এই lesson-এ আমরা শিখেছি:
Stringtext represent করেStringprimitive নয়, এটি একটি class- String literal double quotes-এর মধ্যে লেখা হয়
- Empty String, blank String এবং
nullআলাদা null-এর ওপর method call করলেNullPointerExceptionহতে পারে+operator দিয়ে String concatenate করা যায়- Concatenation left-to-right execute হয়
- Parentheses calculation order control করে
length()character count দেয়- String index
0থেকে শুরু হয় charAt()নির্দিষ্ট character দেয়substring()String-এর একটি অংশ দেয়toUpperCase()এবংtoLowerCase()নতুন String return করেstrip()surrounding whitespace remove করেcontains(),startsWith()এবংendsWith()text inspect করেreplace()matching text replace করেindexOf()position দেয় এবং না পেলে-1return করেisEmpty()এবংisBlank()আলাদা condition check করে- String content compare করতে
.equals()ব্যবহার করা উচিত - Case-insensitive comparison-এর জন্য
.equalsIgnoreCase() ==String content comparison-এর জন্য reliable নয়- String immutable
- String method original value change না করে নতুন String return করে
- Escape sequence special character represent করে
- Text block multi-line text readableভাবে লেখে
Stringএবংcharআলাদা typeformatted()structured output তৈরি করতে সাহায্য করেsplit()String ভাগ করেString.join()multiple String combine করে- String থেকে number parse করা যায়
- Repeated concatenation-এর জন্য
StringBuilderবেশি efficient হতে পারে - User input validate করার সময় null, empty এবং blank আলাদাভাবে বিবেচনা করা প্রয়োজন
Next Lesson
পরবর্তী lesson-এ আমরা Java operators এবং expressions শিখব।
আমরা জানব:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Unary operators
- Increment এবং decrement
- Operator precedence
- Parentheses
- Integer এবং decimal expression
- Short-circuit evaluation
- String concatenation
- Common operator-related error