You can test it yourself by following this link: https://nextleap.app/online-compiler/java-programming/hpyae7byi
Want a specific topic to be considered/explained here, please leave a comment for this message 😉
How to Stop a Thread in Java: The Right Way
Stopping a thread in Java is a common topic in job interviews. While the question seems simple, it’s important to understand the right way to do it, especially if you want to avoid bugs 🐞 in your applications.
✋Why Not Use Thread.stop()?
Java used to provide a method called
The Right Approach: interrupted flag
In Java, stopping a thread is often done by using the interruption mechanism rather than forcefully terminating it. The
How It Works
When you want to stop a thread, you call
You can try this example online: https://nextleap.app/online-compiler/java-programming/j4qe1j77a and expect an output similar to the following:
Why Call Thread.currentThread().interrupt()?
When a thread is interrupted and it's performing a blocking operation like
If your code doesn’t call
By calling
🛑 Another way to stop a Thread
Even with the advantages of using
While it can work, I don't really see the need to replicate functionality that Java already provides. The KISS principle (Keep It Simple, Stupid) definitely applies here — why reinvent the wheel or redo what's already built into the language? Plus, software tends to evolve. Even if your thread isn’t using blocking operations right now, that could easily change down the line. When that happens, you’ll probably have to refactor anyway and switch to the interruption mechanism to handle thread interruptions properly.
I genuinely hope this material helps you when you face a job interview. Sooner or later, you'll encounter questions like this, and being prepared can make all the difference. Best of luck! 😌
#java #intermediate #interview
Stopping a thread in Java is a common topic in job interviews. While the question seems simple, it’s important to understand the right way to do it, especially if you want to avoid bugs 🐞 in your applications.
✋Why Not Use Thread.stop()?
Java used to provide a method called
Thread.stop()
, but it’s considered unsafe and has been deprecated since Java 2. It can leave objects in an inconsistent state and lead to unpredictable behavior.The Right Approach: interrupted flag
In Java, stopping a thread is often done by using the interruption mechanism rather than forcefully terminating it. The
isInterrupted()
method is a clean, thread-safe way to signal a thread to stop without causing unpredictable behavior. Here’s how you can do it.How It Works
When you want to stop a thread, you call
Thread.interrupt()
on the thread instance. This doesn’t stop the thread immediately, but it sets an internal interrupt flag. Inside the thread, you should check whether this flag is set by using the isInterrupted()
method and stop the thread’s work if needed.
class MyRunnable implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Thread is running...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // reset the interrupted flag
System.out.println("The thread is interrupted. Going to finish the thread.");
}
}
System.out.println("Thread has been interrupted and stopped.");
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new MyRunnable());
thread.start();
// Let the thread run for a while
Thread.sleep(3000);
// Interrupt the thread
thread.interrupt();
}
}
You can try this example online: https://nextleap.app/online-compiler/java-programming/j4qe1j77a and expect an output similar to the following:
Thread is running...
Thread is running...
Thread is running...
The thread is interrupted. Going to finish the thread.
Thread has been interrupted and stopped.
Why Call Thread.currentThread().interrupt()?
When a thread is interrupted and it's performing a blocking operation like
Thread.sleep()
, wait()
, or certain I/O tasks, an InterruptedException
is thrown. This exception clears the thread’s interrupted status, meaning that after catching the exception, the interrupt flag is reset to false.If your code doesn’t call
Thread.currentThread().interrupt()
after catching the exception, the thread will lose the information that it was interrupted, and you might miss the chance to stop the thread properly.By calling
Thread.currentThread().interrupt()
, you restore the interrupted status and allow other parts of the thread (or the rest of the program) to know that the thread was interrupted, so they can handle it accordingly.🛑 Another way to stop a Thread
Even with the advantages of using
Thread.interrupt()
, some developers still opt for custom flags, especially for non-blocking tasks ( like those that don’t involve Thread.sleep()
).While it can work, I don't really see the need to replicate functionality that Java already provides. The KISS principle (Keep It Simple, Stupid) definitely applies here — why reinvent the wheel or redo what's already built into the language? Plus, software tends to evolve. Even if your thread isn’t using blocking operations right now, that could easily change down the line. When that happens, you’ll probably have to refactor anyway and switch to the interruption mechanism to handle thread interruptions properly.
I genuinely hope this material helps you when you face a job interview. Sooner or later, you'll encounter questions like this, and being prepared can make all the difference. Best of luck! 😌
#java #intermediate #interview
Hello dear subscribers and guests 👋
Let's go through a few questions about JUnit to get a better sense of what you're most interested in
Let's go through a few questions about JUnit to get a better sense of what you're most interested in
Please open Telegram to view this post
VIEW IN TELEGRAM
Which of the following is true about @Test in JUnit 5?
Anonymous Quiz
11%
It requires to specify “public” access modifier for test methods
22%
A test method must return “void”
22%
It can take “timeout” and “expected” attributes
33%
It no longer requires test methods to be “public”
11%
I don’t know what JUnit is 😊
What annotation is used in JUnit 5 to indicate that a test should be disabled?
Anonymous Quiz
42%
42%
8%
8%
What is the correct way to write an assertion for throwing an exception in JUnit 5?
Anonymous Quiz
71%
assertThrows(IllegalArgumentException.class, () -> { // code });
7%
assertThrows(() -> { // code });
7%
assertEquals(IllegalArgumentException.class, () -> { // code });
14%
assertThrows(new IllegalArgumentException(), () -> { // code });
How much Java 👩💻 is in JDK 21? The majority of JDK 21 is made up of Java classes, which are part of the core JDK. However, a significant portion (about 21%) is still written in C and C++, reflecting their use in the underlying JVM implementation and other performance-critical components.
Please open Telegram to view this post
VIEW IN TELEGRAM
YAJC become Java programmer
How much Java 👩💻 is in JDK 21? The majority of JDK 21 is made up of Java classes, which are part of the core JDK. However, a significant portion (about 21%) is still written in C and C++, reflecting their use in the underlying JVM implementation and other…
Please open Telegram to view this post
VIEW IN TELEGRAM
Why is Testing Java Programs a Must?
Hey there, Java enthusiasts! 😊 Let’s talk about something super important but sometimes overlooked—testing your Java programs! It’s easy to get excited about building new features and making your code run, but taking a little extra time to test can be a game-changer for your project. Some developers argue that having clear, well-written tests can be even more valuable than elegant production code. Here’s why:
1. Catch Bugs Early🐞
Even the most skilled developers make mistakes—no shame in it! But testing can catch these bugs early, before they grow into bigger issues. Imagine deploying a program only to find out that one tiny bug affects a critical part of your app. That’s a nightmare, right? Testing helps you sleep better at night, knowing your code is more reliable.
2. Build Confidence in Your Code
When you write tests, you’re essentially saying, “I trust my code to do what it’s supposed to.” It’s like having a safety net! With automated tests, you’ll know immediately if a change breaks something. This gives you the freedom to refactor, optimize, and add features without the fear of breaking existing functionality.
3. Save Time (and Headaches) in the Long Run
While writing tests might seem time-consuming at first, it actually saves you a lot of time in the long run. Without tests, every little change means you’d have to manually check each part of your code to see if it still works. Automated tests do this work for you, allowing you to focus on the fun stuff—like coding the next big feature!
4. Improve Code Quality⚠️
Testing isn’t just about finding bugs; it also forces you to write cleaner, more modular code. When your code is structured well, it’s easier to write tests for it. Plus, testing can reveal hidden dependencies or areas that need improvement, making your overall codebase stronger and more maintainable.
5. Better Team Collaboration
If you’re working in a team, testing is crucial. It creates a shared understanding of how the code should behave and makes it easier for everyone to work on different parts of the project without stepping on each other’s toes. Plus, code reviews are way smoother when tests are in place!
Wrapping Up
Testing isn’t just an extra task; it’s an investment in the quality and reliability of your Java programs. So, next time you’re coding away, take a moment to add some tests—it’ll pay off in more ways than one!🚀
In upcoming posts, we’ll explore effective ways to test your programs and look at the best tools available to help you do it.
Happy coding, and may your tests always pass!✅
Hit that🔥 if this topic sparks your interest!
Hey there, Java enthusiasts! 😊 Let’s talk about something super important but sometimes overlooked—testing your Java programs! It’s easy to get excited about building new features and making your code run, but taking a little extra time to test can be a game-changer for your project. Some developers argue that having clear, well-written tests can be even more valuable than elegant production code. Here’s why:
1. Catch Bugs Early
Even the most skilled developers make mistakes—no shame in it! But testing can catch these bugs early, before they grow into bigger issues. Imagine deploying a program only to find out that one tiny bug affects a critical part of your app. That’s a nightmare, right? Testing helps you sleep better at night, knowing your code is more reliable.
2. Build Confidence in Your Code
When you write tests, you’re essentially saying, “I trust my code to do what it’s supposed to.” It’s like having a safety net! With automated tests, you’ll know immediately if a change breaks something. This gives you the freedom to refactor, optimize, and add features without the fear of breaking existing functionality.
3. Save Time (and Headaches) in the Long Run
While writing tests might seem time-consuming at first, it actually saves you a lot of time in the long run. Without tests, every little change means you’d have to manually check each part of your code to see if it still works. Automated tests do this work for you, allowing you to focus on the fun stuff—like coding the next big feature!
4. Improve Code Quality
Testing isn’t just about finding bugs; it also forces you to write cleaner, more modular code. When your code is structured well, it’s easier to write tests for it. Plus, testing can reveal hidden dependencies or areas that need improvement, making your overall codebase stronger and more maintainable.
5. Better Team Collaboration
If you’re working in a team, testing is crucial. It creates a shared understanding of how the code should behave and makes it easier for everyone to work on different parts of the project without stepping on each other’s toes. Plus, code reviews are way smoother when tests are in place!
Wrapping Up
Testing isn’t just an extra task; it’s an investment in the quality and reliability of your Java programs. So, next time you’re coding away, take a moment to add some tests—it’ll pay off in more ways than one!
In upcoming posts, we’ll explore effective ways to test your programs and look at the best tools available to help you do it.
Happy coding, and may your tests always pass!
Hit that
Please open Telegram to view this post
VIEW IN TELEGRAM
👍1🔥1
Testing Without Testing Frameworks
In our previous post, we discussed why testing is essential in software development😎
Today, let's explore how to test a program without using any testing frameworks like JUnit. Imagine we're developing a video game based on Harry Potter 🧙♂️. Our goal is to implement and test a basic
Here's a simple version of the class, where Harry can cast spells:
With this setup, Harry can cast different spells based on his level. Now, we want to ensure that our HarryPotter class works correctly. Since we aren't using any testing frameworks, we'll try a few simple approaches:
Approach 1: Testing with main Method and Console Output
The first approach is to add testing code directly to a main method, creating an instance of HarryPotter and checking the output manually. Here's an example:
Drawback: This approach relies on us checking the console output manually, which can be tedious and error-prone, especially for larger programs.
Approach 2: Using Simple Assertions
To make testing easier, we can add basic assertion-like checks to automatically verify the output. By comparing expected values with actual values and throwing an exception if they don't match, we avoid manually inspecting the output. Here's how:
Now, if a test fails, an exception is thrown, pointing us directly to the issue. This is a more effective way to test compared to simply printing results.
Summary
Testing without frameworks may not be as streamlined as using JUnit, but simple assertions in the main method can still help catch basic issues. This approach provides instant feedback on whether the method behaves as expected.
In our previous post, we discussed why testing is essential in software development
Today, let's explore how to test a program without using any testing frameworks like JUnit. Imagine we're developing a video game based on Harry Potter 🧙♂️. Our goal is to implement and test a basic
HarryPotter
class that represents our main character.Here's a simple version of the class, where Harry can cast spells:
public class HarryPotter {
private int level; // Harry's level
private String[] spells = new String[] { "Lumos", "Expelliarmus", "Expecto Patronum" };
private int spellIndex = 0; // Index to cycle through all available spells
public HarryPotter(int level) {
this.level = level;
}
public String castSpell() {
String spell = spells[spellIndex];
spellIndex = spellIndex % level; // Using mod to cycle spells based on level
return spell + "!";
}
}
With this setup, Harry can cast different spells based on his level. Now, we want to ensure that our HarryPotter class works correctly. Since we aren't using any testing frameworks, we'll try a few simple approaches:
Approach 1: Testing with main Method and Console Output
The first approach is to add testing code directly to a main method, creating an instance of HarryPotter and checking the output manually. Here's an example:
public class Test {
public static void main(String[] args) {
HarryPotter harry = new HarryPotter(2);
System.out.println("Spell 1: " + harry.castSpell());
System.out.println("Spell 2: " + harry.castSpell());
}
}
Drawback: This approach relies on us checking the console output manually, which can be tedious and error-prone, especially for larger programs.
Approach 2: Using Simple Assertions
To make testing easier, we can add basic assertion-like checks to automatically verify the output. By comparing expected values with actual values and throwing an exception if they don't match, we avoid manually inspecting the output. Here's how:
public class Test {
public static void main(String[] args) {
HarryPotter harry = new HarryPotter(2);
if (!harry.castSpell().equals("Lumos!")) {
throw new RuntimeException("First spell should be Lumos!");
}
if (!harry.castSpell().equals("Expelliarmus!")) {
throw new RuntimeException("Second spell should be Expelliarmus!");
}
}
}
Now, if a test fails, an exception is thrown, pointing us directly to the issue. This is a more effective way to test compared to simply printing results.
Summary
Testing without frameworks may not be as streamlined as using JUnit, but simple assertions in the main method can still help catch basic issues. This approach provides instant feedback on whether the method behaves as expected.
Please open Telegram to view this post
VIEW IN TELEGRAM
❤1👍1🔥1
The💪 :
https://nextleap.app/online-compiler/java-programming/m7x3nbndn
Feel free to share your thoughts in the comments! If you enjoyed the challenge, drop a👍 or ❤️
HarryPotter#castSpell
method has a bug - see if you can spot and fix it https://nextleap.app/online-compiler/java-programming/m7x3nbndn
Feel free to share your thoughts in the comments! If you enjoyed the challenge, drop a
Please open Telegram to view this post
VIEW IN TELEGRAM
❤1 1
Your thoughts on this post?
Anonymous Poll
13%
Too challenging
0%
A bit long…
25%
Just right!
63%
I’m ready for JUnit!
What is the output of the following code?
Anonymous Quiz
15%
15 Java 5 10
42%
15 Java 15
24%
15 Java 510
18%
510 Java 510
Hey everyone! 👋
I wanted to take a moment to share some thoughts about this channel and why the activity here has been low🔋
When I started this channel, my goal was to help beginner developers get into Java📱 development - sharing insights on technologies, learning paths, and best practices. However, over time, I noticed that there was very little engagement - few likes, comments, or discussions. And to be honest, that affected my motivation. Without feedback, it’s hard to understand if the content is actually useful or interesting.
Because of this, I decided to focus on something that would be more engaging for me personally - learning new technologies while sharing my progress. Recently, I started a new channel where I document my journey of learning Swift🔢 and SwiftUI 👶 This time, I’m writing in Russian, so if you understand the language and are interested in 🍏 development, feel free to check it out: https://t.me/+9Y323c-9kkw1MzBi
That’s not all! In the near future, I’m planning to create another channel where I will share my experience learning AWS👩💻 and Google Cloud 👩💻
This one will be in English, just like this Java channel.
I appreciate everyone who has been here, and if you’re interested in my new journey - whether it’s Swift now or cloud technologies in the future - stay tuned!
Let’s keep learning together!🚀
I wanted to take a moment to share some thoughts about this channel and why the activity here has been low
When I started this channel, my goal was to help beginner developers get into Java
Because of this, I decided to focus on something that would be more engaging for me personally - learning new technologies while sharing my progress. Recently, I started a new channel where I document my journey of learning Swift
That’s not all! In the near future, I’m planning to create another channel where I will share my experience learning AWS
This one will be in English, just like this Java channel.
I appreciate everyone who has been here, and if you’re interested in my new journey - whether it’s Swift now or cloud technologies in the future - stay tuned!
Let’s keep learning together!
Please open Telegram to view this post
VIEW IN TELEGRAM
Telegram
Kotlin/Swift (iOS) Туда и Обратно
Канал - журнал, рассказывающий об опыте изучения Swift & iOS backend-разработчиком на Java & Kotlin
How to Ask ChatGPT 📱 as a Beginner Developer (and Not Get Burned)
🔤 🔤 - Intro
When I was just starting to code, ChatGPT didn’t exist.
(Yes, I’m that old. Okay, maybe not that old, but you get the point.)
Back then, I had to google endlessly, dig through Stack Overflow threads from 2012, and cry over cryptic compiler errors that no one seemed to explain well. So when ChatGPT appeared, I was like - wow. This changes everything.
But here’s the catch: it also makes it dangerously easy to stop thinking. To just copy-paste code that looks right but isn’t. Especially if you’re just getting started.
That’s why I’m writing this mini-series - short, honest posts for beginners or junior devs on how to actually use ChatGPT to learn, not just survive.
If you’re new to coding, or even just feeling a bit lost - you’re not alone.
I’ll try to keep things short, real, and sometimes a little bit funny.
Stay tuned for Post🔤 🔤
When I was just starting to code, ChatGPT didn’t exist.
(Yes, I’m that old. Okay, maybe not that old, but you get the point.)
Back then, I had to google endlessly, dig through Stack Overflow threads from 2012, and cry over cryptic compiler errors that no one seemed to explain well. So when ChatGPT appeared, I was like - wow. This changes everything.
But here’s the catch: it also makes it dangerously easy to stop thinking. To just copy-paste code that looks right but isn’t. Especially if you’re just getting started.
That’s why I’m writing this mini-series - short, honest posts for beginners or junior devs on how to actually use ChatGPT to learn, not just survive.
If you’re new to coding, or even just feeling a bit lost - you’re not alone.
I’ll try to keep things short, real, and sometimes a little bit funny.
Stay tuned for Post
Please open Telegram to view this post
VIEW IN TELEGRAM
❤3
Post 🔤 🔤 - Always run the code
When ChatGPT first came out, I was amazed.
You could ask: “How do I sort a list?” - and💥 it gives you code. Clean, confident, senior-style 😎
You copy it. Paste it. Move on.
But then you realize:
- it doesn’t compile😵
- the method doesn’t exist😵💫
- or worse - it kind of works, but not the way you want🤨
As a beginner, it’s so easy to stop thinking and just trust the code. I’ve been there - that’s why I’m saying:
Always run the code.
📌 Run it in your IDE, in a Playground, or in an online sandbox. Make sure:
🟡 it compiles,
🟡 it behaves as expected,
🟡 and you roughly understand what it’s doing.
Want to level up faster?
Write a quick note to yourself: what did you just learn? Even a sentence helps.
🙃 ChatGPT is a great assistant, but it can make mistakes.
You’re not dumb - you just need to check the code.
So:
Trust, but verify. Run it. Watch it. Understand it.
When ChatGPT first came out, I was amazed.
You could ask: “How do I sort a list?” - and
You copy it. Paste it. Move on.
But then you realize:
- it doesn’t compile
- the method doesn’t exist
- or worse - it kind of works, but not the way you want
As a beginner, it’s so easy to stop thinking and just trust the code. I’ve been there - that’s why I’m saying:
Always run the code.
Want to level up faster?
Write a quick note to yourself: what did you just learn? Even a sentence helps.
🙃 ChatGPT is a great assistant, but it can make mistakes.
You’re not dumb - you just need to check the code.
So:
Trust, but verify. Run it. Watch it. Understand it.
Please open Telegram to view this post
VIEW IN TELEGRAM
❤2
Post 🔤 🔤 - Don’t just ask “how”, ask “why”
When I work with Java, it’s all crystal clear: I know the ecosystem, I understand what’s going on under the hood, and any steps from ChatGPT or documentation feel like an open book📖 But recently I started learning Swift and SwiftUI - and things got trickier.
Sure, you can just follow step-by-step instructions: copy, paste, run - done. But without knowing why it works, you risk falling into the “magic” trap. It’s fine today, but tomorrow the context changes, and the code breaks - and you have no clue where to start debugging.
That’s why I always try to dig deeper. If ChatGPT gives me an answer, I’ll ask: why is it like this? what if I do it differently? are there alternatives?
⚠️ One catch: this can take a lot of time. The tree of topics can grow wide and deep. You ask about one thing, and the explanation sparks more questions. Sometimes you start with a SwiftUI layout question and end up discussing CPU architecture 🤯 ChatGPT doesn’t always know when to stop, so sometimes it’s better to have a mentor who will say, “Enough, go write code.”
💡 My tip: when learning something new, switch between two modes - “just get it done” and “now understand why it works”. That way you get both results and lasting knowledge.
When I work with Java, it’s all crystal clear: I know the ecosystem, I understand what’s going on under the hood, and any steps from ChatGPT or documentation feel like an open book
Sure, you can just follow step-by-step instructions: copy, paste, run - done. But without knowing why it works, you risk falling into the “magic” trap. It’s fine today, but tomorrow the context changes, and the code breaks - and you have no clue where to start debugging.
That’s why I always try to dig deeper. If ChatGPT gives me an answer, I’ll ask: why is it like this? what if I do it differently? are there alternatives?
Please open Telegram to view this post
VIEW IN TELEGRAM