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 6: Methods in Java \- Code & Output
What keyword is used to declare a method that does not return any value in Java?
Anonymous Quiz
0%
int
0%
return
92%
void
8%
null
๐ŸŽ‰ Happy Day 7, Java Learners! ๐Ÿš€ Today, we're unlocking the power of storing multiple pieces of data efficiently with **Arrays and ArrayLists**!

These two are fundamental data structures, but they have key differences. Arrays are like fixed-size containers, while ArrayLists are dynamic, growing and shrinking as you need them to. Understanding when to use each is crucial for writing efficient Java code. Let's dive in! ๐Ÿ“š๐Ÿ’ก

```java
import java.util.ArrayList;
import java.util.Arrays; // Useful for printing array contents easily

public class Day7ArraysArrayLists {
public static void main(String[] args) {
// --- Working with Arrays (Fixed Size) ---
// Declare and initialize an array of Strings
String[] fruits = {"Apple", "Banana", "Cherry"};

System.out.println("--- Using Arrays ---");
// Accessing elements using index
System.out.println("First fruit: " + fruits[0]); // Output: Apple
System.out.println("Third fruit: " + fruits[2]); // Output: Cherry

// Getting the number of elements (length property)
System.out.println("Number of fruits (Array): " + fruits.length); // Output: 3

// Printing the whole array (Arrays.toString() is helpful!)
System.out.println("All fruits: " + Arrays.toString(fruits)); // Output: [Apple, Banana, Cherry]

// IMPORTANT: Arrays have a fixed size.
// You cannot simply add a new element beyond its initial capacity.
// fruits[3] = "Date"; // This would cause an ArrayIndexOutOfBoundsException at runtime!

// --- Working with ArrayLists (Dynamic Size) ---
// Declare and initialize an ArrayList of Strings
ArrayList<String> veggies = new ArrayList<>();

System.out.println("n--- Using ArrayLists ---");
// Adding elements using .add()
veggies.add("Carrot");
veggies.add("Broccoli");
veggies.add("Spinach");

// Accessing elements using .get()
System.out.println("First veggie: " + veggies.get(0)); // Output: Carrot

// Getting the number of elements (size() method)
System.out.println("Number of veggies (ArrayList): " + veggies.size()); // Output: 3

// ArrayLists are dynamic! You can add more elements easily.
veggies.add("Potato");
System.out.println("After adding Potato: " + veggies); // Output: [Carrot, Broccoli, Spinach, Potato]

// You can also remove elements easily.
veggies.remove("Broccoli"); // Removes the first occurrence of "Broccoli"
System.out.println("After removing Broccoli: " + veggies); // Output: [Carrot, Spinach, Potato]

// Or remove by index
veggies.remove(0); // Removes the element at index 0 (Carrot)
System.out.println("After removing element at index 0: " + veggies); // Output: [Spinach, Potato]
}
}
```

Output example:
```
--- Using Arrays ---
First fruit: Apple
Third fruit: Cherry
Number of fruits (Array): 3
All fruits: [Apple, Banana, Cherry]

--- Using ArrayLists ---
First veggie: Carrot
Number of veggies (ArrayList): 3
After adding Potato: [Carrot, Broccoli, Spinach, Potato]
After removing Broccoli: [Carrot, Spinach, Potato]
After removing element at index 0: [Spinach, Potato]
```

**Small Challenge:**
Can you modify the `veggies` ArrayList in the code to insert "Cucumber" at the second position (index 1), pushing "Spinach" and "Potato" down, without removing any existing elements? ๐Ÿค” Good luck!

---
Day 7: Arrays and ArrayLists \- Code & Output
Hey Java Learners! ๐Ÿ‘‹ Today marks Day 8 of our journey, and we're diving into two incredibly powerful collections: `HashMaps` and `HashSets`! ๐Ÿง  Ever needed to store data where you can quickly find things by a unique label? That's `HashMap` for you โ€“ think of it like a super-efficient dictionary with key-value pairs. And what if you just need a collection of unique items, no duplicates allowed? `HashSet` is your go-to! ๐Ÿ›ก๏ธ Get ready to unlock faster data management with these amazing tools! Let's explore. ๐Ÿ‘‡

```java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map; // For Map.Entry

public class Day8Collections {

public static void main(String[] args) {
System.out.println("--- HashMap Example ---");
// 1. Create a HashMap: Stores key-value pairs
HashMap<String, Integer> studentScores = new HashMap<>();

// 2. Add elements: put(key, value)
studentScores.put("Alice", 95);
studentScores.put("Bob", 88);
studentScores.put("Charlie", 92);
studentScores.put("Alice", 98); // If key exists, value is updated

System.out.println("Student Scores: " + studentScores);

// 3. Get a value: get(key)
System.out.println("Alice's score: " + studentScores.get("Alice"));

// 4. Check if a key exists: containsKey(key)
System.out.println("Contains Bob? " + studentScores.containsKey("Bob"));

// 5. Iterate through HashMap using entrySet()
System.out.println("All scores:");
for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}

System.out.println("n--- HashSet Example ---");
// 1. Create a HashSet: Stores unique elements
HashSet<String> uniqueFruits = new HashSet<>();

// 2. Add elements: add(element)
uniqueFruits.add("Apple");
uniqueFruits.add("Banana");
uniqueFruits.add("Orange");
uniqueFruits.add("Apple"); // Duplicate, won't be added

System.out.println("Unique Fruits: " + uniqueFruits); // Order is not guaranteed

// 3. Check if an element exists: contains(element)
System.out.println("Contains Banana? " + uniqueFruits.contains("Banana"));

// 4. Remove an element: remove(element)
uniqueFruits.remove("Orange");
System.out.println("Fruits after removing Orange: " + uniqueFruits);

// 5. Iterate through HashSet
System.out.println("My fruits:");
for (String fruit : uniqueFruits) {
System.out.println(fruit);
}
}
}
```

Output example:
```
--- HashMap Example ---
Student Scores: {Alice=98, Bob=88, Charlie=92}
Alice's score: 98
Contains Bob? true
All scores:
Alice -> 98
Bob -> 88
Charlie -> 92

--- HashSet Example ---
Unique Fruits: [Apple, Banana, Orange]
Contains Banana? true
Fruits after removing Orange: [Apple, Banana]
My fruits:
Apple
Banana
```

๐Ÿ’ก Your Challenge: Can you use a `HashMap` to count the frequency of each word in a given sentence? For example, for the sentence "Java is fun, Java is powerful." your output should be something like `{"Java": 2, "is": 2, "fun": 1, "powerful": 1}` (you can ignore punctuation and case for simplicity). Go ahead and try it out! โœ…
Day 8: HashMaps and HashSets \- Code & Output
๐ŸŒŸ **Day 9: String Manipulation in Java!** ๐ŸŒŸ

Hello, future Java pros! ๐Ÿ‘‹ Today, we're diving into one of the most fundamental and frequently used data types: **Strings**! โœจ From names and messages to URLs and file paths, strings are everywhere. Java's `String` class is incredibly powerful, offering a plethora of methods to manipulate text with ease.

Let's explore some essential string manipulation techniques that will make your code robust and dynamic. Get ready to slice, dice, and transform your text! ๐Ÿš€

```java
public class StringManipulationDemo {
public static void main(String[] args) {
String originalText = " Hello Java Learners! Welcome to Day 9. ";

System.out.println("Original String: '" + originalText + "'");
System.out.println("Length of original: " + originalText.length());

// 1. Trimming whitespace
String trimmedText = originalText.trim();
System.out.println("Trimmed String: '" + trimmedText + "'");
System.out.println("Length after trim: " + trimmedText.length());

// 2. Getting a substring
// Substring from index 6 (inclusive) to 10 (exclusive)
System.out.println("Substring (index 6 to 10): " + trimmedText.substring(6, 10)); // "Java"

// 3. Finding the index of a character or substring
System.out.println("Index of 'Java': " + trimmedText.indexOf("Java")); // 6
System.out.println("Index of first 'e': " + trimmedText.indexOf('e')); // 1

// 4. Replacing parts of a string
String replacedText = trimmedText.replace("Java", "Awesome");
System.out.println("Text after replacing 'Java': " + replacedText);

// 5. Changing case
System.out.println("Uppercase: " + trimmedText.toUpperCase());
System.out.println("Lowercase: " + trimmedText.toLowerCase());

// 6. Checking if a string contains another string
System.out.println("Contains 'Learners'?: " + trimmedText.contains("Learners")); // true

// 7. Concatenating strings
String newGreeting = "Happy coding!";
System.out.println("Concatenated: " + trimmedText + " " + newGreeting);
}
}
```

Output example:
```
Original String: ' Hello Java Learners! Welcome to Day 9. '
Length of original: 44
Trimmed String: 'Hello Java Learners! Welcome to Day 9.'
Length after trim: 38
Substring (index 6 to 10): Java
Index of 'Java': 6
Index of first 'e': 1
Text after replacing 'Java': Hello Awesome Learners! Welcome to Day 9.
Uppercase: HELLO JAVA LEARNERS! WELCOME TO DAY 9.
Lowercase: hello java learners! welcome to day 9.
Contains 'Learners'?: true
Concatenated: Hello Java Learners! Welcome to Day 9. Happy coding!
```

**Small Challenge:** ๐Ÿ’ช
Take the string `"Coding is Fun and Powerful!"`. Write Java code to:
1. Extract the word "Fun".
2. Replace "Powerful" with "Creative".
3. Check if the modified string ends with "!".

Share your solutions or questions below! Happy learning! #Java #JavaLearning #StringManipulation #Programming #Day9

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