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
Day 22: Generics \- Code & Output
Here's your Telegram post for Day 23!

---

πŸš€ Day 23: Mastering Java! Today we're diving into `try-with-resources`, a powerful feature introduced in Java 7 for efficient resource management. No more manual `finally` blocks to close resources! πŸŽ‰ `try-with-resources` automatically ensures that any resource opened in its declaration is closed once the `try` block finishes, whether normally or due to an exception. It makes your code cleaner, safer, and easier to maintain. Let's explore how it simplifies handling file streams and other resources! πŸ’‘

```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ResourceManagementDemo {
public static void main(String[] args) {
// Imagine 'data.txt' exists and contains "Welcome to Day 23!"
// For actual execution, create a file named data.txt in your project root
// and add some text, e.g., "Welcome to Day 23!"

System.out.println("Attempting to read from data.txt...");

try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String firstLine = reader.readLine();
System.out.println("Content read: " + firstLine);
} catch (IOException e) {
System.err.println("🚨 Failed to read file: " + e.getMessage());
System.err.println("Make sure 'data.txt' exists in the same directory!");
}
}
}
```

Output example:
```
Attempting to read from data.txt...
Content read: Welcome to Day 23!
```
*(If `data.txt` does not exist, you will see the error message.)*

Challenge for you! πŸ’ͺ
Modify the code to write a few lines of text to a file named `output.txt` using `try-with-resources` with a `FileWriter`. Then, read and print those lines back to the console using another `try-with-resources` block! Don't forget to handle `IOException`! ✍️

---
Day 23: Try\-with\-Resources \(Resource Management\) \- Code & Output
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