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 9: String Manipulation \- Code & Output
What will be the output of `System.out.println("Programming".substring(3, 7));`?
Anonymous Quiz
83%
gram
8%
ogra
8%
gramm
0%
ogras
๐Ÿ‘Ž3
๐Ÿ”ฅ **Day 10: Mastering File I/O in Java!** ๐Ÿ“

Welcome back, Java learners! ๐Ÿ‘‹ Today's an important one: **File Input/Output (I/O)**. Ever wondered how applications save and load data? It's all thanks to File I/O! We'll explore how to **read from** ๐Ÿ“– and **write to** โœ๏ธ files, making your program's data persistent even after it closes. Get ready to interact with your file system! ๐Ÿš€ Let's dive in.

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

public class FileIOExample {

private static final String FILENAME = "myJavaFile.txt";

public static void main(String[] args) {
// --- Part 1: Writing to a file ---
System.out.println("--- Writing to " + FILENAME + " ---");
try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILENAME))) {
writer.write("Hello, Java Learners!");
writer.newLine();
writer.write("This is a line written by our Java program.");
writer.newLine();
writer.write("Day 10: File I/O is fun! ๐ŸŽ‰");
System.out.println("Content successfully written to " + FILENAME);
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}

System.out.println("n--- Reading from " + FILENAME + " ---");
// --- Part 2: Reading from a file ---
try (BufferedReader reader = new BufferedReader(new FileReader(FILENAME))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
System.out.println("Content successfully read from " + FILENAME);
} catch (IOException e) {
System.err.println("Error reading from file: " + e.getMessage());
}
}
}
```

Output example:
```
--- Writing to myJavaFile.txt ---
Content successfully written to myJavaFile.txt

--- Reading from myJavaFile.txt ---
Hello, Java Learners!
This is a line written by our Java program.
Day 10: File I/O is fun! ๐ŸŽ‰
Content successfully read from myJavaFile.txt
```

๐Ÿ’ก **Small Challenge:**
1. Modify the writing part of the code to **append** new content to the file instead of overwriting it. (Hint: Look at `FileWriter` constructor options!)
2. Extend the reading part to **count and print the total number of lines** in the file.

---
Day 10: File I/O \(Input/Output\) \- Code & Output
๐Ÿšจ Day 11: Diving into Java's Exception Handling! ๐Ÿšจ Ever had your program crash unexpectedly? That's where exceptions come in! Today, we'll learn how to make our code robust and user-friendly using `try`, `catch`, and `finally`.

`try`: Encloses code that might throw an exception.
`catch`: Catches and handles specific exceptions.
`finally`: Guarantees code execution, whether an exception occurred or not.

Let's prevent those crashes and handle errors gracefully! ๐Ÿ‘‡

```java
public class ExceptionHandlingDemo {
public static void main(String[] args) {
System.out.println("Program starting...");

try {
// Code that might throw an exception
int numerator = 10;
int denominator = 0; // This will cause an ArithmeticException

int result = numerator / denominator;
System.out.println("Result: " + result); // This line won't execute
} catch (ArithmeticException e) {
// Code to handle a specific exception (e.g., division by zero)
System.err.println("๐Ÿšซ Caught an ArithmeticException: " + e.getMessage());
System.err.println("Suggestion: Please do not divide by zero!");
} catch (Exception e) { // A general catch block for any other unexpected exception
System.err.println("โš ๏ธ Caught a general exception: " + e.getMessage());
} finally {
// Code that always executes, regardless of an exception
System.out.println("โœ… The 'finally' block always runs. Cleanup or final message complete.");
}

System.out.println("Program finished.");
}
}
```

Output example:
```
Program starting...
๐Ÿšซ Caught an ArithmeticException: / by zero
Suggestion: Please do not divide by zero!
โœ… The 'finally' block always runs. Cleanup or final message complete.
Program finished.
```

โœ… Your Challenge: Modify the example! Write a small program that asks the user for two numbers. Use `try-catch` to handle `NumberFormatException` if the user enters non-numeric input, and also `ArithmeticException` if the second number is zero. Make sure a `finally` block prints a 'Thank you for using the calculator!' message.
Day 11: Exception Handling \(try, catch, finally\) \- Code & Output
Which of the following blocks in Java's exception handling construct (`try-catch-finally`) is guaranteed to execute, whether an exception occurs or not?
Anonymous Quiz
14%
The `try` block
0%
The `catch` block
86%
The `finally` block
0%
None of the above
Here's your Telegram post for Day 12 of the Java learning series!

---

๐ŸŽ‰ Day 12: Packages and Import Statements! ๐ŸŽ‰

Ready to keep your Java code neat and tidy? ๐Ÿงน On Day 12, we're diving into `Packages` and `Import Statements`! These aren't just fancy keywords; they're essential tools for organizing your classes, preventing naming conflicts, and making your code much more readable and manageable, especially in larger projects. Think of packages as folders for your classes, and import statements as shortcuts to access files in those folders easily. Let's make our code professional! ๐Ÿง‘โ€๐Ÿ’ป

```java
// File: src/com/example/myapp/utilities/Greeter.java
package com.example.myapp.utilities;

public class Greeter {
public static String greet(String name) {
return "Hello from package utilities, " + name + "!";
}
}

// File: src/com/example/myapp/main/MyMainApp.java
package com.example.myapp.main;

import com.example.myapp.utilities.Greeter; // Importing the Greeter class

public class MyMainApp {
public static void main(String[] args) {
// Now you can use Greeter directly thanks to the import!
String message = Greeter.greet("Java Learner");
System.out.println(message);

// Without import, you would need the fully qualified name:
// String message2 = com.example.myapp.utilities.Greeter.greet("Another Learner");
// System.out.println(message2);
}
}
```

Output example:
```
Hello from package utilities, Java Learner!
```

---

๐Ÿš€ **Small Challenge:**
Your turn! Create a new package, say `com.example.myapp.mathutils`, and add a class `Calculator` with a static method `add(int a, int b)`. Then, modify `MyMainApp` to import and use your `Calculator` class to print the sum of two numbers! Good luck! โœจ

---
Day 12: Packages and Import Statements \- Code & Output
Here's your Telegram post and quiz for Day 13!

---

**โœจ Java Learning Series - Day 13: Object-Oriented Programming (Classes & Objects) โœจ**

Hello, future Java wizards! ๐Ÿš€ Today is a *big* day as we dive into the heart of Java: Object-Oriented Programming (OOP)! Specifically, we're unlocking the power of **Classes and Objects**.

Think of a `class` as a blueprint or a cookie cutter. It defines the structure and behavior that its "products" will have. An `object`, then, is the actual cookie โ€“ a real instance created from that blueprint! It's how we model real-world entities and organize our code in a powerful, reusable way. Get ready to build some software architecture! ๐Ÿ—๏ธ

Let's see them in action! ๐Ÿ‘‡

```java
// Define a Car class (the blueprint)
class Car {
// Attributes (state/data)
String make;
String model;
int year;

// Constructor (a special method to create objects)
public Car(String make, String model, int year) {
this.make = make; // 'this' refers to the current object
this.model = model;
this.year = year;
System.out.println("A new Car object has been created: " + make + " " + model);
}

// Methods (behavior/actions)
public void start() {
System.out.println("The " + make + " " + model + " is starting...");
}

public void accelerate() {
System.out.println("The " + make + " " + model + " is accelerating!");
}

public void displayInfo() {
System.out.println("Car Info: " + year + " " + make + " " + model);
}
}

public class Day13_ClassesAndObjects {
public static void main(String[] args) {
// Create objects (instances) from the Car blueprint
Car myCar = new Car("Toyota", "Camry", 2023); // Creates an object named myCar
myCar.start();
myCar.accelerate();
myCar.displayInfo();
System.out.println("---");

Car anotherCar = new Car("Honda", "Civic", 2022); // Creates another object
anotherCar.start();
anotherCar.displayInfo();
}
}
```

Output example:
```
A new Car object has been created: Toyota Camry
The Toyota Camry is starting...
The Toyota Camry is accelerating!
Car Info: 2023 Toyota Camry
---
A new Car object has been created: Honda Civic
The Honda Civic is starting...
Car Info: 2022 Honda Civic
```

---

**๐Ÿค” Small Challenge for You:**
Modify the `Car` class!
1. Add a new attribute: `double fuelLevel` (initialize it to `100.0` in the constructor).
2. Add a new method: `public void drive(double distance)` that prints "Driving X km." and decreases `fuelLevel` by `distance / 10.0`.
3. Add another method: `public void refuel(double amount)` that increases `fuelLevel` by the given `amount`.
4. In `main`, call `drive()` and `refuel()` on `myCar` and print its `fuelLevel` before and after these actions. ๐Ÿ’ช

---

**Quiz Question:**
Day 13: Object\-Oriented Programming \(Classes and Objects\) \- Code & Output
Here's your Telegram post for Day 14!

---

**Day 14: Inheritance and Polymorphism โ€“ The Pillars of OOP!** ๐Ÿงฌ

Hello, Java learners! Today, we're unlocking the power of two fundamental OOP concepts: **Inheritance** and **Polymorphism**. โœจ

**Inheritance** allows a class (subclass/child) to inherit properties and methods from another class (superclass/parent). This promotes code reusability and creates a clear "is-a" relationship. Think of it as building on existing foundations!

**Polymorphism** (meaning "many forms") lets objects of different classes be treated as objects of a common type. It's the magic behind writing flexible and extensible code, allowing you to handle different types of objects uniformly. ๐Ÿ”„ Let's see them in action!

```java
// Parent class (Superclass)
class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}

public void eat() {
System.out.println("Animal eats food");
}
}

// Child class (Subclass) inheriting from Animal
class Dog extends Animal {
// Method Overriding: Providing a specific implementation for makeSound()
@Override
public void makeSound() {
System.out.println("Woof! Woof!");
}

public void fetch() {
System.out.println("Dog fetches the ball!");
}
}

// Another Child class inheriting from Animal
class Cat extends Animal {
// Method Overriding: Providing a specific implementation for makeSound()
@Override
public void makeSound() {
System.out.println("Meow!");
}

public void scratch() {
System.out.println("Cat scratches the post.");
}
}

public class ZooPark {
public static void main(String[] args) {
// Inheritance: myDog is a Dog, which IS-A Animal
Dog myDog = new Dog();
Cat myCat = new Cat();

System.out.println("--- Specific animal actions ---");
myDog.makeSound(); // Calls Dog's specific sound
myDog.fetch(); // Calls Dog's specific action
myCat.makeSound(); // Calls Cat's specific sound
myCat.scratch(); // Calls Cat's specific action
myDog.eat(); // Calls inherited eat() from Animal

System.out.println("n--- Polymorphism in a common method ---");
// Polymorphism: An Animal reference can point to a Dog or Cat object
makeAnimalPerform(myDog); // Dog object treated as Animal
makeAnimalPerform(myCat); // Cat object treated as Animal

System.out.println("n--- Polymorphism in a collection ---");
// Polymorphism in action: Array of Animal references
Animal[] pets = new Animal[2];
pets[0] = new Dog(); // Dog object assigned to Animal reference
pets[1] = new Cat(); // Cat object assigned to Animal reference

for (Animal pet : pets) {
pet.makeSound(); // Calls appropriate overridden makeSound()
pet.eat(); // Calls inherited eat()
}
}

// A method demonstrating polymorphism by accepting the superclass type
public static void makeAnimalPerform(Animal animal) {
System.out.print("Performing for an animal: ");
animal.makeSound(); // Behaves differently based on actual object type
animal.eat();
}
}
```

**Output example:**
```
--- Specific animal actions ---
Woof! Woof!
Dog fetches the ball!
Meow!
Cat scratches the post.
Animal eats food

--- Polymorphism in a common method ---
Performing for an animal: Woof! Woof!
Animal eats food
Performing for an animal: Meow!
Animal eats food

--- Polymorphism in a collection ---
Woof! Woof!
Animal eats food
Meow!
Animal eats food
```

**Small challenge:**
Can you add a new animal, `Cow`, to our `Animal` hierarchy? ๐Ÿ„ Give it its unique `makeSound()` (e.g., "Moo!") and maybe a special action like `graze()`. Then, demonstrate its behavior using polymorphism by adding it to the `pets` array in the `main` method! Show its unique sound and inherited `eat()` method. ๐Ÿš€

---
Day 14: Inheritance and Polymorphism \- Code & Output
Which keyword is used in Java to indicate that a class is inheriting from another class?
Anonymous Quiz
0%
A. implements
93%
B. extends
0%
C. uses
7%
D. inherits
๐Ÿš€ Day 15 already! Today, we're diving into the heart of Java's power: its standard libraries! ๐Ÿ“š We'll explore `java.util` for essential utility classes like `Scanner` to handle input, and `java.io` for all your input/output needs, like reading from or writing to files. Mastering these will unlock a whole new level of programming possibilities! โœจ Let's get hands-on! ๐Ÿ’ก

```java
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class LibraryDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();

String fileName = "greeting.txt";

// Writing to a file using java.io.FileWriter
System.out.println("n--- Writing to file ---");
try (FileWriter writer = new FileWriter(fileName)) {
writer.write("Hello, " + name + "!n");
writer.write("Welcome to Day 15 of Java learning.n");
System.out.println("Message written to " + fileName + " successfully.");
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}

// Reading from a file using java.io.FileReader
System.out.println("n--- Reading from file ---");
System.out.println("Content of " + fileName + ":");
try (FileReader reader = new FileReader(fileName)) {
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
System.out.println("File read successfully!");
} catch (IOException e) {
System.err.println("Error reading from file: " + e.getMessage());
} finally {
scanner.close(); // Important to close resources!
}
}
}
```

Output example:
```
Enter your name: JavaLearner

--- Writing to file ---
Message written to greeting.txt successfully.

--- Reading from file ---
Content of greeting.txt:
Hello, JavaLearner!
Welcome to Day 15 of Java learning.
File read successfully!
```

Small challenge:
Can you modify the code to also ask for the user's favorite programming language and append it as a new line to the `greeting.txt` file after the initial message? Remember to handle potential `IOException` when appending! (Hint: Look for `FileWriter` constructors that take a boolean `append` argument!) ๐Ÿค“
Day 15: Introduction to Java Libraries \(java\.util, java\.io\) \- Code & Output
Which Java package is primarily designed for providing general-purpose utility classes such as `Scanner`, `ArrayList`, and `Date`?
Anonymous Quiz
100%
java.util
0%
java.sql
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