Java Primitives
Software development is all about solving problems and tasks.
Every task is similar to one of:
- calculation on numbers
- images processing (pixels are also numbers)
- text data processing
- User Interface
- transferring data over network
- other data manipulation
In all your programs you will work with simple data structures, they could be combined together to create a new data structure. But at the end any data structure could be handled as a set of numbers.
So don't hesitate and get acquainted with the basic building blocks for any Java program in this wonderful article: https://www.baeldung.com/java-primitives 📗
#begin #java
Software development is all about solving problems and tasks.
Every task is similar to one of:
- calculation on numbers
- images processing (pixels are also numbers)
- text data processing
- User Interface
- transferring data over network
- other data manipulation
In all your programs you will work with simple data structures, they could be combined together to create a new data structure. But at the end any data structure could be handled as a set of numbers.
So don't hesitate and get acquainted with the basic building blocks for any Java program in this wonderful article: https://www.baeldung.com/java-primitives 📗
#begin #java
Baeldung
Introduction to Java Primitives | Baeldung
Learn the basics of Java's primitive data types.
Let's solve something fundamental and easy: https://telegra.ph/Reverse-a-word-01-29
Any feedback is appreciated
#java #beginner
Any feedback is appreciated
#java #beginner
Telegraph
Reverse a word
Hello! 👋 In this short post we will solve a typical task in programming which is given to every beginner. Task You are given a word, you need to reverse it.Examples: word → drow; radar → radar; sequence → ecneuqes; Solution There are many possible solutions…
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
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