Java for beginners
406 subscribers
49 photos
29 links
Learn Java daily with bite-sized lessons, practical code examples, output previews, and fun quizzes.
Download Telegram
🌟 **Day 9: String Manipulation in Java!** 🌟

Hello, future Java pros! 👋 Today, we're diving into one of the most fundamental and frequently used data types: **Strings**! ✨ From names and messages to URLs and file paths, strings are everywhere. Java's `String` class is incredibly powerful, offering a plethora of methods to manipulate text with ease.

Let's explore some essential string manipulation techniques that will make your code robust and dynamic. Get ready to slice, dice, and transform your text! 🚀

```java
public class StringManipulationDemo {
public static void main(String[] args) {
String originalText = " Hello Java Learners! Welcome to Day 9. ";

System.out.println("Original String: '" + originalText + "'");
System.out.println("Length of original: " + originalText.length());

// 1. Trimming whitespace
String trimmedText = originalText.trim();
System.out.println("Trimmed String: '" + trimmedText + "'");
System.out.println("Length after trim: " + trimmedText.length());

// 2. Getting a substring
// Substring from index 6 (inclusive) to 10 (exclusive)
System.out.println("Substring (index 6 to 10): " + trimmedText.substring(6, 10)); // "Java"

// 3. Finding the index of a character or substring
System.out.println("Index of 'Java': " + trimmedText.indexOf("Java")); // 6
System.out.println("Index of first 'e': " + trimmedText.indexOf('e')); // 1

// 4. Replacing parts of a string
String replacedText = trimmedText.replace("Java", "Awesome");
System.out.println("Text after replacing 'Java': " + replacedText);

// 5. Changing case
System.out.println("Uppercase: " + trimmedText.toUpperCase());
System.out.println("Lowercase: " + trimmedText.toLowerCase());

// 6. Checking if a string contains another string
System.out.println("Contains 'Learners'?: " + trimmedText.contains("Learners")); // true

// 7. Concatenating strings
String newGreeting = "Happy coding!";
System.out.println("Concatenated: " + trimmedText + " " + newGreeting);
}
}
```

Output example:
```
Original String: ' Hello Java Learners! Welcome to Day 9. '
Length of original: 44
Trimmed String: 'Hello Java Learners! Welcome to Day 9.'
Length after trim: 38
Substring (index 6 to 10): Java
Index of 'Java': 6
Index of first 'e': 1
Text after replacing 'Java': Hello Awesome Learners! Welcome to Day 9.
Uppercase: HELLO JAVA LEARNERS! WELCOME TO DAY 9.
Lowercase: hello java learners! welcome to day 9.
Contains 'Learners'?: true
Concatenated: Hello Java Learners! Welcome to Day 9. Happy coding!
```

**Small Challenge:** 💪
Take the string `"Coding is Fun and Powerful!"`. Write Java code to:
1. Extract the word "Fun".
2. Replace "Powerful" with "Creative".
3. Check if the modified string ends with "!".

Share your solutions or questions below! Happy learning! #Java #JavaLearning #StringManipulation #Programming #Day9

---