5 Tricky Java Programming Problems
1. Find the maximum and minimum value of a triplet without using conditional statements
Given three integers, find the maximum and minimum number between them without using any conditional statement (if, switch) or ternary operator.
Solution 1. Using short-circuiting in Boolean expressions
Briefly, short-circuiting is when in some boolean expression like a && b && ... && d (where a..z — some expressions) we skip execution of the rest of the expression if the previous part guarantees us some boolean value. For example, expression true || b guarantees us true because of the first value, so we’re not going to execute b expression.
So let’s put this approach into our solution:
Solution 2. Using repeated subtraction
Note: this solution works with positive integers
2. Swap two numbers without using a third variable in one line (Java)
Given two integers, swap them in a single line in Java.
Let’s suppose we have two variables: x and y.
Solution 1. Using Bitwise XOR (^) Operator
We have ^ operation. And in Java assignment may be an expression that returns an assigned value. Let’s use both facts together:
Solution 2. Using Addition and Subtraction Operator
Solution 3. Using Multiplication and Division Operator
3. Multiply two numbers without using a multiplication operator or loops
Given two integers, multiply them without using the multiplication operator or loops.
Solution
As we know, multiplication is summing x value y times. This would be easy if we could use loops. But we also may use recursion instead:
4. Print “Hello World” with an empty main
Solution 1. Using static block
When our program tries to run main, it runs static block before:
Solution 2. Initialize field using a static method
Solution 3. Initialize inner static class
Solution 4. Call static variable from outer class
Solution
We may rewrite the expression n*15 as n*15 = n*16 - n = (n << 4) - n
Hi Omar Ismail Your posts really helps us to grow in the field of java i really appreciate your efforts.