Here's your Telegram post for Day 18 of the Java learning series! 🚀
---
🎉 **Day 18: Mastering Regular Expressions in Java!** 🎉
Hey Java Learners! 👋 Today, we're unlocking a superpower for text manipulation: Regular Expressions (Regex)! 🕵️♀️ Ever needed to validate input formats, search for complex patterns, or extract specific data from large strings? Regex is your ultimate tool!
In Java, the `java.util.regex` package provides the `Pattern` and `Matcher` classes to work with regex. `Pattern` compiles your regex into an object, and `Matcher` uses that pattern to perform search operations on a given input string. Let's dive into an example! ✨
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexFun {
public static void main(String[] args) {
String text = "Hello world! My email is example@domain.com, and another one is user123@sub.net. Don't forget my number: 12345.";
// Regex to find email addresses
String emailRegex = "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b";
Pattern pattern = Pattern.compile(emailRegex);
Matcher matcher = pattern.matcher(text);
System.out.println("🔍 Finding email addresses:");
while (matcher.find()) {
System.out.println("Found: " + matcher.group());
}
System.out.println("n🔢 Finding all numbers (one or more digits):");
String numberRegex = "\d+";
Pattern numberPattern = Pattern.compile(numberRegex);
Matcher numberMatcher = numberPattern.matcher(text);
while (numberMatcher.find()) {
System.out.println("Number found: " + numberMatcher.group());
}
}
}
```
Output example:
```
🔍 Finding email addresses:
Found: example@domain.com
Found: user123@sub.net
🔢 Finding all numbers (one or more digits):
Number found: 12345
```
### Small Challenge:
Can you modify the `emailRegex` to *also* find phone numbers like `123-456-7890` or `(123) 456-7890` in the same text, perhaps by creating a new `Pattern` and `Matcher`? Or, try to find all words starting with "D" or "d"! 💡
---
---
🎉 **Day 18: Mastering Regular Expressions in Java!** 🎉
Hey Java Learners! 👋 Today, we're unlocking a superpower for text manipulation: Regular Expressions (Regex)! 🕵️♀️ Ever needed to validate input formats, search for complex patterns, or extract specific data from large strings? Regex is your ultimate tool!
In Java, the `java.util.regex` package provides the `Pattern` and `Matcher` classes to work with regex. `Pattern` compiles your regex into an object, and `Matcher` uses that pattern to perform search operations on a given input string. Let's dive into an example! ✨
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexFun {
public static void main(String[] args) {
String text = "Hello world! My email is example@domain.com, and another one is user123@sub.net. Don't forget my number: 12345.";
// Regex to find email addresses
String emailRegex = "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b";
Pattern pattern = Pattern.compile(emailRegex);
Matcher matcher = pattern.matcher(text);
System.out.println("🔍 Finding email addresses:");
while (matcher.find()) {
System.out.println("Found: " + matcher.group());
}
System.out.println("n🔢 Finding all numbers (one or more digits):");
String numberRegex = "\d+";
Pattern numberPattern = Pattern.compile(numberRegex);
Matcher numberMatcher = numberPattern.matcher(text);
while (numberMatcher.find()) {
System.out.println("Number found: " + numberMatcher.group());
}
}
}
```
Output example:
```
🔍 Finding email addresses:
Found: example@domain.com
Found: user123@sub.net
🔢 Finding all numbers (one or more digits):
Number found: 12345
```
### Small Challenge:
Can you modify the `emailRegex` to *also* find phone numbers like `123-456-7890` or `(123) 456-7890` in the same text, perhaps by creating a new `Pattern` and `Matcher`? Or, try to find all words starting with "D" or "d"! 💡
---
Which `Matcher` class method is used to attempt to find the next subsequence of the input sequence that matches the pattern?
Anonymous Quiz
25%
A) matches()
0%
B) lookingAt()
75%
C) find()
0%
D) group()
🚀 Day 19: Build Tools & Dependency Management (Maven/Gradle)! 🛠️
Today, we dive into the indispensable world of build tools! Ever wondered how large Java projects manage complex compilations, tests, and external libraries? Maven and Gradle are your answers! They automate tasks like compiling code, running tests, packaging applications, and most crucially, managing all your project's dependencies. Say goodbye to manual JAR file management and hello to efficient, reproducible builds! Let's explore why these tools are vital for any serious Java developer. 📦🔗
```java
// src/main/java/com/example/app/SimpleApp.java
package com.example.app;
public class SimpleApp {
public static void main(String[] args) {
String appName = "My First Built Java App";
int version = 1;
System.out.println("--- " + appName + " v" + version + " ---");
System.out.println("This application demonstrates a simple Java program.");
System.out.println("It's designed to be compiled and run using a build tool like Maven or Gradle.");
System.out.println("Build tools help manage dependencies, compile code, and package applications.");
System.out.println("--- End of Application ---");
}
}
```
Output example:
```
--- My First Built Java App v1 ---
This application demonstrates a simple Java program.
It's designed to be compiled and run using a build tool like Maven or Gradle.
Build tools help manage dependencies, compile code, and package applications.
--- End of Application ---
```
💡 **Small Challenge:** Imagine you need to add an external library, say Apache Commons Lang, to your Java project. How would using Maven or Gradle simplify the process of including this library and all its transitive dependencies compared to manually downloading JARs?
---
Today, we dive into the indispensable world of build tools! Ever wondered how large Java projects manage complex compilations, tests, and external libraries? Maven and Gradle are your answers! They automate tasks like compiling code, running tests, packaging applications, and most crucially, managing all your project's dependencies. Say goodbye to manual JAR file management and hello to efficient, reproducible builds! Let's explore why these tools are vital for any serious Java developer. 📦🔗
```java
// src/main/java/com/example/app/SimpleApp.java
package com.example.app;
public class SimpleApp {
public static void main(String[] args) {
String appName = "My First Built Java App";
int version = 1;
System.out.println("--- " + appName + " v" + version + " ---");
System.out.println("This application demonstrates a simple Java program.");
System.out.println("It's designed to be compiled and run using a build tool like Maven or Gradle.");
System.out.println("Build tools help manage dependencies, compile code, and package applications.");
System.out.println("--- End of Application ---");
}
}
```
Output example:
```
--- My First Built Java App v1 ---
This application demonstrates a simple Java program.
It's designed to be compiled and run using a build tool like Maven or Gradle.
Build tools help manage dependencies, compile code, and package applications.
--- End of Application ---
```
💡 **Small Challenge:** Imagine you need to add an external library, say Apache Commons Lang, to your Java project. How would using Maven or Gradle simplify the process of including this library and all its transitive dependencies compared to manually downloading JARs?
---
Which of the following is NOT a primary function of build tools like Maven or Gradle in a Java project?
Anonymous Quiz
0%
A. Automating compilation and packaging of code.
14%
B. Managing project dependencies and their versions.
71%
C. Providing a graphical user interface (GUI) for coding.
14%
D. Running tests and generating reports.
🚀 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! 👇
---
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! 👇
---
Which of the following is a key advantage of using classes from the `java.time` package (like `LocalDate`, `LocalDateTime`) over the legacy `java.util.Date` class?
Anonymous Quiz
0%
They are mutable, allowing easy modification of date/time objects.
20%
They are not thread-safe, requiring external synchronization.
80%
They provide a clearer, more consistent API and are immutable and thread-safe.
0%
They only support local date and time representations, without timezone awareness.
🚀 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! 👇
---
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! 👇
---
Which statement is TRUE regarding Java Interfaces and Abstract Classes?
Anonymous Quiz
0%
An interface can have concrete methods, while an abstract class cannot.
60%
A class can implement multiple interfaces but can extend only one abstract class.
20%
An abstract class can be instantiated, but an interface cannot.
20%
All methods in an abstract class must be declared `abstract`.
✨ 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! 🚀
---
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! 🚀
---
What is the primary benefit of using Generics in Java?
Anonymous Quiz
0%
A. To increase runtime performance of applications.
71%
B. To provide compile-time type checking and eliminate the need for explicit casts.
0%
C. To allow methods to return multiple values.
29%
D. To reduce the memory footprint of objects.
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: 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`! ✍️
---
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!
---
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!
---