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 for Day 16 of the Java learning series!

---

🌟 **Day 16: Mastering APIs with Java!** 🌟

Ever wondered how your apps can fetch data from the internet or interact with other services? Today, we unlock the power of **APIs (Application Programming Interfaces)**! 🚀

APIs are the backbone of modern web communication, allowing different software systems to talk to each other. In Java, we have powerful tools like the modern `HttpClient` (introduced in Java 11) and the traditional `HttpURLConnection` to make these interactions happen.

In this lesson, we'll focus on making a simple GET request using `HttpClient` to fetch data from a public API. Get ready to connect your Java applications to the world! 🌍

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.IOException;

public class ApiFetcher {
public static void main(String[] args) {
// Create an HttpClient instance
HttpClient client = HttpClient.newHttpClient();

// Build an HttpRequest
// We'll fetch a single post from JSONPlaceholder
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.GET() // Specifies the HTTP method as GET
.build();

try {
// Send the request and get the response
// HttpResponse.BodyHandlers.ofString() reads the response body as a String
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

// Print the status code and the response body
System.out.println("Status Code: " + response.statusCode());
System.out.println("Response Body:");
System.out.println(response.body());

} catch (IOException | InterruptedException e) {
System.err.println("An error occurred while making the HTTP request: " + e.getMessage());
e.printStackTrace();
}
}
}
```

Output example:
```
Status Code: 200
Response Body:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto"
}
```

### Small Challenge:
Your turn! 💪 Try fetching a list of *users* instead of posts from `https://jsonplaceholder.typicode.com/users`. Can you modify the code to print only the `name` and `email` of the *first* user in the list? (Hint: You'll need to parse the JSON response!)

---
Day 16: Working with APIs \(HttpClient/HttpURLConnection\) \- Code & Output
Here's your Telegram post for Day 17!

---

🎉 Day 17 is here, and we're tackling a crucial skill for modern Java development: **JSON Data Handling!** 🚀

JSON (JavaScript Object Notation) is everywhere – from web APIs to configuration files. Today, you'll learn how to seamlessly convert Java objects into JSON strings (serialization) and vice-versa (deserialization) using powerful libraries like **Jackson** or **Gson**. It's easier than you think and opens up a world of possibilities for your applications!

Let's dive into an example using Jackson. 🛠️

```java
// Product.java
// This is our simple Java POJO (Plain Old Java Object)
public class Product {
private int id;
private String name;
private double price;
private boolean available;

// Default constructor for deserialization
public Product() {}

public Product(int id, String name, double price, boolean available) {
this.id = id;
this.name = name;
this.price = price;
this.available = available;
}

// Getters and Setters (required by Jackson for serialization/deserialization)
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
public boolean isAvailable() { return available; }
public void setAvailable(boolean available) { this.available = available; }

@Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", price=" + price + ", available=" + available + "]";
}
}

// MainJsonHandler.java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;

public class MainJsonHandler {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();

try {
// --- 1. Serialize Java Object to JSON String ---
Product laptop = new Product(101, "SuperLaptop", 1200.00, true);
String jsonOutput = objectMapper.writeValueAsString(laptop);
System.out.println("Serialized Product to JSON:n" + jsonOutput);

// --- 2. Deserialize JSON String to Java Object ---
String jsonInput = "{"id":202,"name":"GamingMouse","price":75.50,"available":false}";
Product mouse = objectMapper.readValue(jsonInput, Product.class);
System.out.println("nDeserialized JSON to Product:n" + mouse);

} catch (IOException e) {
e.printStackTrace();
}
}
}
```

**Note:** To run this code, you'll need the Jackson dependency. For Maven, add this to your `pom.xml`:
```xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version> <!-- Use the latest version -->
</dependency>
```

Output example:
```
Serialized Product to JSON:
{"id":101,"name":"SuperLaptop","price":1200.0,"available":true}

Deserialized JSON to Product:
Product [id=202, name=GamingMouse, price=75.5, available=false]
```

### Your Challenge! 🚀
Modify the `MainJsonHandler` to:
1. Create a `List<Product>` with a few different product objects.
2. Serialize this `List<Product>` into a JSON array string.
3. Deserialize that JSON array string back into another `List<Product>`.
Can you do it? Show us your solution! 👇

Happy coding, and see you tomorrow! #JavaLearning #JSON #Jackson #Serialization #Programming

---
Day 17: JSON Data Handling \(Jackson/Gson\) \- Code & Output
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: Regular Expressions \- Code & Output
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?

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