๐ **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 initial steps into the powerful world of Java programming. We'll start with the absolute basics: understanding the structure of a simple Java program and making it say that classic greeting: "Hello, World!" Get ready to write your first lines of code and witness them in action! Let's dive in! ๐ป
---
**Your First Java Code:**
Here's the quintessential "Hello World" program in Java. Don't worry if it looks a bit complex at first; we'll break down each part in future lessons!
```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 for You!**
Your first programming challenge: Can you modify the line `System.out.println("Hello, World!");` in the code above to print "Hello, [Your Name]!" instead? Give it a try and see your personalized message appear in the console! ๐ค Share your output in the comments!
---
๐ Welcome to the very first day of our exciting Java Learning Series! ๐ Today, we're taking our initial steps into the powerful world of Java programming. We'll start with the absolute basics: understanding the structure of a simple Java program and making it say that classic greeting: "Hello, World!" Get ready to write your first lines of code and witness them in action! Let's dive in! ๐ป
---
**Your First Java Code:**
Here's the quintessential "Hello World" program in Java. Don't worry if it looks a bit complex at first; we'll break down each part in future lessons!
```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 for You!**
Your first programming challenge: Can you modify the line `System.out.println("Hello, World!");` in the code above to print "Hello, [Your Name]!" instead? Give it a try and see your personalized message appear in the console! ๐ค Share your output in the comments!
---
โค1
What is the primary purpose of the line `System.out.println("Hello, World!");` in the Java 'Hello World' program?
Anonymous Quiz
3%
To declare a new class named `HelloWorld`.
94%
To display text output (like "Hello, World!") on the console.
3%
To define the main entry point of the Java program.
0%
To import necessary libraries for printing.
๐ Day 2: Variables and Data Types! ๐
Ready to store information in your Java programs? Today, we dive into the fundamental concepts of Variables and Data Types. Think of variables as named containers for different kinds of data, from numbers to text and true/false values. Understanding them is key to writing dynamic and powerful code! Let's get started and see how Java handles different types of information. ๐ก๐
```java
public class Day2Variables {
public static void main(String[] args) {
// Declaring and initializing different types of variables
// 1. Integer (whole numbers)
int age = 30;
System.out.println("My age is: " + age); // Output: My age is: 30
// 2. Double (floating-point numbers, e.g., decimals)
double price = 19.99;
System.out.println("The product price is: $" + price); // Output: The product price is: $19.99
// 3. Boolean (true or false)
boolean isJavaFun = true;
System.out.println("Is Java fun? " + isJavaFun); // Output: Is Java fun? true
// 4. Character (single character)
char initial = 'J';
System.out.println("My initial is: " + initial); // Output: My initial is: J
// 5. String (sequence of characters - technically a class, but acts like a primitive for beginners)
String userName = "CodeMaster7";
System.out.println("Username: " + userName); // Output: Username: CodeMaster7
// You can also change variable values
age = 31; // Age is now updated
System.out.println("Updated age: " + age); // Output: Updated age: 31
// Simple arithmetic with variables
int num1 = 10;
int num2 = 5;
int sum = num1 + num2;
System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum); // Output: Sum of 10 and 5 is: 15
}
}
```
Output example:
```
My age is: 30
The product price is: $19.99
Is Java fun? true
My initial is: J
Username: CodeMaster7
Updated age: 31
Sum of 10 and 5 is: 15
```
โจ **Your Small Challenge:**
Create a new Java program. Declare a `float` variable (remember to add 'f' at the end of the number, e.g., `3.14f`) to store the value of Pi. Then, declare an `int` variable for a radius. Calculate the area of a circle (`Pi * radius * radius`) and print the result to the console! Don't forget to use appropriate data types for your variables. Good luck! ๐ฏ
---
Ready to store information in your Java programs? Today, we dive into the fundamental concepts of Variables and Data Types. Think of variables as named containers for different kinds of data, from numbers to text and true/false values. Understanding them is key to writing dynamic and powerful code! Let's get started and see how Java handles different types of information. ๐ก๐
```java
public class Day2Variables {
public static void main(String[] args) {
// Declaring and initializing different types of variables
// 1. Integer (whole numbers)
int age = 30;
System.out.println("My age is: " + age); // Output: My age is: 30
// 2. Double (floating-point numbers, e.g., decimals)
double price = 19.99;
System.out.println("The product price is: $" + price); // Output: The product price is: $19.99
// 3. Boolean (true or false)
boolean isJavaFun = true;
System.out.println("Is Java fun? " + isJavaFun); // Output: Is Java fun? true
// 4. Character (single character)
char initial = 'J';
System.out.println("My initial is: " + initial); // Output: My initial is: J
// 5. String (sequence of characters - technically a class, but acts like a primitive for beginners)
String userName = "CodeMaster7";
System.out.println("Username: " + userName); // Output: Username: CodeMaster7
// You can also change variable values
age = 31; // Age is now updated
System.out.println("Updated age: " + age); // Output: Updated age: 31
// Simple arithmetic with variables
int num1 = 10;
int num2 = 5;
int sum = num1 + num2;
System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum); // Output: Sum of 10 and 5 is: 15
}
}
```
Output example:
```
My age is: 30
The product price is: $19.99
Is Java fun? true
My initial is: J
Username: CodeMaster7
Updated age: 31
Sum of 10 and 5 is: 15
```
โจ **Your Small Challenge:**
Create a new Java program. Declare a `float` variable (remember to add 'f' at the end of the number, e.g., `3.14f`) to store the value of Pi. Then, declare an `int` variable for a radius. Calculate the area of a circle (`Pi * radius * radius`) and print the result to the console! Don't forget to use appropriate data types for your variables. Good luck! ๐ฏ
---
Which of the following is NOT a primitive data type in Java?
Anonymous Quiz
2%
int
16%
boolean
71%
String
11%
char
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.ยป
Learn Python daily with bite-sized lessons, code examples, output previews, and fun quizzes. Perfect for beginners and enthusiasts!
https://t.me/Python_basic_to_advance
https://t.me/Python_basic_to_advance
Telegram
Python basic to advance
Learn Python daily with bite-sized lessons, code examples, output previews, and fun quizzes. Perfect for beginners and enthusiasts!
๐ Java Learning Series - Day 3! ๐
Ready to make your code *do things*? Today, we're diving into the powerful world of **Operators in Java**! โโโ๏ธโ These special symbols are the backbone of computation and logic, allowing you to perform calculations, make comparisons, and control program flow. Understanding operators is crucial for writing dynamic and interactive Java applications. Let's get started! ๐ช
```java
public class OperatorShowcase {
public static void main(String[] args) {
// 1. Arithmetic Operators (+, -, *, /, %)
int a = 10;
int b = 3;
System.out.println("--- Arithmetic Operators ---");
System.out.println("a + b = " + (a + b)); // Addition: 13
System.out.println("a - b = " + (a - b)); // Subtraction: 7
System.out.println("a * b = " + (a * b)); // Multiplication: 30
System.out.println("a / b = " + (a / b)); // Division (integer): 3
System.out.println("a % b = " + (a % b)); // Modulo (remainder): 1
// 2. Assignment Operators (=, +=, -=, *=, /=, %=)
int c = 5;
c += 2; // Equivalent to c = c + 2;
System.out.println("n--- Assignment Operators ---");
System.out.println("c after c += 2: " + c); // Output: 7
// 3. Relational Operators (==, !=, >, <, >=, <=)
int x = 10;
int y = 5;
System.out.println("n--- Relational Operators ---");
System.out.println("x > y is " + (x > y)); // Output: true
System.out.println("x == y is " + (x == y)); // Output: false
System.out.println("x != y is " + (x != y)); // Output: true
// 4. Logical Operators (&&, ||, !)
boolean isJavaFun = true;
boolean isDay3 = true;
System.out.println("n--- Logical Operators ---");
System.out.println("isJavaFun && isDay3 is " + (isJavaFun && isDay3)); // AND: true
System.out.println("!isJavaFun is " + (!isJavaFun)); // NOT: false
// 5. Unary Operators (++, --)
int i = 7;
i++; // Post-increment: i becomes 8
System.out.println("n--- Unary Operators ---");
System.out.println("i after i++: " + i); // Output: 8
--i; // Pre-decrement: i becomes 7
System.out.println("i after --i: " + i); // Output: 7
}
}
```
Output example:
```
--- Arithmetic Operators ---
a + b = 13
a - b = 7
a * b = 30
a / b = 3
a % b = 1
--- Assignment Operators ---
c after c += 2: 7
--- Relational Operators ---
x > y is true
x == y is false
x != y is true
--- Logical Operators ---
isJavaFun && isDay3 is true
!isJavaFun is false
--- Unary Operators ---
i after i++: 8
i after --i: 7
```
**Small challenge:** ๐ค
What will be the value of `result` after these lines of code?
```java
int num1 = 20;
int num2 = 6;
int result = num1 % num2;
```
Share your answer in the comments below! ๐
---
Ready to make your code *do things*? Today, we're diving into the powerful world of **Operators in Java**! โโโ๏ธโ These special symbols are the backbone of computation and logic, allowing you to perform calculations, make comparisons, and control program flow. Understanding operators is crucial for writing dynamic and interactive Java applications. Let's get started! ๐ช
```java
public class OperatorShowcase {
public static void main(String[] args) {
// 1. Arithmetic Operators (+, -, *, /, %)
int a = 10;
int b = 3;
System.out.println("--- Arithmetic Operators ---");
System.out.println("a + b = " + (a + b)); // Addition: 13
System.out.println("a - b = " + (a - b)); // Subtraction: 7
System.out.println("a * b = " + (a * b)); // Multiplication: 30
System.out.println("a / b = " + (a / b)); // Division (integer): 3
System.out.println("a % b = " + (a % b)); // Modulo (remainder): 1
// 2. Assignment Operators (=, +=, -=, *=, /=, %=)
int c = 5;
c += 2; // Equivalent to c = c + 2;
System.out.println("n--- Assignment Operators ---");
System.out.println("c after c += 2: " + c); // Output: 7
// 3. Relational Operators (==, !=, >, <, >=, <=)
int x = 10;
int y = 5;
System.out.println("n--- Relational Operators ---");
System.out.println("x > y is " + (x > y)); // Output: true
System.out.println("x == y is " + (x == y)); // Output: false
System.out.println("x != y is " + (x != y)); // Output: true
// 4. Logical Operators (&&, ||, !)
boolean isJavaFun = true;
boolean isDay3 = true;
System.out.println("n--- Logical Operators ---");
System.out.println("isJavaFun && isDay3 is " + (isJavaFun && isDay3)); // AND: true
System.out.println("!isJavaFun is " + (!isJavaFun)); // NOT: false
// 5. Unary Operators (++, --)
int i = 7;
i++; // Post-increment: i becomes 8
System.out.println("n--- Unary Operators ---");
System.out.println("i after i++: " + i); // Output: 8
--i; // Pre-decrement: i becomes 7
System.out.println("i after --i: " + i); // Output: 7
}
}
```
Output example:
```
--- Arithmetic Operators ---
a + b = 13
a - b = 7
a * b = 30
a / b = 3
a % b = 1
--- Assignment Operators ---
c after c += 2: 7
--- Relational Operators ---
x > y is true
x == y is false
x != y is true
--- Logical Operators ---
isJavaFun && isDay3 is true
!isJavaFun is false
--- Unary Operators ---
i after i++: 8
i after --i: 7
```
**Small challenge:** ๐ค
What will be the value of `result` after these lines of code?
```java
int num1 = 20;
int num2 = 6;
int result = num1 % num2;
```
Share your answer in the comments below! ๐
---
โค1
Which operator is used to check if two values are NOT equal in Java?
Anonymous Quiz
19%
==
0%
=
79%
!=
2%
!==
โค1
Here's your Telegram post and quiz question!
---
๐ Hey Java Learners! Ready to make your programs smart? ๐ง Today, on Day 4, we're diving into the heart of decision-making: Conditional Statements! `if`, `else if`, and `else` are your tools to guide program flow based on conditions. They allow your code to react dynamically to different inputs and scenarios. Let's make your code react dynamically! โจ
```java
public class Day4Conditionals {
public static void main(String[] args) {
int score = 85; // Try changing this value!
if (score >= 90) {
System.out.println("Grade: A (Excellent!)");
} else if (score >= 80) {
System.out.println("Grade: B (Very Good!)");
} else if (score >= 70) {
System.out.println("Grade: C (Good)");
} else if (score >= 60) {
System.out.println("Grade: D (Pass)");
} else {
System.out.println("Grade: F (Fail)");
}
System.out.println("n--- Another example ---");
boolean isRaining = true;
if (isRaining) {
System.out.println("Remember your umbrella! โ");
} else {
System.out.println("Enjoy the clear sky! โ๏ธ");
}
}
}
```
Output example:
```
Grade: B (Very Good!)
--- Another example ---
Remember your umbrella! โ
```
๐ก **Challenge:** Try modifying the `Day4Conditionals.java` example to check if a given `int` variable (e.g., `int number = -5;`) is `positive`, `negative`, or `zero`! Share your solution in the comments! ๐
---
---
๐ Hey Java Learners! Ready to make your programs smart? ๐ง Today, on Day 4, we're diving into the heart of decision-making: Conditional Statements! `if`, `else if`, and `else` are your tools to guide program flow based on conditions. They allow your code to react dynamically to different inputs and scenarios. Let's make your code react dynamically! โจ
```java
public class Day4Conditionals {
public static void main(String[] args) {
int score = 85; // Try changing this value!
if (score >= 90) {
System.out.println("Grade: A (Excellent!)");
} else if (score >= 80) {
System.out.println("Grade: B (Very Good!)");
} else if (score >= 70) {
System.out.println("Grade: C (Good)");
} else if (score >= 60) {
System.out.println("Grade: D (Pass)");
} else {
System.out.println("Grade: F (Fail)");
}
System.out.println("n--- Another example ---");
boolean isRaining = true;
if (isRaining) {
System.out.println("Remember your umbrella! โ");
} else {
System.out.println("Enjoy the clear sky! โ๏ธ");
}
}
}
```
Output example:
```
Grade: B (Very Good!)
--- Another example ---
Remember your umbrella! โ
```
๐ก **Challenge:** Try modifying the `Day4Conditionals.java` example to check if a given `int` variable (e.g., `int number = -5;`) is `positive`, `negative`, or `zero`! Share your solution in the comments! ๐
---
๐ **Java Learning Series - Day 5: Loops!** ๐
Ready to make your code work harder, not smarter? ๐ช Today, we're diving into the wonderful world of loops! ๐ We'll explore `for`, `while`, and `do-while` loops โ your essential tools for repeating actions and automating tasks. Understanding loops is crucial for writing efficient and dynamic Java programs. They allow you to execute a block of code multiple times based on a condition. Let's get looping! ๐
```java
public class LoopExamples {
public static void main(String[] args) {
System.out.println("--- For Loop (Known number of iterations) ---");
// A 'for' loop is ideal when you know how many times you want to loop.
for (int i = 0; i < 3; i++) {
System.out.println("For loop count: " + i);
}
System.out.println("n--- While Loop (Condition-controlled) ---");
// A 'while' loop executes as long as a condition is true.
// The condition is checked *before* each iteration.
int countWhile = 0;
while (countWhile < 3) {
System.out.println("While loop count: " + countWhile);
countWhile++;
}
System.out.println("n--- Do-While Loop (Executes at least once) ---");
// A 'do-while' loop is similar to 'while', but its body is executed at least once
// because the condition is checked *after* the first iteration.
int countDoWhile = 0;
do {
System.out.println("Do-While loop count: " + countDoWhile);
countDoWhile++;
} while (countDoWhile < 3);
System.out.println("n--- Do-While example (condition initially false) ---");
// See how this runs once even if 'neverRun < 5' is immediately false!
int neverRun = 5;
do {
System.out.println("This runs at least once: " + neverRun);
neverRun++;
} while (neverRun < 5);
}
}
```
Output example:
```
--- For Loop (Known number of iterations) ---
For loop count: 0
For loop count: 1
For loop count: 2
--- While Loop (Condition-controlled) ---
While loop count: 0
While loop count: 1
While loop count: 2
--- Do-While Loop (Executes at least once) ---
Do-While loop count: 0
Do-While loop count: 1
Do-While loop count: 2
--- Do-While example (condition initially false) ---
This runs at least once: 5
```
๐ก **Your Challenge!**
Modify the `for` loop above to print only even numbers from 0 to 10 (inclusive). Hint: You might need to change the loop's increment or add an `if` statement! Share your solution in the comments! ๐
---
Ready to make your code work harder, not smarter? ๐ช Today, we're diving into the wonderful world of loops! ๐ We'll explore `for`, `while`, and `do-while` loops โ your essential tools for repeating actions and automating tasks. Understanding loops is crucial for writing efficient and dynamic Java programs. They allow you to execute a block of code multiple times based on a condition. Let's get looping! ๐
```java
public class LoopExamples {
public static void main(String[] args) {
System.out.println("--- For Loop (Known number of iterations) ---");
// A 'for' loop is ideal when you know how many times you want to loop.
for (int i = 0; i < 3; i++) {
System.out.println("For loop count: " + i);
}
System.out.println("n--- While Loop (Condition-controlled) ---");
// A 'while' loop executes as long as a condition is true.
// The condition is checked *before* each iteration.
int countWhile = 0;
while (countWhile < 3) {
System.out.println("While loop count: " + countWhile);
countWhile++;
}
System.out.println("n--- Do-While Loop (Executes at least once) ---");
// A 'do-while' loop is similar to 'while', but its body is executed at least once
// because the condition is checked *after* the first iteration.
int countDoWhile = 0;
do {
System.out.println("Do-While loop count: " + countDoWhile);
countDoWhile++;
} while (countDoWhile < 3);
System.out.println("n--- Do-While example (condition initially false) ---");
// See how this runs once even if 'neverRun < 5' is immediately false!
int neverRun = 5;
do {
System.out.println("This runs at least once: " + neverRun);
neverRun++;
} while (neverRun < 5);
}
}
```
Output example:
```
--- For Loop (Known number of iterations) ---
For loop count: 0
For loop count: 1
For loop count: 2
--- While Loop (Condition-controlled) ---
While loop count: 0
While loop count: 1
While loop count: 2
--- Do-While Loop (Executes at least once) ---
Do-While loop count: 0
Do-While loop count: 1
Do-While loop count: 2
--- Do-While example (condition initially false) ---
This runs at least once: 5
```
๐ก **Your Challenge!**
Modify the `for` loop above to print only even numbers from 0 to 10 (inclusive). Hint: You might need to change the loop's increment or add an `if` statement! Share your solution in the comments! ๐
---
Which of the following statements is true about the `do-while` loop in Java?
Anonymous Quiz
97%
It guarantees that its loop body will execute at least once, regardless of the initial condition.
0%
Its condition is evaluated before the first execution of the loop body, similar to a `while` loop.
3%
It is primarily used for iterating through elements of an array or collection efficiently.
0%
It requires an explicit initialization, condition, and increment/decrement part within its header.
Here's your Telegram post for Day 7 of the Java learning series!
---
๐ Day 7 of our Java journey is here, and it's a big one! Today, we're diving into the fundamental world of **Arrays and ArrayLists**! ๐ You'll learn how to store collections of data efficiently. Arrays offer a fixed-size container for primitives or objects, while ArrayLists provide a dynamic, resizable solution for objects, part of Java's powerful Collections Framework. Understanding these is crucial for organizing your data structures. Let's conquer them! ๐ก
```java
import java.util.ArrayList;
import java.util.Arrays; // Needed for Arrays.toString()
public class DataCollections {
public static void main(String[] args) {
// --- Working with Arrays ---
System.out.println("--- Working with Arrays ---");
int[] numbers = new int[3]; // Declare an array of 3 integers
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
System.out.println("Array elements: " + Arrays.toString(numbers));
System.out.println("First element of array: " + numbers[0]);
// --- Working with ArrayLists ---
System.out.println("n--- Working with ArrayLists ---");
ArrayList<String> fruits = new ArrayList<>(); // Create an ArrayList of Strings
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Date");
System.out.println("ArrayList elements: " + fruits);
System.out.println("Size of ArrayList: " + fruits.size());
System.out.println("Element at index 1: " + fruits.get(1));
fruits.remove("Banana"); // Remove an element by value
// fruits.remove(0); // You can also remove by index
System.out.println("ArrayList after removing Banana: " + fruits);
System.out.println("Does ArrayList contain 'Apple'? " + fruits.contains("Apple"));
}
}
```
Output example:
```
--- Working with Arrays ---
Array elements: [10, 20, 30]
First element of array: 10
--- Working with ArrayLists ---
ArrayList elements: [Apple, Banana, Cherry, Date]
Size of ArrayList: 4
Element at index 1: Banana
ArrayList after removing Banana: [Apple, Cherry, Date]
Does ArrayList contain 'Apple'? true
```
**Small challenge:**
Your challenge for today: Modify the `fruits` ArrayList in the code to add a new fruit, "Grape", at the *second* position (index 1), and then iterate through the updated ArrayList using a `for-each` loop to print each fruit on a new line! ๐๐ฉโ๐ป
---
---
๐ Day 7 of our Java journey is here, and it's a big one! Today, we're diving into the fundamental world of **Arrays and ArrayLists**! ๐ You'll learn how to store collections of data efficiently. Arrays offer a fixed-size container for primitives or objects, while ArrayLists provide a dynamic, resizable solution for objects, part of Java's powerful Collections Framework. Understanding these is crucial for organizing your data structures. Let's conquer them! ๐ก
```java
import java.util.ArrayList;
import java.util.Arrays; // Needed for Arrays.toString()
public class DataCollections {
public static void main(String[] args) {
// --- Working with Arrays ---
System.out.println("--- Working with Arrays ---");
int[] numbers = new int[3]; // Declare an array of 3 integers
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
System.out.println("Array elements: " + Arrays.toString(numbers));
System.out.println("First element of array: " + numbers[0]);
// --- Working with ArrayLists ---
System.out.println("n--- Working with ArrayLists ---");
ArrayList<String> fruits = new ArrayList<>(); // Create an ArrayList of Strings
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Date");
System.out.println("ArrayList elements: " + fruits);
System.out.println("Size of ArrayList: " + fruits.size());
System.out.println("Element at index 1: " + fruits.get(1));
fruits.remove("Banana"); // Remove an element by value
// fruits.remove(0); // You can also remove by index
System.out.println("ArrayList after removing Banana: " + fruits);
System.out.println("Does ArrayList contain 'Apple'? " + fruits.contains("Apple"));
}
}
```
Output example:
```
--- Working with Arrays ---
Array elements: [10, 20, 30]
First element of array: 10
--- Working with ArrayLists ---
ArrayList elements: [Apple, Banana, Cherry, Date]
Size of ArrayList: 4
Element at index 1: Banana
ArrayList after removing Banana: [Apple, Cherry, Date]
Does ArrayList contain 'Apple'? true
```
**Small challenge:**
Your challenge for today: Modify the `fruits` ArrayList in the code to add a new fruit, "Grape", at the *second* position (index 1), and then iterate through the updated ArrayList using a `for-each` loop to print each fruit on a new line! ๐๐ฉโ๐ป
---
What is the primary difference between a Java Array and an ArrayList regarding their size management?
Anonymous Quiz
15%
Arrays are dynamic in size, while ArrayLists have a fixed size.
74%
Arrays have a fixed size upon initialization, while ArrayLists can dynamically resize.
4%
Both Arrays and ArrayLists have fixed sizes, but ArrayLists offer more methods for manipulation.
7%
Both Arrays and ArrayLists can dynamically resize, but Arrays are generally faster for insertion.
๐ Day 8 of our Java journey! Today we're diving into two incredibly powerful collection types: `HashMaps` and `HashSets`. ๐ These data structures are essential for efficient data storage and retrieval, offering lightning-fast operations.
`HashMaps` store data in key-value pairs, perfect for looking up information quickly, while `HashSets` ensure you only store unique elements. Both are built on the concept of hashing, which allows for O(1) average-case performance for adding, removing, and checking for elements. Get ready to supercharge your Java applications! ๐ก
```java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map; // Import for Map.Entry
public class Day8Collections {
public static void main(String[] args) {
// --- HashMap Example ---
System.out.println("--- HashMap Example ---");
HashMap<String, Integer> studentGrades = new HashMap<>();
// Adding elements (Key-Value pairs)
studentGrades.put("Alice", 95);
studentGrades.put("Bob", 88);
studentGrades.put("Charlie", 92);
studentGrades.put("Alice", 97); // Updates Alice's grade (keys must be unique)
System.out.println("Student Grades: " + studentGrades);
// Getting an element by key
System.out.println("Bob's grade: " + studentGrades.get("Bob"));
// Checking if a key exists
System.out.println("Contains Charlie? " + studentGrades.containsKey("Charlie"));
System.out.println("Contains David? " + studentGrades.containsKey("David"));
// Removing an element by key
studentGrades.remove("Bob");
System.out.println("Grades after removing Bob: " + studentGrades);
// Iterating through HashMap using entrySet()
System.out.println("nIterating through grades:");
for (Map.Entry<String, Integer> entry : studentGrades.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// --- HashSet Example ---
System.out.println("n--- HashSet Example ---");
HashSet<String> uniqueCourses = new HashSet<>();
// Adding elements (only unique elements are stored)
uniqueCourses.add("Java Basics");
uniqueCourses.add("Data Structures");
uniqueCourses.add("Algorithms");
uniqueCourses.add("Java Basics"); // Duplicate, will not be added again
System.out.println("Unique Courses: " + uniqueCourses);
// Checking if an element exists
System.out.println("Contains 'Algorithms'? " + uniqueCourses.contains("Algorithms"));
System.out.println("Contains 'Python Basics'? " + uniqueCourses.contains("Python Basics"));
// Removing an element
uniqueCourses.remove("Data Structures");
System.out.println("Courses after removing 'Data Structures': " + uniqueCourses);
// Size of the set
System.out.println("Number of unique courses: " + uniqueCourses.size());
// Iterating through HashSet
System.out.println("nIterating through courses:");
for (String course : uniqueCourses) {
System.out.println("- " + course);
}
}
}
```
Output example:
```
--- HashMap Example ---
Student Grades: {Alice=97, Bob=88, Charlie=92}
Bob's grade: 88
Contains Charlie? true
Contains David? false
Grades after removing Bob: {Alice=97, Charlie=92}
Iterating through grades:
Alice: 97
Charlie: 92
--- HashSet Example ---
Unique Courses: [Java Basics, Algorithms, Data Structures]
Contains 'Algorithms'? true
Contains 'Python Basics'? false
Courses after removing 'Data Structures': [Java Basics, Algorithms]
Number of unique courses: 2
Iterating through courses:
- Java Basics
- Algorithms
```
๐ค **Your Challenge:** How would you retrieve all the *keys* from the `studentGrades` HashMap and store them in a `HashSet`? Give it a try! ๐
---
`HashMaps` store data in key-value pairs, perfect for looking up information quickly, while `HashSets` ensure you only store unique elements. Both are built on the concept of hashing, which allows for O(1) average-case performance for adding, removing, and checking for elements. Get ready to supercharge your Java applications! ๐ก
```java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map; // Import for Map.Entry
public class Day8Collections {
public static void main(String[] args) {
// --- HashMap Example ---
System.out.println("--- HashMap Example ---");
HashMap<String, Integer> studentGrades = new HashMap<>();
// Adding elements (Key-Value pairs)
studentGrades.put("Alice", 95);
studentGrades.put("Bob", 88);
studentGrades.put("Charlie", 92);
studentGrades.put("Alice", 97); // Updates Alice's grade (keys must be unique)
System.out.println("Student Grades: " + studentGrades);
// Getting an element by key
System.out.println("Bob's grade: " + studentGrades.get("Bob"));
// Checking if a key exists
System.out.println("Contains Charlie? " + studentGrades.containsKey("Charlie"));
System.out.println("Contains David? " + studentGrades.containsKey("David"));
// Removing an element by key
studentGrades.remove("Bob");
System.out.println("Grades after removing Bob: " + studentGrades);
// Iterating through HashMap using entrySet()
System.out.println("nIterating through grades:");
for (Map.Entry<String, Integer> entry : studentGrades.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// --- HashSet Example ---
System.out.println("n--- HashSet Example ---");
HashSet<String> uniqueCourses = new HashSet<>();
// Adding elements (only unique elements are stored)
uniqueCourses.add("Java Basics");
uniqueCourses.add("Data Structures");
uniqueCourses.add("Algorithms");
uniqueCourses.add("Java Basics"); // Duplicate, will not be added again
System.out.println("Unique Courses: " + uniqueCourses);
// Checking if an element exists
System.out.println("Contains 'Algorithms'? " + uniqueCourses.contains("Algorithms"));
System.out.println("Contains 'Python Basics'? " + uniqueCourses.contains("Python Basics"));
// Removing an element
uniqueCourses.remove("Data Structures");
System.out.println("Courses after removing 'Data Structures': " + uniqueCourses);
// Size of the set
System.out.println("Number of unique courses: " + uniqueCourses.size());
// Iterating through HashSet
System.out.println("nIterating through courses:");
for (String course : uniqueCourses) {
System.out.println("- " + course);
}
}
}
```
Output example:
```
--- HashMap Example ---
Student Grades: {Alice=97, Bob=88, Charlie=92}
Bob's grade: 88
Contains Charlie? true
Contains David? false
Grades after removing Bob: {Alice=97, Charlie=92}
Iterating through grades:
Alice: 97
Charlie: 92
--- HashSet Example ---
Unique Courses: [Java Basics, Algorithms, Data Structures]
Contains 'Algorithms'? true
Contains 'Python Basics'? false
Courses after removing 'Data Structures': [Java Basics, Algorithms]
Number of unique courses: 2
Iterating through courses:
- Java Basics
- Algorithms
```
๐ค **Your Challenge:** How would you retrieve all the *keys* from the `studentGrades` HashMap and store them in a `HashSet`? Give it a try! ๐
---
โค1