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
Which interface must a resource implement to be used in a try-with-resources statement?
Anonymous Quiz
13%
java.io.Serializable
13%
java.io.Closeable
13%
java.lang.AutoCloseable
63%
java.lang.Runnable
Hello, Java learners! πŸ‘‹ Welcome to **Day 24** of our journey!

Today, we're unlocking some of Java's most powerful and expressive features: **Lambda Expressions** and the **Streams API**. πŸš€ These concepts are cornerstones of modern Java, allowing you to write more concise, readable, and functional code for data processing. Get ready to transform your collections with ease and elegance! Let's dive in and see how they make your code shine. ✨

---

```java
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class Day24StreamDemo {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

System.out.println("Original numbers: " + numbers);
System.out.println("---");

// Example 1: Filtering even numbers and squaring them using Streams and Lambdas
List<Integer> squaredEvenNumbers = numbers.stream()
.filter(n -> n % 2 == 0) // Lambda as Predicate
.map(n -> n * n) // Lambda as Function
.collect(Collectors.toList()); // Terminal operation

System.out.println("Squared even numbers: " + squaredEvenNumbers);
System.out.println("---");

// Example 2: Sum of numbers greater than 5
long countGreaterThan5 = numbers.stream()
.filter(n -> n > 5) // Another Predicate lambda
.count(); // Terminal operation

System.out.println("Count of numbers greater than 5: " + countGreaterThan5);
System.out.println("---");

// Example 3: Finding the first odd number
Optional<Integer> firstOdd = numbers.stream()
.filter(n -> n % 2 != 0) // Predicate lambda
.findFirst(); // Terminal operation returning Optional

firstOdd.ifPresent(n -> System.out.println("First odd number: " + n)); // Lambda as Consumer
System.out.println("---");
}
}
```

---

Output example:
```
Original numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
---
Squared even numbers: [4, 16, 36, 64, 100]
---
Count of numbers greater than 5: 5
---
First odd number: 1
---
```

---

### Small Challenge:
Modify the `numbers` list. Can you find the *sum of the cubes* of all numbers less than 5? πŸ€” Try to achieve this in a single stream pipeline!

---
Day 24: Lambda Expressions and Streams API \- Code & Output
Which of the following is NOT a terminal operation in Java Streams?
Anonymous Quiz
25%
filter()
25%
collect()
25%
forEach()
25%
reduce()
🌟 **Day 25: Unit Testing (JUnit) - Making Your Java Code Bulletproof!** πŸš€

Hello, aspiring Java developers! Today marks a crucial milestone: diving into Unit Testing with JUnit. This isn't just about finding bugs; it's about building robust, reliable applications you can trust. JUnit is the de-facto standard for testing in Java, allowing us to write small, isolated tests for individual units of code (like a single method).

We'll learn how to structure tests, use the `@Test` annotation, and verify outcomes with powerful assertions like `assertEquals()`. Get ready to boost your code quality and confidently refactor! πŸ’ͺ

---

```java
// src/main/java/com/example/app/Calculator.java
package com.example.app;

public class Calculator {

public int add(int a, int b) {
return a + b;
}

public int subtract(int a, int b) {
return a - b;
}

public boolean isPositive(int number) {
return number > 0;
}
}
```

```java
// src/test/java/com/example/app/CalculatorTest.java
package com.example.app;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*; // Import static for easier access to assertions

public class CalculatorTest {

@Test // Marks this method as a JUnit test
void testAddPositiveNumbers() {
Calculator calculator = new Calculator();
int expected = 5;
int actual = calculator.add(2, 3);
assertEquals(expected, actual, "Adding 2 and 3 should result in 5");
}

@Test
void testAddZeroToNumber() {
Calculator calculator = new Calculator();
assertEquals(10, calculator.add(10, 0), "Adding zero should return the original number");
}

@Test
void testIsPositiveTrue() {
Calculator calculator = new Calculator();
assertTrue(calculator.isPositive(5), "5 should be considered positive");
}

@Test
void testIsPositiveFalse() {
Calculator calculator = new Calculator();
assertFalse(calculator.isPositive(-2), "-2 should be considered not positive");
assertFalse(calculator.isPositive(0), "0 should be considered not positive");
}
}
```

---

Output example:
```
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
```

---

πŸ’‘ **Your Challenge:**
1. Add a new JUnit test method (`@Test`) called `testSubtractNegativeNumbers` in `CalculatorTest`.
2. Test the `subtract` method with negative numbers (e.g., `calculator.subtract(5, -2)` should be 7). Use `assertEquals()`.
3. Explore and use `assertNotEquals()` in another test case for your `Calculator` class (e.g., ensuring `add(2,2)` is not `5`).
Happy testing! πŸ§ͺ

---
Day 25: Unit Testing \(JUnit\) \- Code & Output
Which of the following annotations is used in JUnit 5 to mark a method as a test method?
Anonymous Quiz
43%
πŸš€ Day 26: Diving into Basic Web Scraping with Jsoup! πŸ•ΈοΈ

Ever wondered how to programmatically extract information from websites? Today, we're unmasking the power of Jsoup, a fantastic Java library for working with real-world HTML. It makes fetching, parsing, and manipulating HTML documents a breeze. Get ready to turn web pages into structured data without breaking a sweat! Let's get scraping! ✨

```java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;

public class BasicWebScraper {
public static void main(String[] args) {
String url = "https://en.wikipedia.org/wiki/Main_Page"; // Target URL
try {
// 1. Connect to the URL and fetch the HTML document
Document doc = Jsoup.connect(url).get();

// 2. Extract the page title
String pageTitle = doc.title();
System.out.println("Page Title: " + pageTitle);

// 3. Extract the text from the first <h1> tag
String firstH1 = doc.select("h1").first().text();
System.out.println("First H1 Heading: " + firstH1);

} catch (IOException e) {
System.err.println("Error fetching or parsing the URL: " + e.getMessage());
} catch (NullPointerException e) {
System.err.println("Could not find the specified element. " + e.getMessage());
}
}
}
```

Output example:
Page Title: Main Page - Wikipedia
First H1 Heading: Main Page

**Small challenge:**
Modify the code to extract the text from the *first paragraph* (`<p>` tag) on the Wikipedia main page! Can you find the correct selector? πŸ€” Hint: `doc.select("p").first().text()` might be useful!

---
Day 26: Basic Web Scraping \(Jsoup\) \- Code & Output
Which Jsoup method chain is typically used to establish a connection to a URL and retrieve its HTML content as a `Document` object?
Anonymous Quiz
43%
Jsoup.parse(url)
14%
Jsoup.load(url)
43%
Jsoup.connect(url).get()
0%
Jsoup.fetch(url)
πŸš€ Day 27 is here, and we're diving into a game-changer: Spring Boot! ✨

Tired of complex configurations? Spring Boot simplifies Java development, letting you build robust, production-ready applications with minimal fuss. It's built on top of the Spring Framework but takes away much of the boilerplate thanks to auto-configuration and embedded servers. Let's write our first 'Hello World' with Spring Boot and see its magic!

```java
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;

// The @SpringBootApplication annotation is a convenience annotation that combines:
// @Configuration, @EnableAutoConfiguration, and @ComponentScan.
@SpringBootApplication
@RestController // Makes this class capable of handling web requests
public class Day27Application {

public static void main(String[] args) {
SpringApplication.run(Day27Application.class, args);
}

@GetMapping("/hello") // Maps HTTP GET requests to the /hello path
public String hello() {
return "Hello from Spring Boot!";
}
}
```

Output example:
(After running the application and navigating to `http://localhost:8080/hello` in your browser or using `curl`):
`Hello from Spring Boot!`

πŸ€” Small challenge:
1. Add another endpoint, e.g., `/greet` that returns "Greetings, Java Learner!" πŸ’‘
2. Bonus: Try changing the default port (8080) to something else (e.g., 8081) using an `application.properties` file!

---
Day 27: Introduction to Spring Boot \- Code & Output
Day 28: Multithreading and Concurrency \- Code & Output
Day 29: Basic Database Interaction \(JDBC\) \- Code & Output
Here's your Telegram post for Day 30!

---

πŸŽ‰ **Congratulations on Reaching Day 30!** πŸŽ‰

You've made incredible progress in just thirty days, diving into Java fundamentals! πŸš€ Now it's time to consolidate all your learning with a final project. How about building a simple *Command-Line To-Do List Manager*? πŸ“ It's a fantastic way to apply your understanding of classes, objects, methods, `ArrayList`s, and user input. Let's review some core concepts and get you thinking!

Here’s a quick look at a basic `Task` class and how you might manage a list of them:

```java
import java.util.ArrayList;
import java.util.List;

// Represents a single To-Do item
class Task {
private String description;
private boolean isCompleted;

public Task(String description) {
this.description = description;
this.isCompleted = false; // By default, a new task is not completed
}

public String getDescription() {
return description;
}

public boolean isCompleted() {
return isCompleted;
}

public void markCompleted() {
this.isCompleted = true;
}

@Override
public String toString() {
return "[" + (isCompleted ? "βœ…" : "⏳") + "] " + description;
}
}

// Main class to demonstrate To-Do list management
public class Day30Review {
public static void main(String[] args) {
List<Task> myTasks = new ArrayList<>(); // Use ArrayList for dynamic size

System.out.println("--- Initial To-Do List ---");
myTasks.add(new Task("Learn Java basics"));
myTasks.add(new Task("Start final project idea"));
myTasks.add(new Task("Review OOP concepts"));

for (Task task : myTasks) {
System.out.println(task);
}

System.out.println("n--- Updating Task Status ---");
// Mark the first task as completed
if (!myTasks.isEmpty()) {
myTasks.get(0).markCompleted();
System.out.println("Marked '" + myTasks.get(0).getDescription() + "' as completed.");
}

System.out.println("n--- Updated To-Do List ---");
for (Task task : myTasks) {
System.out.println(task);
}
}
}
```

Output example:
```
--- Initial To-Do List ---
[⏳] Learn Java basics
[⏳] Start final project idea
[⏳] Review OOP concepts

--- Updating Task Status ---
Marked 'Learn Java basics' as completed.

--- Updated To-Do List ---
[βœ…] Learn Java basics
[⏳] Start final project idea
[⏳] Review OOP concepts
```

### Small Challenge:
Your challenge for your To-Do List Manager:
1. **Add User Input:** Implement `Scanner` to allow users to add new tasks.
2. **Remove Tasks:** Create a method that allows users to remove tasks by their index in the list.
3. **List by Status:** Add functionality to display *only* completed tasks or *only* pending tasks.

Ready to build something awesome? You've got this! πŸ’ͺ Don't forget to share your progress! #JavaLearning #Day30 #FinalProject #CodingChallenge

---
Day 30: Final Project Idea and Review \- Code & Output
Which of the following concepts is NOT directly demonstrated or primarily used in the provided `Day30Review` Java code for the To-Do List idea?
Anonymous Quiz
33%
A. Object-Oriented Programming (OOP) principles like encapsulation.
0%
B. Dynamic data structures using `ArrayList`.
33%
C. Basic input/output operations for user interaction.
33%
D. Iterating over collections using a for-each loop.
Here's your Telegram post for Day 31 of your Java learning series!

---

πŸš€ Day 31: Ready to unlock the next level of Java concurrency?

Traditional threads are heavy, but Project Loom introduces **Virtual Threads**, lightweight wonders that revolutionize how we build scalable applications! 🀯 Imagine handling millions of concurrent tasks with ease, dramatically simplifying your code. We'll explore how Loom is driving a **Reactive Renaissance**, making complex asynchronous systems more manageable and efficient. Get ready to architect scalable futures! ✨

```java
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

public class VirtualThreadsDemo {

public static void main(String[] args) throws InterruptedException {
int numberOfTasks = 1_000_000; // Let's create a million "lightweight" tasks!
System.out.println("Starting " + numberOfTasks + " virtual tasks...");

Instant start = Instant.now();

// Using Executors.newVirtualThreadPerTaskExecutor() creates a new virtual thread
// for each submitted task, showcasing Loom's efficiency.
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, numberOfTasks).forEach(i ->
executor.submit(() -> {
// Simulate some work, perhaps a tiny delay or computation
try {
// In a real scenario, this might involve I/O operations
// which Virtual Threads are designed to efficiently handle.
// Thread.sleep(1); // Uncomment to simulate a tiny blocking operation per task
} catch (Exception e) {
Thread.currentThread().interrupt();
}
// System.out.println("Task " + i + " on " + Thread.currentThread().getName());
// (Commented out to avoid overwhelming console output)
})
);
} // The ExecutorService is automatically shut down here, waiting for all tasks.

Instant end = Instant.now();
Duration duration = Duration.between(start, end);
System.out.println("All " + numberOfTasks + " tasks completed in " + duration.toMillis() + " ms.");
}
}
```

Output example:
```
Starting 1000000 virtual tasks...
All 1000000 tasks completed in XXX ms.
```
*(The `XXX` will be a relatively small number, demonstrating the speed of creating and managing a million virtual threads compared to traditional threads.)*

πŸ’‘ **Challenge Time!**
Modify the code to:
1. Run the same `numberOfTasks` using a traditional thread pool, e.g., `Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())` or `Executors.newCachedThreadPool()`.
2. Compare the execution time and observe any differences. What limitations or overheads do you encounter with traditional threads that Virtual Threads overcome? (Hint: Think about thread creation cost and memory footprint!).

---
Here's your Telegram post for Day 36 of your advanced Java learning series! πŸš€

---

πŸš€ Day 36: Time to level up your concurrency game! Traditional thread pools hit limits, but what if you could have *millions* of lightweight threads? 🧡 Today, we're diving deep into **Project Loom's Virtual Threads**! ✨ Forget blocking I/O woes and embrace hyperscale concurrency with minimal resource overhead. Virtual Threads redefine how we write scalable Java applications, making blocking code efficient and easy to reason about. Get ready to unlock new levels of performance!

```java
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

public class VirtualThreadsExample {

private static void performTask(int id) {
try {
// Simulate a blocking I/O operation (e.g., database call, network request)
// This blocking call will "park" the virtual thread, freeing up its carrier thread.
Thread.sleep(Duration.ofMillis(10));
// System.out.println("Task " + id + " completed by " + Thread.currentThread()); // Uncomment to see thread names
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}

public static void main(String[] args) throws InterruptedException {
int numTasks = 10_000; // Let's launch 10,000 concurrent "blocking" tasks

System.out.println("--- Platform Threads Example (Limited Pool) ---");
Instant startPlatform = Instant.now();
// A small fixed pool to simulate resource contention with traditional threads
try (var executor = Executors.newFixedThreadPool(10)) {
IntStream.range(0, numTasks).forEach(i ->
executor.submit(() -> performTask(i))
);
} // Executor shuts down automatically
Instant endPlatform = Instant.now();
System.out.println("Platform Threads finished " + numTasks + " tasks in: " + Duration.between(startPlatform, endPlatform).toMillis() + " msn");


System.out.println("--- Virtual Threads Example ---");
Instant startVirtual = Instant.now();
// Executors.newVirtualThreadPerTaskExecutor() creates a new virtual thread for each task
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, numTasks).forEach(i ->
executor.submit(() -> performTask(i))
);
}
Instant endVirtual = Instant.now();
System.out.println("Virtual Threads finished " + numTasks + " tasks in: " + Duration.between(startVirtual, endVirtual).toMillis() + " ms");
}
}
```

Output example:
```
--- Platform Threads Example (Limited Pool) ---
Platform Threads finished 10000 tasks in: 10045 ms

--- Virtual Threads Example ---
Virtual Threads finished 10000 tasks in: 112 ms
```
*(Note: Actual times may vary based on your system and Java version. Java 21+ recommended for Project Loom features.)*

πŸ’‘ **Challenge:** Modify the `performTask` method to simulate a non-blocking operation (e.g., a simple CPU-bound calculation) instead of `Thread.sleep()`. How does the performance difference between platform and virtual threads change then? What does this tell you about the ideal use cases for virtual threads?

---
Day 37, advanced Java explorers! πŸš€ Today, we're diving deep into a modern concurrency marvel: Project Loom's `ScopedValue`. Say goodbye to the complexities and potential leaks of `ThreadLocal` in concurrent scenarios. `ScopedValue` offers a cleaner, safer, and more performant way to share immutable data within a lexical scope, perfectly aligning with Java's new Structured Concurrency paradigm. Get ready to rethink how you pass context across your application! πŸ’‘

```java
import java.util.concurrent.Executors;
import java.util.concurrent.ScopedValue;
import java.util.concurrent.TimeUnit;

public class ScopedValueDemo {

// Declare a ScopedValue instance
private static final ScopedValue<String> USER_ID = ScopedValue.newInstance();

public static void main(String[] args) throws InterruptedException {
System.out.println("Main thread - Before binding: " + USER_ID.orElse("N/A"));

// Bind a value to USER_ID within a specific scope
ScopedValue.where(USER_ID, "user-123")
.run(() -> {
System.out.println("Scoped block 1 - User ID: " + USER_ID.get());

// Virtual threads within this scope automatically "see" the bound value
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> {
System.out.println("Virtual Thread in Scoped block 1 - User ID: " + USER_ID.get());
processRequest(); // Method called within the scope
}).get(); // Wait for the virtual thread to complete
} catch (Exception e) {
e.printStackTrace();
}

// Nested scope demonstrates re-binding, which only affects the inner scope
ScopedValue.where(USER_ID, "user-456")
.run(() -> {
System.out.println("Nested Scoped block 2 - User ID: " + USER_ID.get());
});

System.out.println("Back in Scoped block 1 - User ID: " + USER_ID.get());
}); // The binding for "user-123" ends here

System.out.println("Main thread - After binding scope: " + USER_ID.orElse("N/A"));

// Demonstrate attempting to access from a new, unrelated virtual thread
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> {
System.out.println("Virtual Thread outside any explicit scope - User ID: " + USER_ID.orElse("N/A"));
}).get();
} catch (Exception e) {
e.printStackTrace();
}
}

private static void processRequest() {
// This method will automatically see the ScopedValue if called within its scope
System.out.println("Processing request with User ID: " + USER_ID.orElse("N/A"));
}
}
```

Output example:
```
Main thread - Before binding: N/A
Scoped block 1 - User ID: user-123
Virtual Thread in Scoped block 1 - User ID: user-123
Processing request with User ID: user-123
Nested Scoped block 2 - User ID: user-456
Back in Scoped block 1 - User ID: user-123
Main thread - After binding scope: N/A
Virtual Thread outside any explicit scope - User ID: N/A
```

Small challenge:
Modify the `processRequest()` method to try binding `USER_ID` to a *new* value within itself using `ScopedValue.where(USER_ID, "temp-user").run(...)`. Observe the behavior when `processRequest()` finishes and control returns to its caller. What does this tell you about the immutable and lexically scoped nature of `ScopedValue` bindings, especially compared to `ThreadLocal`? πŸ€”