What is the next topic
Anonymous Poll
64%
Testing Framework
27%
Application distribution
9%
External libraries
👍1🔥1
What is the value of Math.abs(Integer.MIN_VALUE)
Anonymous Quiz
22%
0
44%
-2147483648
0%
-2147483647
0%
2147483648
11%
2147483647
22%
Exception
Why Math.abs(Integer.MIN_VALUE) equals Integer.MIN_VALUE in Java ☕️
In Java, we often use the
However, an interesting trick happens when you apply
In Java, an int is a 32-bit signed integer, which means it can represent values defined as:
Notice that the absolute value of
Why Does This Happen?
Here's what happens under the hood when you try to get the absolute value of
1. Two's Complement Representation (wiki https://en.wikipedia.org/wiki/Two%27s_complement): Java uses two's complement to represent signed integers. In this system, the negative of a number is formed by flipping its bits and adding 1. However, in the case of
2. Overflow: When applying
In other words it’s similar to
3. Special Case in Java: Java's
Explanation Through Bit Representation
To better understand this behavior, let's examine the binary representation of
10000000 00000000 00000000 00000000
(the leftmost 1 indicates that the number is negative in two's complement).
Negating this value in two's complement results in an overflow back to the same number because no positive counterpart exists within the 32-bit int range.
Conclusion
The reason
#java #beginner
In Java, we often use the
Math.abs()
function to calculate the absolute value of a number. It’s supposed to return the positive equivalent of any number by stripping away its negative sign.However, an interesting trick happens when you apply
Math.abs()
to Integer.MIN_VALUE
. Surprisingly, it returns Integer.MIN_VALUE
itself, not its positive counterpart. Let’s explore why.In Java, an int is a 32-bit signed integer, which means it can represent values defined as:
Integer.MIN_VALUE = -2,147,483,648
Integer.MAX_VALUE = 2,147,483,647
Notice that the absolute value of
Integer.MIN_VALUE
would theoretically be 2,147,483,648, which is one greater than Integer.MAX_VALUE
. But Java's int type cannot represent numbers larger than Integer.MAX_VALUE
. This creates a situation where the positive equivalent of Integer.MIN_VALUE
doesn't exist within the int range.Why Does This Happen?
Here's what happens under the hood when you try to get the absolute value of
Integer.MIN_VALUE
1. Two's Complement Representation (wiki https://en.wikipedia.org/wiki/Two%27s_complement): Java uses two's complement to represent signed integers. In this system, the negative of a number is formed by flipping its bits and adding 1. However, in the case of
Integer.MIN_VALUE
, there’s no positive equivalent because of how two’s complement works. The range for negative values is slightly larger than for positive values.2. Overflow: When applying
Math.abs()
to Integer.MIN_VALUE
, the function tries to negate the value. Negating Integer.MIN_VALUE
would result in 2,147,483,648, which is beyond the representable range of the int type. As a result, the value overflows and remains Integer.MIN_VALUE
.In other words it’s similar to
Integer.MAX_VALUE + 1
wichi is equal to Integer.MIN_VALUE
.3. Special Case in Java: Java's
Math.abs()
function doesn’t throw an error in this situation but recognizes that the result is out of bounds and simply returns Integer.MIN_VALUE
.Explanation Through Bit Representation
To better understand this behavior, let's examine the binary representation of
Integer.MIN_VALUE
:Integer.MIN_VALUE
in binary:10000000 00000000 00000000 00000000
(the leftmost 1 indicates that the number is negative in two's complement).
Negating this value in two's complement results in an overflow back to the same number because no positive counterpart exists within the 32-bit int range.
Conclusion
The reason
Math.abs(Integer.MIN_VALUE)
equals Integer.MIN_VALUE
is due to Java’s use of two's complement arithmetic and the limitations of the int data type. Because Integer.MIN_VALUE
has no positive counterpart in the int range, applying Math.abs()
to it causes an overflow, returning the same negative value. This behavior is a consequence of how integers are represented and negated in binary.#java #beginner
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