Java for beginners
406 subscribers
49 photos
29 links
Learn Java daily with bite-sized lessons, practical code examples, output previews, and fun quizzes.
Download Telegram
Here's your Telegram post and quiz for Day 27!

---

**๐ŸŒŸ Day 27: Introduction to Spring Boot ๐Ÿš€**

Ready for something game-changing? Today, we're diving into Spring Boot โ€“ the powerhouse framework that makes building robust, production-ready Java applications a breeze! ๐ŸŽ‰ Say goodbye to complex configurations and hello to convention over configuration, embedded servers, and rapid development. We'll build our very first 'Hello World' REST API, showcasing just how easy it is to get started. Let's make some magic! โœจ

```java
// SpringBootDemoApplication.java
// This is your main application entry point.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication // Marks this as a Spring Boot application
public class SpringBootDemoApplication {

public static void main(String[] args) {
// This line launches the Spring Boot application
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}

// HelloController.java
// This would typically be in a separate file (e.g., com.example.demo.controller)
// It handles incoming web requests.
@RestController // Marks this class as a REST controller
class HelloController {

// Maps HTTP GET requests to the "/hello" path
@GetMapping("/hello")
public String sayHello() {
return "Hello from Spring Boot! ๐Ÿ‘‹"; // The response sent to the client
}
}
```

**How to run (conceptual):**
1. Set up a Spring Boot project (e.g., using Spring Initializr).
2. Place `SpringBootDemoApplication.java` and `HelloController.java` in appropriate packages (e.g., `com.example.demo`).
3. Run the `main` method in `SpringBootDemoApplication`.
4. Open your browser and navigate to `http://localhost:8080/hello`.

**Output example:**
When you open `http://localhost:8080/hello` in your browser:

```
Hello from Spring Boot! ๐Ÿ‘‹
```

**Small Challenge:**
Can you add another endpoint to our `HelloController`? Create a new method mapped to `/greet` that returns the string "Greetings, Java Learner! Happy coding! ๐Ÿ’ช".

---
๐Ÿš€ Day 28: Dive into the fascinating world of **Multithreading and Concurrency** in Java! ๐Ÿคฏ Ever wanted your program to do multiple things *simultaneously*? That's what multithreading empowers you to do! We'll explore how to create and manage independent threads of execution using `Runnable` and `Thread`. Get ready to unlock parallel processing power, but also learn about the cool challenges it brings! ๐Ÿ’ช

Here's a simple example demonstrating concurrent execution and a common pitfall:

```java
// Counter.java
class Counter {
int count = 0; // This shared resource is not thread-safe

public void increment() {
// Simulate some work being done
try {
Thread.sleep(1); // Small delay to increase chance of race condition
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
count++;
}

public int getCount() {
return count;
}
}

// Task.java
class Task implements Runnable {
private Counter sharedCounter;
private String name;
private int incrementsPerThread;

public Task(Counter counter, String name, int increments) {
this.sharedCounter = counter;
this.name = name;
this.incrementsPerThread = increments;
}

@Override
public void run() {
System.out.println(name + " starting...");
for (int i = 0; i < incrementsPerThread; i++) {
sharedCounter.increment();
}
System.out.println(name + " finished.");
}
}

// MultithreadingExample.java
public class MultithreadingExample {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
int numIncrementsPerThread = 1000;
int numThreads = 2;

// Create two threads, each incrementing the same counter
Thread t1 = new Thread(new Task(counter, "Worker-1", numIncrementsPerThread));
Thread t2 = new Thread(new Task(counter, "Worker-2", numIncrementsPerThread));

// Start both threads
t1.start();
t2.start();

// Wait for both threads to complete their execution
t1.join(); // main thread waits for t1 to finish
t2.join(); // main thread waits for t2 to finish

System.out.println("nExpected Final Counter Value: " + (numIncrementsPerThread * numThreads));
System.out.println("Actual Final Counter Value: " + counter.getCount());
}
}
```

Output example:
```
Worker-1 starting...
Worker-2 starting...
Worker-1 finished.
Worker-2 finished.

Expected Final Counter Value: 2000
Actual Final Counter Value: 1978 (This value will vary due to race condition, always less than expected)
```

๐Ÿ’ก Challenge Time! Why is the `Actual Final Counter Value` often less than the `Expected` one? ๐Ÿค” This is a classic **race condition**! Your mission: Modify the `increment()` method in the `Counter` class using the `synchronized` keyword to ensure thread-safe increments and always get the correct final value! Share your solution in the comments! ๐Ÿ‘‡

---
Day 28: Multithreading and Concurrency \- Code & Output
๐Ÿš€ **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`).

---
Day 29: Basic Database Interaction \(JDBC\) \- Code & Output
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
Day 30: Final Project Idea and Review \- Code & Output
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? ๐Ÿค”

---
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
๐ŸŽ‰ **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! ๐Ÿ‘‡

---
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!

---
โค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; ```
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: Conditional Statements \(if, else if, else\) \- Code & Output