π Java Learning Series - Day 18 π
Hello, Java learners! π Today, we're diving into the powerful world of **Regular Expressions** (Regex)! π Regular expressions are sequence of characters that define a search pattern. They are incredibly useful for searching, manipulating, and validating strings. Think of them as super-charged pattern matchers for text data! In Java, we use the `java.util.regex` package, featuring the `Pattern` and `Matcher` classes, to harness this power. Let's explore how to find and replace text using regex! β¨
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexBasics {
public static void main(String[] args) {
String text = "Java is a powerful language. Version 1.8 is widely used, but Java 21 is out!";
// 1. Finding all occurrences of "Java" (case-insensitive)
Pattern javaPattern = Pattern.compile("java", Pattern.CASE_INSENSITIVE);
Matcher javaMatcher = javaPattern.matcher(text);
System.out.println("π Finding all 'Java' occurrences:");
while (javaMatcher.find()) {
System.out.println("Found: '" + javaMatcher.group() + "' at index " + javaMatcher.start());
}
// 2. Replacing all digits with a hash '#'
// "\d" is the regex for any digit (0-9)
String textWithNumbers = "My project ID is P123 and my build number is 4567.";
String replacedText = textWithNumbers.replaceAll("\d+", "#"); // \d+ matches one or more digits
System.out.println("nβοΈ Text after replacing digits: " + replacedText);
// 3. Checking if the entire string matches a pattern (e.g., starts with a letter and ends with a number)
Pattern specificPattern = Pattern.compile("^[A-Za-z].*\d$"); // Starts with letter, ends with digit
String validString = "HelloWorld1";
String invalidString = "1HelloWorld";
System.out.println("nβ Does '" + validString + "' match: " + specificPattern.matcher(validString).matches());
System.out.println("β Does '" + invalidString + "' match: " + specificPattern.matcher(invalidString).matches());
}
}
```
Output example:
```
π Finding all 'Java' occurrences:
Found: 'Java' at index 0
Found: 'Java' at index 48
βοΈ Text after replacing digits: My project ID is P# and my build number is #.
β Does 'HelloWorld1' match: true
β Does '1HelloWorld' match: false
```
### Small Challenge:
Can you modify the code to find and print all words that contain at least one digit in the original `text` variable? (Hint: Use `\b` for word boundaries and `\w*\d\w*` for words with digits). Good luck! π§ π‘
---
Hello, Java learners! π Today, we're diving into the powerful world of **Regular Expressions** (Regex)! π Regular expressions are sequence of characters that define a search pattern. They are incredibly useful for searching, manipulating, and validating strings. Think of them as super-charged pattern matchers for text data! In Java, we use the `java.util.regex` package, featuring the `Pattern` and `Matcher` classes, to harness this power. Let's explore how to find and replace text using regex! β¨
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexBasics {
public static void main(String[] args) {
String text = "Java is a powerful language. Version 1.8 is widely used, but Java 21 is out!";
// 1. Finding all occurrences of "Java" (case-insensitive)
Pattern javaPattern = Pattern.compile("java", Pattern.CASE_INSENSITIVE);
Matcher javaMatcher = javaPattern.matcher(text);
System.out.println("π Finding all 'Java' occurrences:");
while (javaMatcher.find()) {
System.out.println("Found: '" + javaMatcher.group() + "' at index " + javaMatcher.start());
}
// 2. Replacing all digits with a hash '#'
// "\d" is the regex for any digit (0-9)
String textWithNumbers = "My project ID is P123 and my build number is 4567.";
String replacedText = textWithNumbers.replaceAll("\d+", "#"); // \d+ matches one or more digits
System.out.println("nβοΈ Text after replacing digits: " + replacedText);
// 3. Checking if the entire string matches a pattern (e.g., starts with a letter and ends with a number)
Pattern specificPattern = Pattern.compile("^[A-Za-z].*\d$"); // Starts with letter, ends with digit
String validString = "HelloWorld1";
String invalidString = "1HelloWorld";
System.out.println("nβ Does '" + validString + "' match: " + specificPattern.matcher(validString).matches());
System.out.println("β Does '" + invalidString + "' match: " + specificPattern.matcher(invalidString).matches());
}
}
```
Output example:
```
π Finding all 'Java' occurrences:
Found: 'Java' at index 0
Found: 'Java' at index 48
βοΈ Text after replacing digits: My project ID is P# and my build number is #.
β Does 'HelloWorld1' match: true
β Does '1HelloWorld' match: false
```
### Small Challenge:
Can you modify the code to find and print all words that contain at least one digit in the original `text` variable? (Hint: Use `\b` for word boundaries and `\w*\d\w*` for words with digits). Good luck! π§ π‘
---
Which of the following regex metacharacters represents 'any single digit'?
Anonymous Quiz
11%
\s
11%
\w
44%
\d
33%
.
β¨ **Day 19: Mastering Java Build Tools & Dependency Management!** β¨
Hey Java learners! π Today we dive into the backbone of professional Java development: **Build Tools** like Maven and Gradle. π οΈ These tools are indispensable for automating tasks like compiling code, running tests, packaging applications, and most importantly, managing project dependencies. Say goodbye to manual JAR hell! π¦ They ensure your project builds consistently and efficiently, making collaboration a breeze.
Let's look at a simple Java application that leverages an external library β something build tools handle seamlessly!
```java
package com.example;
import org.apache.commons.lang3.StringUtils; // An external dependency!
public class App {
public static void main(String[] args) {
String originalMessage = "hello java world";
// StringUtils comes from Apache Commons Lang3, managed by Maven/Gradle!
String capitalizedMessage = StringUtils.capitalize(originalMessage);
System.out.println("Original String: " + originalMessage);
System.out.println("Capitalized String: " + capitalizedMessage);
System.out.println("nThis app uses an external library. Build tools like Maven or Gradle make integrating 'StringUtils' effortless by simply declaring it as a dependency!");
}
}
```
Output example:
```
Original String: hello java world
Capitalized String: Hello java world
This app uses an external library. Build tools like Maven or Gradle make integrating 'StringUtils' effortless by simply declaring it as a dependency!
```
**Small Challenge:** π‘
When you use Maven or Gradle, you don't manually download `.jar` files for libraries. What is the name of the central configuration file in a Maven project where you would declare `org.apache.commons:commons-lang3:3.12.0` as a dependency? (Hint: It's the Project Object Model!)
Happy coding! ππ
Hey Java learners! π Today we dive into the backbone of professional Java development: **Build Tools** like Maven and Gradle. π οΈ These tools are indispensable for automating tasks like compiling code, running tests, packaging applications, and most importantly, managing project dependencies. Say goodbye to manual JAR hell! π¦ They ensure your project builds consistently and efficiently, making collaboration a breeze.
Let's look at a simple Java application that leverages an external library β something build tools handle seamlessly!
```java
package com.example;
import org.apache.commons.lang3.StringUtils; // An external dependency!
public class App {
public static void main(String[] args) {
String originalMessage = "hello java world";
// StringUtils comes from Apache Commons Lang3, managed by Maven/Gradle!
String capitalizedMessage = StringUtils.capitalize(originalMessage);
System.out.println("Original String: " + originalMessage);
System.out.println("Capitalized String: " + capitalizedMessage);
System.out.println("nThis app uses an external library. Build tools like Maven or Gradle make integrating 'StringUtils' effortless by simply declaring it as a dependency!");
}
}
```
Output example:
```
Original String: hello java world
Capitalized String: Hello java world
This app uses an external library. Build tools like Maven or Gradle make integrating 'StringUtils' effortless by simply declaring it as a dependency!
```
**Small Challenge:** π‘
When you use Maven or Gradle, you don't manually download `.jar` files for libraries. What is the name of the central configuration file in a Maven project where you would declare `org.apache.commons:commons-lang3:3.12.0` as a dependency? (Hint: It's the Project Object Model!)
Happy coding! ππ
Which file is primarily used by Maven to define project dependencies, plugins, and the build lifecycle?
Anonymous Quiz
0%
build.gradle
100%
pom.xml
0%
settings.xml
Which `java.time` class is used to represent a date without a time or a time-zone, like '2023-10-27'?
Anonymous Quiz
33%
LocalDateTime
0%
LocalTime
50%
LocalDate
17%
Instant
Which of the following statements about Java interfaces is TRUE?
Anonymous Quiz
38%
An interface can have instance fields (non-static, non-final variables).
50%
A class can implement multiple interfaces.
0%
An interface can have a constructor.
13%
All methods in an interface must be abstract and public.
Here's your Telegram post for Day 22 on Java Generics! β¨
---
**Day 22: Generics - Type-Safe Code, Reimagined!** β¨
Ready to write more robust, reusable, and type-safe Java code? Today we're diving into Generics, a powerful feature that allows you to define classes, interfaces, and methods with a type parameter. This means fewer `ClassCastException`s at runtime and more compile-time safety! π Let's make our code shine by creating a simple generic `Box` class. π
```java
public class MyGenericBox<T> {
private T content;
public MyGenericBox(T content) {
this.content = content;
}
public T getContent() {
return content;
}
public void setContent(T content) {
this.content = content;
}
// A generic method example:
public static <U> void printBoxContentInfo(MyGenericBox<U> box) {
System.out.println("Box contains: " + box.getContent() +
" (Actual Type: " + box.getContent().getClass().getSimpleName() + ")");
}
public static void main(String[] args) {
// Box for String
MyGenericBox<String> stringBox = new MyGenericBox<>("Hello Generics");
System.out.println("String Box content: " + stringBox.getContent());
// Box for Integer
MyGenericBox<Integer> intBox = new MyGenericBox<>(123);
System.out.println("Integer Box content: " + intBox.getContent());
// Using the generic method with different box types
printBoxContentInfo(stringBox);
printBoxContentInfo(intBox);
// β Generics in action! This line would cause a compile-time error:
// stringBox.setContent(456); // Error: Incompatible types. Integer cannot be converted to String
}
}
```
Output example:
```
String Box content: Hello Generics
Integer Box content: 123
Box contains: Hello Generics (Actual Type: String)
Box contains: 123 (Actual Type: Integer)
```
**Small Challenge:**
Can you extend our understanding of generics? Create a generic `Pair<K, V>` class that can hold two different types of values (e.g., a key and a value). Then, instantiate it with `Pair<String, Integer>` and `Pair<Double, String>` and print their contents! π‘
---
---
**Day 22: Generics - Type-Safe Code, Reimagined!** β¨
Ready to write more robust, reusable, and type-safe Java code? Today we're diving into Generics, a powerful feature that allows you to define classes, interfaces, and methods with a type parameter. This means fewer `ClassCastException`s at runtime and more compile-time safety! π Let's make our code shine by creating a simple generic `Box` class. π
```java
public class MyGenericBox<T> {
private T content;
public MyGenericBox(T content) {
this.content = content;
}
public T getContent() {
return content;
}
public void setContent(T content) {
this.content = content;
}
// A generic method example:
public static <U> void printBoxContentInfo(MyGenericBox<U> box) {
System.out.println("Box contains: " + box.getContent() +
" (Actual Type: " + box.getContent().getClass().getSimpleName() + ")");
}
public static void main(String[] args) {
// Box for String
MyGenericBox<String> stringBox = new MyGenericBox<>("Hello Generics");
System.out.println("String Box content: " + stringBox.getContent());
// Box for Integer
MyGenericBox<Integer> intBox = new MyGenericBox<>(123);
System.out.println("Integer Box content: " + intBox.getContent());
// Using the generic method with different box types
printBoxContentInfo(stringBox);
printBoxContentInfo(intBox);
// β Generics in action! This line would cause a compile-time error:
// stringBox.setContent(456); // Error: Incompatible types. Integer cannot be converted to String
}
}
```
Output example:
```
String Box content: Hello Generics
Integer Box content: 123
Box contains: Hello Generics (Actual Type: String)
Box contains: 123 (Actual Type: Integer)
```
**Small Challenge:**
Can you extend our understanding of generics? Create a generic `Pair<K, V>` class that can hold two different types of values (e.g., a key and a value). Then, instantiate it with `Pair<String, Integer>` and `Pair<Double, String>` and print their contents! π‘
---
What is the primary benefit of using Generics in Java?
Anonymous Quiz
33%
A) To reduce the memory footprint of objects at runtime.
67%
B) To provide compile-time type checking and avoid ClassCastException errors.
0%
C) To allow objects to be serialized and deserialized more efficiently.
0%
D) To enable multiple inheritance for classes.
Here's your Telegram post for Day 23 of the Java learning series!
---
π Day 23: Try-with-Resources (Resource Management) π
Tired of manually closing your streams, files, or database connections? π Forgetting to close resources can lead to serious performance issues and resource leaks! Java 7+ introduced a brilliant feature to tackle this: `try-with-resources`.
It automatically closes any resource that implements the `AutoCloseable` interface once the `try` block finishes, *regardless* of whether an exception occurs. β¨ This means cleaner, safer, and more robust code with less boilerplate! Say goodbye to cumbersome `finally` blocks just for closing! π
Let's see this powerful construct in action:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ResourceManagementDemo {
public static void main(String[] args) {
// For this example, assume 'example.txt' exists in the same directory
// and contains at least one line, e.g., "Hello Try-with-Resources!"
String fileName = "example.txt";
System.out.println("Attempting to read from file: " + fileName);
// try-with-resources automatically closes FileReader and BufferedReader
try (FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line = bufferedReader.readLine(); // Read the first line
if (line != null) {
System.out.println("Successfully read: "" + line + """);
} else {
System.out.println("File is empty or could not read any line.");
}
} catch (IOException e) {
System.err.println("An error occurred while reading the file: " + e.getMessage());
// The resources are still automatically closed even if an exception happens here!
} finally {
System.out.println("Resources are guaranteed to be closed!");
}
}
}
```
Output example:
```
Attempting to read from file: example.txt
Successfully read: "Hello Try-with-Resources!"
Resources are guaranteed to be closed!
```
*(If `example.txt` contains "Hello Try-with-Resources!")*
**Small Challenge:**
Can you modify the code above to read and print *all* lines from `example.txt` until the end of the file is reached, still using the `try-with-resources` block? π€ What other common `AutoCloseable` resources can you think of besides file readers?
---
---
π Day 23: Try-with-Resources (Resource Management) π
Tired of manually closing your streams, files, or database connections? π Forgetting to close resources can lead to serious performance issues and resource leaks! Java 7+ introduced a brilliant feature to tackle this: `try-with-resources`.
It automatically closes any resource that implements the `AutoCloseable` interface once the `try` block finishes, *regardless* of whether an exception occurs. β¨ This means cleaner, safer, and more robust code with less boilerplate! Say goodbye to cumbersome `finally` blocks just for closing! π
Let's see this powerful construct in action:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ResourceManagementDemo {
public static void main(String[] args) {
// For this example, assume 'example.txt' exists in the same directory
// and contains at least one line, e.g., "Hello Try-with-Resources!"
String fileName = "example.txt";
System.out.println("Attempting to read from file: " + fileName);
// try-with-resources automatically closes FileReader and BufferedReader
try (FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line = bufferedReader.readLine(); // Read the first line
if (line != null) {
System.out.println("Successfully read: "" + line + """);
} else {
System.out.println("File is empty or could not read any line.");
}
} catch (IOException e) {
System.err.println("An error occurred while reading the file: " + e.getMessage());
// The resources are still automatically closed even if an exception happens here!
} finally {
System.out.println("Resources are guaranteed to be closed!");
}
}
}
```
Output example:
```
Attempting to read from file: example.txt
Successfully read: "Hello Try-with-Resources!"
Resources are guaranteed to be closed!
```
*(If `example.txt` contains "Hello Try-with-Resources!")*
**Small Challenge:**
Can you modify the code above to read and print *all* lines from `example.txt` until the end of the file is reached, still using the `try-with-resources` block? π€ What other common `AutoCloseable` resources can you think of besides file readers?
---
Which of the following best describes a 'functional interface' in the context of Java Lambda Expressions?
Anonymous Quiz
21%
An interface that contains only static methods.
71%
An interface with exactly one abstract method, which can be implemented by a lambda expression.
7%
An interface that can only be implemented by anonymous inner classes.
0%
An interface that has no methods at all.
Restart from Day 1?
Anonymous Poll
79%
πYes, let's start from the basics.
21%
βοΈ No, continue from where we left off.
Here's your Telegram post for Day 25 of the Java learning series!
---
π Day 25: Unit Testing (JUnit) π
It's time to build robust Java applications! Today, we dive into the world of Unit Testing with **JUnit**. π§ͺ Writing tests ensures your code behaves exactly as expected, catches bugs early, and makes refactoring a breeze. We'll learn how to create simple test cases to verify individual components (units) of your code. Let's make our code reliable! πͺ
```java
// Calculator.java - The class we want to test
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
// A simple method to demonstrate an edge case for testing
public int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("Cannot divide by zero");
}
return a / b;
}
}
```
```java
// CalculatorTest.java - Our JUnit test class
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*; // Import static assertions
public class CalculatorTest {
// Test method for the add operation
@Test
void testAdd() {
Calculator calculator = new Calculator();
// assertEquals(expected, actual, message)
assertEquals(5, calculator.add(2, 3), "2 + 3 should be 5");
assertEquals(0, calculator.add(-1, 1), "-1 + 1 should be 0");
assertEquals(-5, calculator.add(-2, -3), "-2 + -3 should be -5");
}
// Test method for the subtract operation
@Test
void testSubtract() {
Calculator calculator = new Calculator();
assertEquals(1, calculator.subtract(3, 2), "3 - 2 should be 1");
assertEquals(-5, calculator.subtract(0, 5), "0 - 5 should be -5");
assertEquals(0, calculator.subtract(7, 7), "7 - 7 should be 0");
}
// Test method for the multiply operation
@Test
void testMultiply() {
Calculator calculator = new Calculator();
assertEquals(6, calculator.multiply(2, 3), "2 * 3 should be 6");
assertEquals(0, calculator.multiply(5, 0), "5 * 0 should be 0");
assertEquals(-10, calculator.multiply(-2, 5), "-2 * 5 should be -10");
}
// Test method to verify division by zero throws an exception
@Test
void testDivideByZeroThrowsException() {
Calculator calculator = new Calculator();
// assertThrows(expectedType, executable, message)
assertThrows(IllegalArgumentException.class, () -> calculator.divide(10, 0),
"Dividing by zero should throw IllegalArgumentException");
}
// Example of a failing test (if you change expected to 4 for 2+3)
// @Test
// void testAddFailingExample() {
// Calculator calculator = new Calculator();
// assertEquals(4, calculator.add(2, 3), "2 + 3 should be 5 (this will fail)");
// }
}
```
Output example:
```
[INFO] Running CalculatorTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
```
**Challenge for you!** π‘
Add a new method `power(int base, int exponent)` to the `Calculator` class that calculates `base` raised to the power of `exponent`. Then, write a JUnit test method (`testPower()`) to verify its correctness. Don't forget edge cases like `exponent = 0` and `exponent = 1`!
---
---
π Day 25: Unit Testing (JUnit) π
It's time to build robust Java applications! Today, we dive into the world of Unit Testing with **JUnit**. π§ͺ Writing tests ensures your code behaves exactly as expected, catches bugs early, and makes refactoring a breeze. We'll learn how to create simple test cases to verify individual components (units) of your code. Let's make our code reliable! πͺ
```java
// Calculator.java - The class we want to test
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
// A simple method to demonstrate an edge case for testing
public int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("Cannot divide by zero");
}
return a / b;
}
}
```
```java
// CalculatorTest.java - Our JUnit test class
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*; // Import static assertions
public class CalculatorTest {
// Test method for the add operation
@Test
void testAdd() {
Calculator calculator = new Calculator();
// assertEquals(expected, actual, message)
assertEquals(5, calculator.add(2, 3), "2 + 3 should be 5");
assertEquals(0, calculator.add(-1, 1), "-1 + 1 should be 0");
assertEquals(-5, calculator.add(-2, -3), "-2 + -3 should be -5");
}
// Test method for the subtract operation
@Test
void testSubtract() {
Calculator calculator = new Calculator();
assertEquals(1, calculator.subtract(3, 2), "3 - 2 should be 1");
assertEquals(-5, calculator.subtract(0, 5), "0 - 5 should be -5");
assertEquals(0, calculator.subtract(7, 7), "7 - 7 should be 0");
}
// Test method for the multiply operation
@Test
void testMultiply() {
Calculator calculator = new Calculator();
assertEquals(6, calculator.multiply(2, 3), "2 * 3 should be 6");
assertEquals(0, calculator.multiply(5, 0), "5 * 0 should be 0");
assertEquals(-10, calculator.multiply(-2, 5), "-2 * 5 should be -10");
}
// Test method to verify division by zero throws an exception
@Test
void testDivideByZeroThrowsException() {
Calculator calculator = new Calculator();
// assertThrows(expectedType, executable, message)
assertThrows(IllegalArgumentException.class, () -> calculator.divide(10, 0),
"Dividing by zero should throw IllegalArgumentException");
}
// Example of a failing test (if you change expected to 4 for 2+3)
// @Test
// void testAddFailingExample() {
// Calculator calculator = new Calculator();
// assertEquals(4, calculator.add(2, 3), "2 + 3 should be 5 (this will fail)");
// }
}
```
Output example:
```
[INFO] Running CalculatorTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
```
**Challenge for you!** π‘
Add a new method `power(int base, int exponent)` to the `Calculator` class that calculates `base` raised to the power of `exponent`. Then, write a JUnit test method (`testPower()`) to verify its correctness. Don't forget edge cases like `exponent = 0` and `exponent = 1`!
---
Which JUnit 5 annotation is used to mark a method as a test method?
Anonymous Quiz
0%
A) @BeforeEach
63%
B) @Test
13%
C) @TestSuite
25%
D) @RunTest
π Day 26: Diving into Basic Web Scraping with Jsoup! πΈοΈ Ever wished you could automatically pull information from websites? Today, we're exploring the fascinating world of web scraping using Jsoup, a robust Java library. Jsoup simplifies parsing HTML, navigating the DOM, and extracting specific data with familiar CSS selectors. It's an essential skill for data collection, monitoring, and automation. Let's write some code! π§βπ»
Here's how to get started with Jsoup to extract a page title and a paragraph:
```java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class SimpleWebScraper {
public static void main(String[] args) {
String url = "http://example.com/"; // A simple, static page for demonstration
try {
// 1. Connect to the URL and get the HTML document
// Jsoup.connect(url) creates a Connection object
// .get() fetches the URL and parses the HTML into a Document object
Document document = Jsoup.connect(url).get();
// 2. Extract the page title
String title = document.title();
System.out.println("Page Title: " + title);
// 3. Extract the text from the first paragraph (<p> tag)
// .select("p") finds all <p> tags
Elements paragraphs = document.select("p");
if (!paragraphs.isEmpty()) {
// .first() gets the first Element in the collection
// .text() extracts the plain text content of the element
System.out.println("First Paragraph Text: " + paragraphs.first().text());
}
// 4. Extract the text from the <h1> tag
// .selectFirst("h1") finds only the first <h1> tag
Element h1Tag = document.selectFirst("h1");
if (h1Tag != null) {
System.out.println("H1 Tag Text: " + h1Tag.text());
}
} catch (IOException e) {
System.err.println("Error connecting to " + url + ": " + e.getMessage());
e.printStackTrace(); // For more detailed error info
}
}
}
```
Output example:
```
Page Title: Example Domain
First Paragraph Text: This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.
H1 Tag Text: Example Domain
```
π‘ **Challenge:** Can you modify the code to find *all* `<a>` (anchor) tags on `http://example.com/` and print their `href` attributes? (Hint: Loop through the `Elements` collection and use `element.attr("href")`!) Happy scraping! π΅οΈββοΈ
---
Here's how to get started with Jsoup to extract a page title and a paragraph:
```java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class SimpleWebScraper {
public static void main(String[] args) {
String url = "http://example.com/"; // A simple, static page for demonstration
try {
// 1. Connect to the URL and get the HTML document
// Jsoup.connect(url) creates a Connection object
// .get() fetches the URL and parses the HTML into a Document object
Document document = Jsoup.connect(url).get();
// 2. Extract the page title
String title = document.title();
System.out.println("Page Title: " + title);
// 3. Extract the text from the first paragraph (<p> tag)
// .select("p") finds all <p> tags
Elements paragraphs = document.select("p");
if (!paragraphs.isEmpty()) {
// .first() gets the first Element in the collection
// .text() extracts the plain text content of the element
System.out.println("First Paragraph Text: " + paragraphs.first().text());
}
// 4. Extract the text from the <h1> tag
// .selectFirst("h1") finds only the first <h1> tag
Element h1Tag = document.selectFirst("h1");
if (h1Tag != null) {
System.out.println("H1 Tag Text: " + h1Tag.text());
}
} catch (IOException e) {
System.err.println("Error connecting to " + url + ": " + e.getMessage());
e.printStackTrace(); // For more detailed error info
}
}
}
```
Output example:
```
Page Title: Example Domain
First Paragraph Text: This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.
H1 Tag Text: Example Domain
```
π‘ **Challenge:** Can you modify the code to find *all* `<a>` (anchor) tags on `http://example.com/` and print their `href` attributes? (Hint: Loop through the `Elements` collection and use `element.attr("href")`!) Happy scraping! π΅οΈββοΈ
---