Share this with your friends so they also get benefits.
https://t.me/java_for_beginner
https://t.me/java_for_beginner
Telegram
Java for beginners
Learn Java daily with bite-sized lessons, practical code examples, output previews, and fun quizzes.
๐ **Day 1: Introduction to Java with Hello World!** ๐
๐ Welcome to the very first day of our exciting Java Learning Series! Today, we're taking our first steps into the world of Java programming. Don't worry if you're a complete beginner โ we'll start with the absolute fundamentals. We'll learn what Java is, set up our environment (conceptually for now!), and write the most classic first program: "Hello, World!". Get ready to launch your coding adventure! โจ
---
**Our First Java Program:**
```java
public class HelloWorld {
public static void main(String[] args) {
// This line prints "Hello, World!" to the console
System.out.println("Hello, World!");
}
}
```
---
**Output example:**
```
Hello, World!
```
---
**Small Challenge:**
Can you modify the code above to print a different greeting, perhaps "Hello, [Your Name]!" instead of "Hello, World!"? Give it a try and share your custom output in the comments! ๐
---
๐ Welcome to the very first day of our exciting Java Learning Series! Today, we're taking our first steps into the world of Java programming. Don't worry if you're a complete beginner โ we'll start with the absolute fundamentals. We'll learn what Java is, set up our environment (conceptually for now!), and write the most classic first program: "Hello, World!". Get ready to launch your coding adventure! โจ
---
**Our First Java Program:**
```java
public class HelloWorld {
public static void main(String[] args) {
// This line prints "Hello, World!" to the console
System.out.println("Hello, World!");
}
}
```
---
**Output example:**
```
Hello, World!
```
---
**Small Challenge:**
Can you modify the code above to print a different greeting, perhaps "Hello, [Your Name]!" instead of "Hello, World!"? Give it a try and share your custom output in the comments! ๐
---
What is the primary purpose of `System.out.println("Hello, World!");` in a Java program?
Anonymous Quiz
4%
To define a new variable.
0%
To read input from the user.
96%
To print "Hello, World!" to the console.
0%
To declare a class.
Java for beginners pinned ยซHey everyone! We're starting again from Day 1 so everyone can build a strong foundation by learning everything from the basics this time.ยป
๐ Welcome back, Java enthusiasts! It's Day 2 of our learning journey, and today we're diving into the building blocks of any program: **Variables and Data Types**! ๐ ๏ธ
Think of variables as containers that hold information, and data types as labels telling Java what kind of information each container can store (numbers, text, true/false values, etc.). Understanding them is crucial for writing dynamic programs. Let's learn how to declare and use them! ๐
```java
public class Day2Variables {
public static void main(String[] args) {
// Declaring and initializing different types of variables
// Integer (whole numbers)
int age = 30;
System.out.println("My age is: " + age);
// Double (floating-point numbers, decimals)
double price = 19.99;
System.out.println("The price is: $" + price);
// Boolean (true or false)
boolean isJavaFun = true;
System.out.println("Is Java fun? " + isJavaFun);
// Character (single character)
char grade = 'A';
System.out.println("My grade is: " + grade);
// String (sequence of characters, text)
String name = "Alice";
System.out.println("My name is: " + name);
// You can also change variable values
age = 31; // Assigning a new value to 'age'
System.out.println("Next year, my age will be: " + age);
// Declaring without initializing, then assigning later
int numberOfStudents;
numberOfStudents = 25;
System.out.println("Number of students: " + numberOfStudents);
}
}
```
Output example:
```
My age is: 30
The price is: $19.99
Is Java fun? true
My grade is: A
My name is: Alice
Next year, my age will be: 31
Number of students: 25
```
๐ก **Your Challenge:** Try declaring a new `String` variable to hold your favorite programming language and an `int` variable for its release year. Then print them out using `System.out.println()`! Share your code or output in the comments if you like! ๐ฌ Happy coding!
---
Think of variables as containers that hold information, and data types as labels telling Java what kind of information each container can store (numbers, text, true/false values, etc.). Understanding them is crucial for writing dynamic programs. Let's learn how to declare and use them! ๐
```java
public class Day2Variables {
public static void main(String[] args) {
// Declaring and initializing different types of variables
// Integer (whole numbers)
int age = 30;
System.out.println("My age is: " + age);
// Double (floating-point numbers, decimals)
double price = 19.99;
System.out.println("The price is: $" + price);
// Boolean (true or false)
boolean isJavaFun = true;
System.out.println("Is Java fun? " + isJavaFun);
// Character (single character)
char grade = 'A';
System.out.println("My grade is: " + grade);
// String (sequence of characters, text)
String name = "Alice";
System.out.println("My name is: " + name);
// You can also change variable values
age = 31; // Assigning a new value to 'age'
System.out.println("Next year, my age will be: " + age);
// Declaring without initializing, then assigning later
int numberOfStudents;
numberOfStudents = 25;
System.out.println("Number of students: " + numberOfStudents);
}
}
```
Output example:
```
My age is: 30
The price is: $19.99
Is Java fun? true
My grade is: A
My name is: Alice
Next year, my age will be: 31
Number of students: 25
```
๐ก **Your Challenge:** Try declaring a new `String` variable to hold your favorite programming language and an `int` variable for its release year. Then print them out using `System.out.println()`! Share your code or output in the comments if you like! ๐ฌ Happy coding!
---
โค1
Which of the following is the correct way to declare an integer variable named `quantity` and initialize it with the value `50` in Java?
Anonymous Quiz
95%
int quantity = 50;
5%
integer quantity = 50;
0%
quantity int = 50;
0%
Int quantity = 50;
What will be the value of `x` and `y` after the following code snippet executes?
```java
int x = 5; int y = ++x; ```
```java
int x = 5; int y = ++x; ```
Anonymous Quiz
25%
x = 5, y = 5
13%
x = 6, y = 5
50%
x = 5, y = 6
13%
x = 6, y = 6
Here's your Telegram post and quiz question!
---
๐ **Day 4: Making Decisions in Java! Conditional Statements** ๐ก
Hello, Java learners! Today we're diving into how your programs can make intelligent choices โ welcome to the world of Conditional Statements (`if`, `else if`, `else`)! ๐ค
Imagine your program as a person: it needs to decide what to do based on different situations. Should it print a "Pass" or "Fail"? Should it offer a discount or not? Conditional statements are the tools that give your code this power of decision-making. They allow your program to execute different blocks of code only when specific conditions are met. Get ready to add logic and flexibility to your Java applications! ๐
```java
public class Day4Conditional {
public static void main(String[] args) {
int score = 85;
System.out.println("Your score: " + score);
if (score >= 90) {
System.out.println("Excellent! You got an A.");
} else if (score >= 80) { // This block executes if the first 'if' was false, AND score is >= 80
System.out.println("Great job! You got a B.");
} else if (score >= 70) {
System.out.println("Good effort! You got a C.");
} else { // This block executes if all preceding 'if' and 'else if' conditions were false
System.out.println("Keep practicing! You got a D or F.");
}
System.out.println("End of grading.");
}
}
```
Output example:
```
Your score: 85
Great job! You got a B.
End of grading.
```
**Small Challenge:**
Try changing the `score` variable to `95`, `60`, or `75`. What output do you get? Can you add another `else if` condition for a specific "Perfect Score!" message (e.g., if `score == 100`)? ๐งโ๐ป
---
---
๐ **Day 4: Making Decisions in Java! Conditional Statements** ๐ก
Hello, Java learners! Today we're diving into how your programs can make intelligent choices โ welcome to the world of Conditional Statements (`if`, `else if`, `else`)! ๐ค
Imagine your program as a person: it needs to decide what to do based on different situations. Should it print a "Pass" or "Fail"? Should it offer a discount or not? Conditional statements are the tools that give your code this power of decision-making. They allow your program to execute different blocks of code only when specific conditions are met. Get ready to add logic and flexibility to your Java applications! ๐
```java
public class Day4Conditional {
public static void main(String[] args) {
int score = 85;
System.out.println("Your score: " + score);
if (score >= 90) {
System.out.println("Excellent! You got an A.");
} else if (score >= 80) { // This block executes if the first 'if' was false, AND score is >= 80
System.out.println("Great job! You got a B.");
} else if (score >= 70) {
System.out.println("Good effort! You got a C.");
} else { // This block executes if all preceding 'if' and 'else if' conditions were false
System.out.println("Keep practicing! You got a D or F.");
}
System.out.println("End of grading.");
}
}
```
Output example:
```
Your score: 85
Great job! You got a B.
End of grading.
```
**Small Challenge:**
Try changing the `score` variable to `95`, `60`, or `75`. What output do you get? Can you add another `else if` condition for a specific "Perfect Score!" message (e.g., if `score == 100`)? ๐งโ๐ป
---
Here's your Telegram post for Day 5 of the Java learning series:
---
๐ Day 5 is here, Java Explorers! Today, we're diving into one of programming's most fundamental concepts: **Loops**! ๐ Ever needed to repeat a task multiple times? That's where `for`, `while`, and `do-while` come in handy. They help us automate repetitive actions, making our code efficient and powerful. Get ready to master iteration! Let's code! ๐ป
```java
public class LoopExamples {
public static void main(String[] args) {
System.out.println("--- For Loop Example (Counts 0-2) ---");
for (int i = 0; i < 3; i++) {
System.out.println("For loop iteration: " + i);
}
System.out.println("n--- While Loop Example (Counts 0-2) ---");
int count = 0;
while (count < 3) {
System.out.println("While loop iteration: " + count);
count++;
}
System.out.println("n--- Do-While Loop Example (Counts 0-2) ---");
int num = 0;
do {
System.out.println("Do-While loop iteration: " + num);
num++;
} while (num < 3);
System.out.println("n--- Do-While (Executes at least once) ---");
int x = 5; // Initial condition x < 3 is false
do {
System.out.println("This runs once even if the condition is initially false! x is: " + x);
x++;
} while (x < 3); // Condition will be false, loop exits after one run
}
}
```
Output example:
```
--- For Loop Example (Counts 0-2) ---
For loop iteration: 0
For loop iteration: 1
For loop iteration: 2
--- While Loop Example (Counts 0-2) ---
While loop iteration: 0
While loop iteration: 1
While loop iteration: 2
--- Do-While Loop Example (Counts 0-2) ---
Do-While loop iteration: 0
Do-While loop iteration: 1
Do-While loop iteration: 2
--- Do-While (Executes at least once) ---
This runs once even if the condition is initially false! x is: 5
```
๐ก **Your Challenge:**
Write a Java program using a `for` loop to print all even numbers from 1 to 10. Can you also achieve this using a `while` loop? Share your solutions in the comments! ๐
---
---
๐ Day 5 is here, Java Explorers! Today, we're diving into one of programming's most fundamental concepts: **Loops**! ๐ Ever needed to repeat a task multiple times? That's where `for`, `while`, and `do-while` come in handy. They help us automate repetitive actions, making our code efficient and powerful. Get ready to master iteration! Let's code! ๐ป
```java
public class LoopExamples {
public static void main(String[] args) {
System.out.println("--- For Loop Example (Counts 0-2) ---");
for (int i = 0; i < 3; i++) {
System.out.println("For loop iteration: " + i);
}
System.out.println("n--- While Loop Example (Counts 0-2) ---");
int count = 0;
while (count < 3) {
System.out.println("While loop iteration: " + count);
count++;
}
System.out.println("n--- Do-While Loop Example (Counts 0-2) ---");
int num = 0;
do {
System.out.println("Do-While loop iteration: " + num);
num++;
} while (num < 3);
System.out.println("n--- Do-While (Executes at least once) ---");
int x = 5; // Initial condition x < 3 is false
do {
System.out.println("This runs once even if the condition is initially false! x is: " + x);
x++;
} while (x < 3); // Condition will be false, loop exits after one run
}
}
```
Output example:
```
--- For Loop Example (Counts 0-2) ---
For loop iteration: 0
For loop iteration: 1
For loop iteration: 2
--- While Loop Example (Counts 0-2) ---
While loop iteration: 0
While loop iteration: 1
While loop iteration: 2
--- Do-While Loop Example (Counts 0-2) ---
Do-While loop iteration: 0
Do-While loop iteration: 1
Do-While loop iteration: 2
--- Do-While (Executes at least once) ---
This runs once even if the condition is initially false! x is: 5
```
๐ก **Your Challenge:**
Write a Java program using a `for` loop to print all even numbers from 1 to 10. Can you also achieve this using a `while` loop? Share your solutions in the comments! ๐
---
Which type of loop in Java is guaranteed to execute its body at least once, regardless of whether its condition is initially true or false?
Anonymous Quiz
9%
for loop
18%
while loop
73%
do-while loop
0%
foreach loop
Here's your Telegram post for Day 6!
---
Hey #JavaLearners! ๐ Ready for Day 6 of our Java journey? Today, we're diving into the heart of code reusability: **Methods in Java**! ๐
Methods are like mini-programs within your main program. They help you organize code, perform specific tasks, and make your applications much cleaner and easier to manage. Think of them as actions your objects can perform! โจ They take input, do some work, and optionally return a result. Let's see them in action! ๐
```java
public class MethodMagic {
public static void main(String[] args) {
// Calling our custom methods
int sumResult = addNumbers(10, 5); // Calling a method with a return value
System.out.println("Sum of 10 and 5 is: " + sumResult);
sayHello("Alice"); // Calling a method with no return value (void)
sayHello("Bob");
}
/**
* This method takes two integers as parameters and returns their sum.
*/
public static int addNumbers(int num1, int num2) {
int sum = num1 + num2;
return sum; // 'return' sends the result back
}
/**
* This method takes a String name as a parameter and prints a greeting.
* It does not return anything, indicated by the 'void' keyword.
*/
public static void sayHello(String name) {
System.out.println("Hello, " + name + "! Welcome to Methods!");
}
}
```
Output example:
```
Sum of 10 and 5 is: 15
Hello, Alice! Welcome to Methods!
Hello, Bob! Welcome to Methods!
```
**Small challenge:**
Your turn! ๐ ๏ธ Try creating a new method in the `MethodMagic` class called `multiplyNumbers` that takes two integers as parameters and returns their product. Then call it from your `main` method and print the result! Good luck, future Java wizard! ๐ง โจ
---
---
Hey #JavaLearners! ๐ Ready for Day 6 of our Java journey? Today, we're diving into the heart of code reusability: **Methods in Java**! ๐
Methods are like mini-programs within your main program. They help you organize code, perform specific tasks, and make your applications much cleaner and easier to manage. Think of them as actions your objects can perform! โจ They take input, do some work, and optionally return a result. Let's see them in action! ๐
```java
public class MethodMagic {
public static void main(String[] args) {
// Calling our custom methods
int sumResult = addNumbers(10, 5); // Calling a method with a return value
System.out.println("Sum of 10 and 5 is: " + sumResult);
sayHello("Alice"); // Calling a method with no return value (void)
sayHello("Bob");
}
/**
* This method takes two integers as parameters and returns their sum.
*/
public static int addNumbers(int num1, int num2) {
int sum = num1 + num2;
return sum; // 'return' sends the result back
}
/**
* This method takes a String name as a parameter and prints a greeting.
* It does not return anything, indicated by the 'void' keyword.
*/
public static void sayHello(String name) {
System.out.println("Hello, " + name + "! Welcome to Methods!");
}
}
```
Output example:
```
Sum of 10 and 5 is: 15
Hello, Alice! Welcome to Methods!
Hello, Bob! Welcome to Methods!
```
**Small challenge:**
Your turn! ๐ ๏ธ Try creating a new method in the `MethodMagic` class called `multiplyNumbers` that takes two integers as parameters and returns their product. Then call it from your `main` method and print the result! Good luck, future Java wizard! ๐ง โจ
---
What keyword is used to declare a method that does not return any value in Java?
Anonymous Quiz
0%
int
0%
return
92%
void
8%
null
๐ Happy Day 7, Java Learners! ๐ Today, we're unlocking the power of storing multiple pieces of data efficiently with **Arrays and ArrayLists**!
These two are fundamental data structures, but they have key differences. Arrays are like fixed-size containers, while ArrayLists are dynamic, growing and shrinking as you need them to. Understanding when to use each is crucial for writing efficient Java code. Let's dive in! ๐๐ก
```java
import java.util.ArrayList;
import java.util.Arrays; // Useful for printing array contents easily
public class Day7ArraysArrayLists {
public static void main(String[] args) {
// --- Working with Arrays (Fixed Size) ---
// Declare and initialize an array of Strings
String[] fruits = {"Apple", "Banana", "Cherry"};
System.out.println("--- Using Arrays ---");
// Accessing elements using index
System.out.println("First fruit: " + fruits[0]); // Output: Apple
System.out.println("Third fruit: " + fruits[2]); // Output: Cherry
// Getting the number of elements (length property)
System.out.println("Number of fruits (Array): " + fruits.length); // Output: 3
// Printing the whole array (Arrays.toString() is helpful!)
System.out.println("All fruits: " + Arrays.toString(fruits)); // Output: [Apple, Banana, Cherry]
// IMPORTANT: Arrays have a fixed size.
// You cannot simply add a new element beyond its initial capacity.
// fruits[3] = "Date"; // This would cause an ArrayIndexOutOfBoundsException at runtime!
// --- Working with ArrayLists (Dynamic Size) ---
// Declare and initialize an ArrayList of Strings
ArrayList<String> veggies = new ArrayList<>();
System.out.println("n--- Using ArrayLists ---");
// Adding elements using .add()
veggies.add("Carrot");
veggies.add("Broccoli");
veggies.add("Spinach");
// Accessing elements using .get()
System.out.println("First veggie: " + veggies.get(0)); // Output: Carrot
// Getting the number of elements (size() method)
System.out.println("Number of veggies (ArrayList): " + veggies.size()); // Output: 3
// ArrayLists are dynamic! You can add more elements easily.
veggies.add("Potato");
System.out.println("After adding Potato: " + veggies); // Output: [Carrot, Broccoli, Spinach, Potato]
// You can also remove elements easily.
veggies.remove("Broccoli"); // Removes the first occurrence of "Broccoli"
System.out.println("After removing Broccoli: " + veggies); // Output: [Carrot, Spinach, Potato]
// Or remove by index
veggies.remove(0); // Removes the element at index 0 (Carrot)
System.out.println("After removing element at index 0: " + veggies); // Output: [Spinach, Potato]
}
}
```
Output example:
```
--- Using Arrays ---
First fruit: Apple
Third fruit: Cherry
Number of fruits (Array): 3
All fruits: [Apple, Banana, Cherry]
--- Using ArrayLists ---
First veggie: Carrot
Number of veggies (ArrayList): 3
After adding Potato: [Carrot, Broccoli, Spinach, Potato]
After removing Broccoli: [Carrot, Spinach, Potato]
After removing element at index 0: [Spinach, Potato]
```
**Small Challenge:**
Can you modify the `veggies` ArrayList in the code to insert "Cucumber" at the second position (index 1), pushing "Spinach" and "Potato" down, without removing any existing elements? ๐ค Good luck!
---
These two are fundamental data structures, but they have key differences. Arrays are like fixed-size containers, while ArrayLists are dynamic, growing and shrinking as you need them to. Understanding when to use each is crucial for writing efficient Java code. Let's dive in! ๐๐ก
```java
import java.util.ArrayList;
import java.util.Arrays; // Useful for printing array contents easily
public class Day7ArraysArrayLists {
public static void main(String[] args) {
// --- Working with Arrays (Fixed Size) ---
// Declare and initialize an array of Strings
String[] fruits = {"Apple", "Banana", "Cherry"};
System.out.println("--- Using Arrays ---");
// Accessing elements using index
System.out.println("First fruit: " + fruits[0]); // Output: Apple
System.out.println("Third fruit: " + fruits[2]); // Output: Cherry
// Getting the number of elements (length property)
System.out.println("Number of fruits (Array): " + fruits.length); // Output: 3
// Printing the whole array (Arrays.toString() is helpful!)
System.out.println("All fruits: " + Arrays.toString(fruits)); // Output: [Apple, Banana, Cherry]
// IMPORTANT: Arrays have a fixed size.
// You cannot simply add a new element beyond its initial capacity.
// fruits[3] = "Date"; // This would cause an ArrayIndexOutOfBoundsException at runtime!
// --- Working with ArrayLists (Dynamic Size) ---
// Declare and initialize an ArrayList of Strings
ArrayList<String> veggies = new ArrayList<>();
System.out.println("n--- Using ArrayLists ---");
// Adding elements using .add()
veggies.add("Carrot");
veggies.add("Broccoli");
veggies.add("Spinach");
// Accessing elements using .get()
System.out.println("First veggie: " + veggies.get(0)); // Output: Carrot
// Getting the number of elements (size() method)
System.out.println("Number of veggies (ArrayList): " + veggies.size()); // Output: 3
// ArrayLists are dynamic! You can add more elements easily.
veggies.add("Potato");
System.out.println("After adding Potato: " + veggies); // Output: [Carrot, Broccoli, Spinach, Potato]
// You can also remove elements easily.
veggies.remove("Broccoli"); // Removes the first occurrence of "Broccoli"
System.out.println("After removing Broccoli: " + veggies); // Output: [Carrot, Spinach, Potato]
// Or remove by index
veggies.remove(0); // Removes the element at index 0 (Carrot)
System.out.println("After removing element at index 0: " + veggies); // Output: [Spinach, Potato]
}
}
```
Output example:
```
--- Using Arrays ---
First fruit: Apple
Third fruit: Cherry
Number of fruits (Array): 3
All fruits: [Apple, Banana, Cherry]
--- Using ArrayLists ---
First veggie: Carrot
Number of veggies (ArrayList): 3
After adding Potato: [Carrot, Broccoli, Spinach, Potato]
After removing Broccoli: [Carrot, Spinach, Potato]
After removing element at index 0: [Spinach, Potato]
```
**Small Challenge:**
Can you modify the `veggies` ArrayList in the code to insert "Cucumber" at the second position (index 1), pushing "Spinach" and "Potato" down, without removing any existing elements? ๐ค Good luck!
---
Hey Java Learners! ๐ Today marks Day 8 of our journey, and we're diving into two incredibly powerful collections: `HashMaps` and `HashSets`! ๐ง Ever needed to store data where you can quickly find things by a unique label? That's `HashMap` for you โ think of it like a super-efficient dictionary with key-value pairs. And what if you just need a collection of unique items, no duplicates allowed? `HashSet` is your go-to! ๐ก๏ธ Get ready to unlock faster data management with these amazing tools! Let's explore. ๐
```java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map; // For Map.Entry
public class Day8Collections {
public static void main(String[] args) {
System.out.println("--- HashMap Example ---");
// 1. Create a HashMap: Stores key-value pairs
HashMap<String, Integer> studentScores = new HashMap<>();
// 2. Add elements: put(key, value)
studentScores.put("Alice", 95);
studentScores.put("Bob", 88);
studentScores.put("Charlie", 92);
studentScores.put("Alice", 98); // If key exists, value is updated
System.out.println("Student Scores: " + studentScores);
// 3. Get a value: get(key)
System.out.println("Alice's score: " + studentScores.get("Alice"));
// 4. Check if a key exists: containsKey(key)
System.out.println("Contains Bob? " + studentScores.containsKey("Bob"));
// 5. Iterate through HashMap using entrySet()
System.out.println("All scores:");
for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
System.out.println("n--- HashSet Example ---");
// 1. Create a HashSet: Stores unique elements
HashSet<String> uniqueFruits = new HashSet<>();
// 2. Add elements: add(element)
uniqueFruits.add("Apple");
uniqueFruits.add("Banana");
uniqueFruits.add("Orange");
uniqueFruits.add("Apple"); // Duplicate, won't be added
System.out.println("Unique Fruits: " + uniqueFruits); // Order is not guaranteed
// 3. Check if an element exists: contains(element)
System.out.println("Contains Banana? " + uniqueFruits.contains("Banana"));
// 4. Remove an element: remove(element)
uniqueFruits.remove("Orange");
System.out.println("Fruits after removing Orange: " + uniqueFruits);
// 5. Iterate through HashSet
System.out.println("My fruits:");
for (String fruit : uniqueFruits) {
System.out.println(fruit);
}
}
}
```
Output example:
```
--- HashMap Example ---
Student Scores: {Alice=98, Bob=88, Charlie=92}
Alice's score: 98
Contains Bob? true
All scores:
Alice -> 98
Bob -> 88
Charlie -> 92
--- HashSet Example ---
Unique Fruits: [Apple, Banana, Orange]
Contains Banana? true
Fruits after removing Orange: [Apple, Banana]
My fruits:
Apple
Banana
```
๐ก Your Challenge: Can you use a `HashMap` to count the frequency of each word in a given sentence? For example, for the sentence "Java is fun, Java is powerful." your output should be something like `{"Java": 2, "is": 2, "fun": 1, "powerful": 1}` (you can ignore punctuation and case for simplicity). Go ahead and try it out! โ
```java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map; // For Map.Entry
public class Day8Collections {
public static void main(String[] args) {
System.out.println("--- HashMap Example ---");
// 1. Create a HashMap: Stores key-value pairs
HashMap<String, Integer> studentScores = new HashMap<>();
// 2. Add elements: put(key, value)
studentScores.put("Alice", 95);
studentScores.put("Bob", 88);
studentScores.put("Charlie", 92);
studentScores.put("Alice", 98); // If key exists, value is updated
System.out.println("Student Scores: " + studentScores);
// 3. Get a value: get(key)
System.out.println("Alice's score: " + studentScores.get("Alice"));
// 4. Check if a key exists: containsKey(key)
System.out.println("Contains Bob? " + studentScores.containsKey("Bob"));
// 5. Iterate through HashMap using entrySet()
System.out.println("All scores:");
for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
System.out.println("n--- HashSet Example ---");
// 1. Create a HashSet: Stores unique elements
HashSet<String> uniqueFruits = new HashSet<>();
// 2. Add elements: add(element)
uniqueFruits.add("Apple");
uniqueFruits.add("Banana");
uniqueFruits.add("Orange");
uniqueFruits.add("Apple"); // Duplicate, won't be added
System.out.println("Unique Fruits: " + uniqueFruits); // Order is not guaranteed
// 3. Check if an element exists: contains(element)
System.out.println("Contains Banana? " + uniqueFruits.contains("Banana"));
// 4. Remove an element: remove(element)
uniqueFruits.remove("Orange");
System.out.println("Fruits after removing Orange: " + uniqueFruits);
// 5. Iterate through HashSet
System.out.println("My fruits:");
for (String fruit : uniqueFruits) {
System.out.println(fruit);
}
}
}
```
Output example:
```
--- HashMap Example ---
Student Scores: {Alice=98, Bob=88, Charlie=92}
Alice's score: 98
Contains Bob? true
All scores:
Alice -> 98
Bob -> 88
Charlie -> 92
--- HashSet Example ---
Unique Fruits: [Apple, Banana, Orange]
Contains Banana? true
Fruits after removing Orange: [Apple, Banana]
My fruits:
Apple
Banana
```
๐ก Your Challenge: Can you use a `HashMap` to count the frequency of each word in a given sentence? For example, for the sentence "Java is fun, Java is powerful." your output should be something like `{"Java": 2, "is": 2, "fun": 1, "powerful": 1}` (you can ignore punctuation and case for simplicity). Go ahead and try it out! โ
Which of the following statements is TRUE about Java's `HashSet`?
Anonymous Quiz
0%
It stores elements in a sorted order.
0%
It allows duplicate elements.
100%
It ensures that all stored elements are unique.
0%
It stores elements as key-value pairs.
๐ **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
---
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
---