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 19: Build Tools and Dependency Management \(Maven/Gradle\) \- Code & Output
πŸš€ Day 20: Mastering Dates and Times with `java.time`! πŸ—“οΈ

Tired of `java.util.Date`? Welcome to the modern era! Java 8 introduced the `java.time` package, a powerful, immutable, and thread-safe API for handling dates and times. Say goodbye to ambiguity and hello to clarity!

Today, we'll explore `LocalDate`, `LocalTime`, `LocalDateTime`, and learn how to manipulate and format them with ease. Get ready to master time like a pro! ⏰✨

```java
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class DateTimeExample {
public static void main(String[] args) {
// Current Date
LocalDate today = LocalDate.now();
System.out.println("Today's Date: " + today);

// Current Time
LocalTime now = LocalTime.now();
System.out.println("Current Time: " + now.truncatedTo(ChronoUnit.SECONDS)); // Truncate for cleaner output

// Current Date and Time
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("Current Date & Time: " + currentDateTime.truncatedTo(ChronoUnit.SECONDS));

// Creating specific dates and times
LocalDate birthday = LocalDate.of(1990, 5, 15);
System.out.println("My Birthday: " + birthday);

LocalTime meetingTime = LocalTime.of(10, 30, 0);
System.out.println("Meeting Time: " + meetingTime);

LocalDateTime specificEvent = LocalDateTime.of(2023, 11, 25, 18, 0);
System.out.println("Specific Event: " + specificEvent);

// Adding and subtracting
LocalDate nextWeek = today.plusWeeks(1);
System.out.println("Date next week: " + nextWeek);

LocalTime fiveHoursLater = now.plusHours(5);
System.out.println("Time 5 hours later: " + fiveHoursLater.truncatedTo(ChronoUnit.SECONDS));

// Formatting dates and times
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy HH:mm:ss");
String formattedDateTime = currentDateTime.format(formatter);
System.out.println("Formatted Date & Time: " + formattedDateTime);

DateTimeFormatter dateOnlyFormatter = DateTimeFormatter.ofPattern("EEEE, MMM d, yyyy");
String formattedDate = today.format(dateOnlyFormatter);
System.out.println("Formatted Today (custom): " + formattedDate);
}
}
```

Output example:
```
Today's Date: 2023-10-27
Current Time: 10:00:00
Current Date & Time: 2023-10-27T10:00:00
My Birthday: 1990-05-15
Meeting Time: 10:30
Specific Event: 2023-11-25T18:00
Date next week: 2023-11-03
Time 5 hours later: 15:00:00
Formatted Date & Time: 27 October 2023 10:00:00
Formatted Today (custom): Friday, Oct 27, 2023
```
*(Note: Actual date and time values in your output will vary based on when you run the code.)*

**Small Challenge:**
Can you calculate the number of days until the end of the current year using `LocalDate` and `ChronoUnit.DAYS.between()`? Share your code snippet in the comments! πŸ‘‡

---
Day 20: Working with Dates and Times \(java\.time\) \- Code & Output
πŸš€ Day 21 of our Java journey is here! Today, we're diving deep into two powerful OOP concepts: **Interfaces and Abstract Classes**. ✨

They are fundamental for achieving abstraction, polymorphism, and building flexible, scalable applications. Think of them as blueprints for behavior and structure, allowing you to define contracts and partial implementations. Let's unravel their magic with a practical example! πŸ‘‡

```java
// Interface: Defines a contract for movement
interface Movable {
void move(); // All methods in an interface are implicitly public and abstract (pre-Java 8)
}

// Abstract Class: Provides a partial implementation and defines abstract methods
abstract class Vehicle implements Movable {
protected String manufacturer;

public Vehicle(String manufacturer) {
this.manufacturer = manufacturer;
}

// Abstract method: Must be implemented by concrete subclasses
public abstract void startEngine();

// Concrete method: Can be used as is or overridden
public void stopEngine() {
System.out.println(manufacturer + " vehicle engine stopped.");
}

// Another abstract method
public abstract String getVehicleType();

// Concrete method using manufacturer
public String getInfo() {
return "Manufacturer: " + manufacturer + ", Type: " + getVehicleType();
}
}

// Concrete Class: Extends the abstract class and implements all abstract methods
class Car extends Vehicle {
public Car(String manufacturer) {
super(manufacturer);
}

@Override
public void startEngine() {
System.out.println(manufacturer + " car engine started. Vroom!");
}

@Override
public void move() {
System.out.println(manufacturer + " car is moving on the road.");
}

@Override
public String getVehicleType() {
return "Car";
}
}

public class AbstractionDemo {
public static void main(String[] args) {
// We cannot instantiate an abstract class or interface directly
// Vehicle myVehicle = new Vehicle("Generic"); // Compile-time error

Car myCar = new Car("Toyota");

myCar.startEngine();
myCar.move();
myCar.stopEngine();
System.out.println(myCar.getInfo());

System.out.println("n--- Polymorphism in action ---");
// Using an abstract class reference
Vehicle anotherVehicle = new Car("Honda");
anotherVehicle.startEngine();
anotherVehicle.move(); // Calls Car's move()
System.out.println(anotherVehicle.getInfo());

// Using an interface reference
Movable movableItem = new Car("Ford");
movableItem.move(); // Calls Car's move()
// movableItem.startEngine(); // Compile-time error: Movable doesn't have startEngine()
}
}
```

Output example:
```
Toyota car engine started. Vroom!
Toyota car is moving on the road.
Toyota vehicle engine stopped.
Manufacturer: Toyota, Type: Car

--- Polymorphism in action ---
Honda car engine started. Vroom!
Honda car is moving on the road.
Manufacturer: Honda, Type: Car
Ford car is moving on the road.
```

πŸ€” **Your Challenge:** What would happen if the `Car` class *didn't* implement the `move()` method (from `Movable`) or `startEngine()` method (from `Vehicle`)? Try it out and see the compiler's feedback! Share your thoughts! πŸ‘‡

---
Day 21: Interfaces and Abstract Classes \- Code & Output
✨ Day 22: Unlocking Generics in Java! ✨

Hello, Java learners! πŸ‘‹ Today we dive into one of Java's most powerful features for writing flexible and type-safe code: **Generics**!

Generics allow you to define classes, interfaces, and methods with type parameters. This means you can write a single piece of code that works with different types of objects, all while ensuring compile-time type safety. No more nasty `ClassCastException` at runtime! πŸ›‘οΈ

Let's explore how Generics help us create reusable and robust code!

```java
// A simple Generic Pair class
class Pair<K, V> {
private K key;
private V value;

public Pair(K key, V value) {
this.key = key;
this.value = value;
}

public K getKey() { return key; }
public V getValue() { return value; }

@Override
public String toString() {
return "Pair{" + "key=" + key + ", value=" + value + '}';
}
}

public class GenericsDay22 {
// A generic method to print any element
public static <T> void printElementInfo(T element) {
System.out.println("Element Type: " + element.getClass().getName());
System.out.println("Element Value: " + element);
System.out.println("---");
}

public static void main(String[] args) {
// Using our generic Pair class
Pair<String, Integer> studentGrade = new Pair<>("Alice", 95);
Pair<Integer, String> errorCode = new Pair<>(404, "Not Found");
Pair<Boolean, Double> sensorReading = new Pair<>(true, 25.75);

System.out.println("Student: " + studentGrade.getKey() + " got " + studentGrade.getValue());
System.out.println("Error: " + errorCode.getKey() + " means '" + errorCode.getValue() + "'");
System.out.println("Sensor Active: " + sensorReading.getKey() + ", Temp: " + sensorReading.getValue());
System.out.println("n");

// Using our generic method
printElementInfo("Hello Generics World!");
printElementInfo(12345);
printElementInfo(3.14159f);
}
}
```

Output example:
```
Student: Alice got 95
Error: 404 means 'Not Found'
Sensor Active: true, Temp: 25.75


Element Type: java.lang.String
Element Value: Hello Generics World!
---
Element Type: java.lang.Integer
Element Value: 12345
---
Element Type: java.lang.Float
Element Value: 3.14159
---
```

**πŸ’‘ Small Challenge:**
Create a generic method named `reverseList(List<T> list)` that takes a `List` of any type `T` and prints its elements in reverse order. Can you do it without creating a new list? (Hint: Think about `Collections.reverse` or manual iteration!)

Happy coding! Let's make our Java code smarter and safer! πŸš€

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

---