๐ **Day 29: Basic Database Interaction (JDBC)!** ๐
Ever wondered how Java applications store and retrieve data from databases? Today's the day we demystify it with **JDBC (Java Database Connectivity)**! ๐คฏ
JDBC is the standard API for Java to interact with relational databases. We'll cover the fundamental steps: establishing a `Connection`, creating `Statement`s to execute SQL queries, and processing the `ResultSet`. Get ready to make your Java apps data-driven! Let's connect! ๐
```java
import java.sql.*;
public class SimpleJdbcApp {
// H2 In-Memory Database URL - simple, no separate server needed!
private static final String DB_URL = "jdbc:h2:mem:testdb";
private static final String USER = "sa"; // Default H2 user
private static final String PASS = ""; // Default H2 password (empty for H2 in-memory)
public static void main(String[] args) {
System.out.println("๐ Day 29: Basic JDBC Interaction! ๐");
System.out.println("Connecting to H2 In-Memory database...");
// Using try-with-resources ensures Connection and Statement are closed automatically
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement()) {
System.out.println("โ Database connected successfully!");
// 1. Create a table
String createTableSQL = "CREATE TABLE STUDENTS " +
"(id INT PRIMARY KEY AUTO_INCREMENT, " +
"name VARCHAR(255) NOT NULL, " +
"age INT)";
stmt.executeUpdate(createTableSQL); // executeUpdate for DDL (CREATE, ALTER, DROP) and DML (INSERT, UPDATE, DELETE)
System.out.println("โจ Table 'STUDENTS' created.");
// 2. Insert some data
String insertSQL1 = "INSERT INTO STUDENTS (name, age) VALUES ('Alice', 20)";
stmt.executeUpdate(insertSQL1);
String insertSQL2 = "INSERT INTO STUDENTS (name, age) VALUES ('Bob', 22)";
stmt.executeUpdate(insertSQL2);
System.out.println("โ Data inserted into STUDENTS table.");
// 3. Select and retrieve data
String selectSQL = "SELECT id, name, age FROM STUDENTS";
System.out.println("n--- Retrieving Student List ---");
// Using try-with-resources for ResultSet too, ensures it's closed
try (ResultSet rs = stmt.executeQuery(selectSQL)) { // executeQuery for SELECT statements
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
// Display values
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
} // ResultSet 'rs' is closed here automatically
} catch (SQLException e) {
System.err.println("โ An SQL error occurred: " + e.getMessage());
// In a real application, you'd log this more robustly
e.printStackTrace();
} finally {
System.out.println("n๐ก Database interaction complete. H2 In-Memory database is ephemeral (data is lost when app closes).");
}
}
}
```
Output example:
```
๐ Day 29: Basic JDBC Interaction! ๐
Connecting to H2 In-Memory database...
โ Database connected successfully!
โจ Table 'STUDENTS' created.
โ Data inserted into STUDENTS table.
--- Retrieving Student List ---
ID: 1, Name: Alice, Age: 20
ID: 2, Name: Bob, Age: 22
๐ก Database interaction complete. H2 In-Memory database is ephemeral (data is lost when app closes).
```
**Small Challenge:** ๐ช Can you add a new student and then write a `SELECT` query to retrieve *only* students older than 21? (Hint: Use `executeUpdate()` for the new student and add a `WHERE` clause to your `SELECT` query! For example: `SELECT ... FROM STUDENTS WHERE age > 21`).
---
Ever wondered how Java applications store and retrieve data from databases? Today's the day we demystify it with **JDBC (Java Database Connectivity)**! ๐คฏ
JDBC is the standard API for Java to interact with relational databases. We'll cover the fundamental steps: establishing a `Connection`, creating `Statement`s to execute SQL queries, and processing the `ResultSet`. Get ready to make your Java apps data-driven! Let's connect! ๐
```java
import java.sql.*;
public class SimpleJdbcApp {
// H2 In-Memory Database URL - simple, no separate server needed!
private static final String DB_URL = "jdbc:h2:mem:testdb";
private static final String USER = "sa"; // Default H2 user
private static final String PASS = ""; // Default H2 password (empty for H2 in-memory)
public static void main(String[] args) {
System.out.println("๐ Day 29: Basic JDBC Interaction! ๐");
System.out.println("Connecting to H2 In-Memory database...");
// Using try-with-resources ensures Connection and Statement are closed automatically
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement()) {
System.out.println("โ Database connected successfully!");
// 1. Create a table
String createTableSQL = "CREATE TABLE STUDENTS " +
"(id INT PRIMARY KEY AUTO_INCREMENT, " +
"name VARCHAR(255) NOT NULL, " +
"age INT)";
stmt.executeUpdate(createTableSQL); // executeUpdate for DDL (CREATE, ALTER, DROP) and DML (INSERT, UPDATE, DELETE)
System.out.println("โจ Table 'STUDENTS' created.");
// 2. Insert some data
String insertSQL1 = "INSERT INTO STUDENTS (name, age) VALUES ('Alice', 20)";
stmt.executeUpdate(insertSQL1);
String insertSQL2 = "INSERT INTO STUDENTS (name, age) VALUES ('Bob', 22)";
stmt.executeUpdate(insertSQL2);
System.out.println("โ Data inserted into STUDENTS table.");
// 3. Select and retrieve data
String selectSQL = "SELECT id, name, age FROM STUDENTS";
System.out.println("n--- Retrieving Student List ---");
// Using try-with-resources for ResultSet too, ensures it's closed
try (ResultSet rs = stmt.executeQuery(selectSQL)) { // executeQuery for SELECT statements
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
// Display values
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
} // ResultSet 'rs' is closed here automatically
} catch (SQLException e) {
System.err.println("โ An SQL error occurred: " + e.getMessage());
// In a real application, you'd log this more robustly
e.printStackTrace();
} finally {
System.out.println("n๐ก Database interaction complete. H2 In-Memory database is ephemeral (data is lost when app closes).");
}
}
}
```
Output example:
```
๐ Day 29: Basic JDBC Interaction! ๐
Connecting to H2 In-Memory database...
โ Database connected successfully!
โจ Table 'STUDENTS' created.
โ Data inserted into STUDENTS table.
--- Retrieving Student List ---
ID: 1, Name: Alice, Age: 20
ID: 2, Name: Bob, Age: 22
๐ก Database interaction complete. H2 In-Memory database is ephemeral (data is lost when app closes).
```
**Small Challenge:** ๐ช Can you add a new student and then write a `SELECT` query to retrieve *only* students older than 21? (Hint: Use `executeUpdate()` for the new student and add a `WHERE` clause to your `SELECT` query! For example: `SELECT ... FROM STUDENTS WHERE age > 21`).
---
Which JDBC object is primarily used to retrieve and process the results returned by executing a SQL SELECT query?
Anonymous Quiz
25%
A) java.sql.Connection
13%
B) java.sql.Statement
63%
C) java.sql.ResultSet
0%
D) java.sql.DriverManager
Which of the following is typically the *first* crucial step when starting a new software development project?
Anonymous Quiz
0%
A. Writing all the code for the main features
0%
B. Deploying the application to a production server
88%
C. Defining requirements, planning, and designing the project structure
13%
D. Creating marketing materials for the finished product
Day 32! ๐ We're diving deep into the future of Java concurrency: **Structured Concurrency with Project Loom**. Forget the old "thread-per-request" headaches and complex `CompletableFuture` chains for error handling. With Virtual Threads and `StructuredTaskScope`, you can orchestrate multiple concurrent operations as a single unit, ensuring cleaner code, automatic error propagation, and efficient resource management. This paradigm shift will revolutionize how we build scalable, resilient services. Get ready to rethink your concurrency strategies! โจ
```java
import java.time.Duration;
import java.util.concurrent.Future;
import java.util.concurrent.StructuredTaskScope;
import java.util.random.RandomGenerator;
public class StructuredConcurrencyExample {
record UserData(String name, int id) {}
record Order(String itemId, int userId) {}
public static void main(String[] args) throws InterruptedException {
System.out.println("๐ Day 32: Starting Structured Concurrency with Virtual Threads!");
long startTime = System.currentTimeMillis();
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<UserData> userFuture = scope.fork(() -> {
System.out.println(" [User Service] Fetching user data on: " + Thread.currentThread());
Thread.sleep(Duration.ofMillis(RandomGenerator.getDefault().nextInt(200, 500)));
return new UserData("Alice", 123);
});
Future<Order> orderFuture = scope.fork(() -> {
System.out.println(" [Order Service] Fetching order data on: " + Thread.currentThread());
Thread.sleep(Duration.ofMillis(RandomGenerator.getDefault().nextInt(300, 800)));
// Simulate a potential failure for demonstration
// if (RandomGenerator.getDefault().nextBoolean()) {
// throw new RuntimeException("Failed to fetch orders!");
// }
return new Order("BOOK-456", 123);
});
// Wait for all subtasks to complete or for one to fail
scope.join();
// If any subtask failed, this will re-throw the exception
scope.throwIfFailed();
UserData user = userFuture.resultNow();
Order order = orderFuture.resultNow();
System.out.println("โ All tasks completed successfully!");
System.out.println("User: " + user);
System.out.println("Order: " + order);
} catch (Exception e) {
System.err.println("โ One or more tasks failed: " + e.getMessage());
}
long endTime = System.currentTimeMillis();
System.out.println("Total execution time: " + (endTime - startTime) + "ms");
System.out.println("Main thread: " + Thread.currentThread());
}
}
```
Output example:
```
๐ Day 32: Starting Structured Concurrency with Virtual Threads!
[User Service] Fetching user data on: VirtualThread[...]/run-scope-1
[Order Service] Fetching order data on: VirtualThread[...]/run-scope-2
โ All tasks completed successfully!
User: UserData[name=Alice, id=123]
Order: Order[itemId=BOOK-456, userId=123]
Total execution time: 785ms
Main thread: main
```
*(Note: Execution time will vary due to random delays. The thread names will show `VirtualThread[...]`.)*
**Small Challenge:**
Uncomment the `// if (RandomGenerator.getDefault().nextBoolean()) { throw new RuntimeException("Failed to fetch orders!"); }` line in the `orderFuture` task. Run the code multiple times and observe how `StructuredTaskScope.ShutdownOnFailure` automatically handles the error, potentially cancelling the other tasks and propagating the exception. How does this compare to traditional `CompletableFuture` error handling? ๐ค
---
```java
import java.time.Duration;
import java.util.concurrent.Future;
import java.util.concurrent.StructuredTaskScope;
import java.util.random.RandomGenerator;
public class StructuredConcurrencyExample {
record UserData(String name, int id) {}
record Order(String itemId, int userId) {}
public static void main(String[] args) throws InterruptedException {
System.out.println("๐ Day 32: Starting Structured Concurrency with Virtual Threads!");
long startTime = System.currentTimeMillis();
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<UserData> userFuture = scope.fork(() -> {
System.out.println(" [User Service] Fetching user data on: " + Thread.currentThread());
Thread.sleep(Duration.ofMillis(RandomGenerator.getDefault().nextInt(200, 500)));
return new UserData("Alice", 123);
});
Future<Order> orderFuture = scope.fork(() -> {
System.out.println(" [Order Service] Fetching order data on: " + Thread.currentThread());
Thread.sleep(Duration.ofMillis(RandomGenerator.getDefault().nextInt(300, 800)));
// Simulate a potential failure for demonstration
// if (RandomGenerator.getDefault().nextBoolean()) {
// throw new RuntimeException("Failed to fetch orders!");
// }
return new Order("BOOK-456", 123);
});
// Wait for all subtasks to complete or for one to fail
scope.join();
// If any subtask failed, this will re-throw the exception
scope.throwIfFailed();
UserData user = userFuture.resultNow();
Order order = orderFuture.resultNow();
System.out.println("โ All tasks completed successfully!");
System.out.println("User: " + user);
System.out.println("Order: " + order);
} catch (Exception e) {
System.err.println("โ One or more tasks failed: " + e.getMessage());
}
long endTime = System.currentTimeMillis();
System.out.println("Total execution time: " + (endTime - startTime) + "ms");
System.out.println("Main thread: " + Thread.currentThread());
}
}
```
Output example:
```
๐ Day 32: Starting Structured Concurrency with Virtual Threads!
[User Service] Fetching user data on: VirtualThread[...]/run-scope-1
[Order Service] Fetching order data on: VirtualThread[...]/run-scope-2
โ All tasks completed successfully!
User: UserData[name=Alice, id=123]
Order: Order[itemId=BOOK-456, userId=123]
Total execution time: 785ms
Main thread: main
```
*(Note: Execution time will vary due to random delays. The thread names will show `VirtualThread[...]`.)*
**Small Challenge:**
Uncomment the `// if (RandomGenerator.getDefault().nextBoolean()) { throw new RuntimeException("Failed to fetch orders!"); }` line in the `orderFuture` task. Run the code multiple times and observe how `StructuredTaskScope.ShutdownOnFailure` automatically handles the error, potentially cancelling the other tasks and propagating the exception. How does this compare to traditional `CompletableFuture` error handling? ๐ค
---
Hey everyone! We're starting again from Day 1 so everyone can build a strong foundation by learning everything from the basics this time.
โค1
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! ๐ง โจ
---