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 30: Final Project Idea and Review \- Code & Output
Day 32! ๐Ÿš€ We're diving deep into the future of Java concurrency: **Structured Concurrency with Project Loom**. Forget the old "thread-per-request" headaches and complex `CompletableFuture` chains for error handling. With Virtual Threads and `StructuredTaskScope`, you can orchestrate multiple concurrent operations as a single unit, ensuring cleaner code, automatic error propagation, and efficient resource management. This paradigm shift will revolutionize how we build scalable, resilient services. Get ready to rethink your concurrency strategies! โœจ

```java
import java.time.Duration;
import java.util.concurrent.Future;
import java.util.concurrent.StructuredTaskScope;
import java.util.random.RandomGenerator;

public class StructuredConcurrencyExample {

record UserData(String name, int id) {}
record Order(String itemId, int userId) {}

public static void main(String[] args) throws InterruptedException {
System.out.println("๐Ÿš€ Day 32: Starting Structured Concurrency with Virtual Threads!");

long startTime = System.currentTimeMillis();

try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<UserData> userFuture = scope.fork(() -> {
System.out.println(" [User Service] Fetching user data on: " + Thread.currentThread());
Thread.sleep(Duration.ofMillis(RandomGenerator.getDefault().nextInt(200, 500)));
return new UserData("Alice", 123);
});

Future<Order> orderFuture = scope.fork(() -> {
System.out.println(" [Order Service] Fetching order data on: " + Thread.currentThread());
Thread.sleep(Duration.ofMillis(RandomGenerator.getDefault().nextInt(300, 800)));
// Simulate a potential failure for demonstration
// if (RandomGenerator.getDefault().nextBoolean()) {
// throw new RuntimeException("Failed to fetch orders!");
// }
return new Order("BOOK-456", 123);
});

// Wait for all subtasks to complete or for one to fail
scope.join();
// If any subtask failed, this will re-throw the exception
scope.throwIfFailed();

UserData user = userFuture.resultNow();
Order order = orderFuture.resultNow();

System.out.println("โœ… All tasks completed successfully!");
System.out.println("User: " + user);
System.out.println("Order: " + order);

} catch (Exception e) {
System.err.println("โŒ One or more tasks failed: " + e.getMessage());
}

long endTime = System.currentTimeMillis();
System.out.println("Total execution time: " + (endTime - startTime) + "ms");
System.out.println("Main thread: " + Thread.currentThread());
}
}
```

Output example:
```
๐Ÿš€ Day 32: Starting Structured Concurrency with Virtual Threads!
[User Service] Fetching user data on: VirtualThread[...]/run-scope-1
[Order Service] Fetching order data on: VirtualThread[...]/run-scope-2
โœ… All tasks completed successfully!
User: UserData[name=Alice, id=123]
Order: Order[itemId=BOOK-456, userId=123]
Total execution time: 785ms
Main thread: main
```
*(Note: Execution time will vary due to random delays. The thread names will show `VirtualThread[...]`.)*

**Small Challenge:**
Uncomment the `// if (RandomGenerator.getDefault().nextBoolean()) { throw new RuntimeException("Failed to fetch orders!"); }` line in the `orderFuture` task. Run the code multiple times and observe how `StructuredTaskScope.ShutdownOnFailure` automatically handles the error, potentially cancelling the other tasks and propagating the exception. How does this compare to traditional `CompletableFuture` error handling? ๐Ÿค”

---
Hey everyone! We're starting again from Day 1 so everyone can build a strong foundation by learning everything from the basics this time.
โค1
๐ŸŽ‰ **Day 1: Introduction to Java with Hello World!** ๐ŸŽ‰

๐Ÿš€ Welcome to the very first day of our exciting Java Learning Series! Today, we're taking our first steps into the world of Java programming. Don't worry if you're a complete beginner โ€“ we'll start with the absolute fundamentals. We'll learn what Java is, set up our environment (conceptually for now!), and write the most classic first program: "Hello, World!". Get ready to launch your coding adventure! โœจ

---

**Our First Java Program:**

```java
public class HelloWorld {
public static void main(String[] args) {
// This line prints "Hello, World!" to the console
System.out.println("Hello, World!");
}
}
```

---

**Output example:**
```
Hello, World!
```

---

**Small Challenge:**

Can you modify the code above to print a different greeting, perhaps "Hello, [Your Name]!" instead of "Hello, World!"? Give it a try and share your custom output in the comments! ๐Ÿ‘‡

---
What is the primary purpose of `System.out.println("Hello, World!");` in a Java program?
Anonymous Quiz
4%
To define a new variable.
0%
To read input from the user.
96%
To print "Hello, World!" to the console.
0%
To declare a class.
Java for beginners pinned ยซHey everyone! We're starting again from Day 1 so everyone can build a strong foundation by learning everything from the basics this time.ยป
๐Ÿš€ Welcome back, Java enthusiasts! It's Day 2 of our learning journey, and today we're diving into the building blocks of any program: **Variables and Data Types**! ๐Ÿ› ๏ธ

Think of variables as containers that hold information, and data types as labels telling Java what kind of information each container can store (numbers, text, true/false values, etc.). Understanding them is crucial for writing dynamic programs. Let's learn how to declare and use them! ๐Ÿ‘‡

```java
public class Day2Variables {
public static void main(String[] args) {
// Declaring and initializing different types of variables

// Integer (whole numbers)
int age = 30;
System.out.println("My age is: " + age);

// Double (floating-point numbers, decimals)
double price = 19.99;
System.out.println("The price is: $" + price);

// Boolean (true or false)
boolean isJavaFun = true;
System.out.println("Is Java fun? " + isJavaFun);

// Character (single character)
char grade = 'A';
System.out.println("My grade is: " + grade);

// String (sequence of characters, text)
String name = "Alice";
System.out.println("My name is: " + name);

// You can also change variable values
age = 31; // Assigning a new value to 'age'
System.out.println("Next year, my age will be: " + age);

// Declaring without initializing, then assigning later
int numberOfStudents;
numberOfStudents = 25;
System.out.println("Number of students: " + numberOfStudents);
}
}
```

Output example:
```
My age is: 30
The price is: $19.99
Is Java fun? true
My grade is: A
My name is: Alice
Next year, my age will be: 31
Number of students: 25
```

๐Ÿ’ก **Your Challenge:** Try declaring a new `String` variable to hold your favorite programming language and an `int` variable for its release year. Then print them out using `System.out.println()`! Share your code or output in the comments if you like! ๐Ÿ’ฌ Happy coding!

---
โค1
Which of the following is the correct way to declare an integer variable named `quantity` and initialize it with the value `50` in Java?
Anonymous Quiz
95%
int quantity = 50;
5%
integer quantity = 50;
0%
quantity int = 50;
0%
Int quantity = 50;
What will be the value of `x` and `y` after the following code snippet executes?
```java
int x = 5; int y = ++x; ```
Anonymous Quiz
25%
x = 5, y = 5
13%
x = 6, y = 5
50%
x = 5, y = 6
13%
x = 6, y = 6
Here's your Telegram post and quiz question!

---

๐Ÿš€ **Day 4: Making Decisions in Java! Conditional Statements** ๐Ÿ’ก

Hello, Java learners! Today we're diving into how your programs can make intelligent choices โ€“ welcome to the world of Conditional Statements (`if`, `else if`, `else`)! ๐Ÿค”

Imagine your program as a person: it needs to decide what to do based on different situations. Should it print a "Pass" or "Fail"? Should it offer a discount or not? Conditional statements are the tools that give your code this power of decision-making. They allow your program to execute different blocks of code only when specific conditions are met. Get ready to add logic and flexibility to your Java applications! ๐Ÿ‘‡

```java
public class Day4Conditional {
public static void main(String[] args) {
int score = 85;

System.out.println("Your score: " + score);

if (score >= 90) {
System.out.println("Excellent! You got an A.");
} else if (score >= 80) { // This block executes if the first 'if' was false, AND score is >= 80
System.out.println("Great job! You got a B.");
} else if (score >= 70) {
System.out.println("Good effort! You got a C.");
} else { // This block executes if all preceding 'if' and 'else if' conditions were false
System.out.println("Keep practicing! You got a D or F.");
}

System.out.println("End of grading.");
}
}
```

Output example:
```
Your score: 85
Great job! You got a B.
End of grading.
```

**Small Challenge:**
Try changing the `score` variable to `95`, `60`, or `75`. What output do you get? Can you add another `else if` condition for a specific "Perfect Score!" message (e.g., if `score == 100`)? ๐Ÿง‘โ€๐Ÿ’ป

---
Day 4: Conditional Statements \(if, else if, else\) \- Code & Output
Here's your Telegram post for Day 5 of the Java learning series:

---

๐Ÿš€ Day 5 is here, Java Explorers! Today, we're diving into one of programming's most fundamental concepts: **Loops**! ๐Ÿ”„ Ever needed to repeat a task multiple times? That's where `for`, `while`, and `do-while` come in handy. They help us automate repetitive actions, making our code efficient and powerful. Get ready to master iteration! Let's code! ๐Ÿ’ป

```java
public class LoopExamples {
public static void main(String[] args) {
System.out.println("--- For Loop Example (Counts 0-2) ---");
for (int i = 0; i < 3; i++) {
System.out.println("For loop iteration: " + i);
}

System.out.println("n--- While Loop Example (Counts 0-2) ---");
int count = 0;
while (count < 3) {
System.out.println("While loop iteration: " + count);
count++;
}

System.out.println("n--- Do-While Loop Example (Counts 0-2) ---");
int num = 0;
do {
System.out.println("Do-While loop iteration: " + num);
num++;
} while (num < 3);

System.out.println("n--- Do-While (Executes at least once) ---");
int x = 5; // Initial condition x < 3 is false
do {
System.out.println("This runs once even if the condition is initially false! x is: " + x);
x++;
} while (x < 3); // Condition will be false, loop exits after one run
}
}
```

Output example:
```
--- For Loop Example (Counts 0-2) ---
For loop iteration: 0
For loop iteration: 1
For loop iteration: 2

--- While Loop Example (Counts 0-2) ---
While loop iteration: 0
While loop iteration: 1
While loop iteration: 2

--- Do-While Loop Example (Counts 0-2) ---
Do-While loop iteration: 0
Do-While loop iteration: 1
Do-While loop iteration: 2

--- Do-While (Executes at least once) ---
This runs once even if the condition is initially false! x is: 5
```

๐Ÿ’ก **Your Challenge:**
Write a Java program using a `for` loop to print all even numbers from 1 to 10. Can you also achieve this using a `while` loop? Share your solutions in the comments! ๐Ÿ‘‡

---
Day 5: Loops \(for, while, do\-while\) \- Code & Output
Which type of loop in Java is guaranteed to execute its body at least once, regardless of whether its condition is initially true or false?
Anonymous Quiz
9%
for loop
18%
while loop
73%
do-while loop
0%
foreach loop
Here's your Telegram post for Day 6!

---

Hey #JavaLearners! ๐Ÿ‘‹ Ready for Day 6 of our Java journey? Today, we're diving into the heart of code reusability: **Methods in Java**! ๐Ÿš€

Methods are like mini-programs within your main program. They help you organize code, perform specific tasks, and make your applications much cleaner and easier to manage. Think of them as actions your objects can perform! โœจ They take input, do some work, and optionally return a result. Let's see them in action! ๐Ÿ‘‡

```java
public class MethodMagic {

public static void main(String[] args) {
// Calling our custom methods
int sumResult = addNumbers(10, 5); // Calling a method with a return value
System.out.println("Sum of 10 and 5 is: " + sumResult);

sayHello("Alice"); // Calling a method with no return value (void)
sayHello("Bob");
}

/**
* This method takes two integers as parameters and returns their sum.
*/
public static int addNumbers(int num1, int num2) {
int sum = num1 + num2;
return sum; // 'return' sends the result back
}

/**
* This method takes a String name as a parameter and prints a greeting.
* It does not return anything, indicated by the 'void' keyword.
*/
public static void sayHello(String name) {
System.out.println("Hello, " + name + "! Welcome to Methods!");
}
}
```

Output example:
```
Sum of 10 and 5 is: 15
Hello, Alice! Welcome to Methods!
Hello, Bob! Welcome to Methods!
```

**Small challenge:**
Your turn! ๐Ÿ› ๏ธ Try creating a new method in the `MethodMagic` class called `multiplyNumbers` that takes two integers as parameters and returns their product. Then call it from your `main` method and print the result! Good luck, future Java wizard! ๐Ÿง โœจ

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