Optimize Algorithm for Improved Performance
1. To check if the number is even or odd:
Instead of Modulus %
if(num % 2 == 0)
// even
else if (num % 2 == 1)
//odduse AND Bitwise operator &
if((num & 1)==0)
// even
else if( (num & 1)==1 )
//oddIt’s because
We know that, for all even numbers 1st binary representation bit is ‘0’ and for odd it’s ‘1’.
if num is odd then "num&1" returns '1'
n=10101
&
1=00001
==00001
Similarly, if num is even "num&1" return '0'
n=10110
&
1=00001
==00000So, to put it simply “num&1" returns the first binary bit
2. To divide or multiply a number by 2 or power of 2's
Instead of /, *
int div = num/2;
int mul = num*2;
use Shift operators >> & <<
// DIVISION num >> n == num/2ⁿ
int div = num >> 1; // num/2¹ = num/2
div = num >> 2; // num/2² = num/4
div = nums >> 3; // num/2³ = num/8
// MULTIPLICATION num << n == num*2ⁿ
int mul = num << 1; // num*2¹ = num*2
mul = num << 2; //num*2² = num*4
mul = nums << 3; // num*2³ = num*8Right shift operator “>>”, to shift 1 bit to the right side.
Example:
Binary: 0 0 0 0 1
Positions (powers of 2):
2⁴ 2³ 2² 2¹ 2⁰
So the rightmost bit (the '1' in this case) is the 2⁰ position, which represents the value 1 in decimal
3. To check if the number has a power of 2
like 2,4,8,16,32,64,128….
Brian Kernighan’s Algorithm: “n & (n-1)” → removes one bit ‘1’ from n’s binary representation. We can loop it, to check number of 1s.
boolean bool = n & (n - 1)) == 0;4. Check if two ints/chars are the same:
Instead of traditional “==”
int a = 123, b= 123;
boolean bool = a==b;Use Bitwise unary xor operator “^”
int a = 123, b= 123;
boolean bool = (a^b)==0;
/*
a^b returns 0 if same & bitwise comparison if different.
So, 0^a = a and a^a = 0
And 5^3 == 6 not 8
Note: For chars xor ^ returns the +ve ascii difference */
In the truth table for the XOR (Exclusive OR) logic gate returns
false (0) - if both inputs are the same and
Get ✨ Srinivas Vadige’s stories in your inbox
Join Medium for free to get updates from this writer.
true (1) - if both inputs are different
5. XOR for checking even duplicates
/**
In XOR(^), same values returns false and different returns true.
true ^ true = false | 1^1 = 0
false ^ false = false | 0^0 = 0
true ^ false = true | 1^0 = 1
*/
int[] arr = {1,1,2,2,3,4,4,4,4,5,5};
int noDup = Arrays.stream(arr).reduce(0, (a,b)->a^b);
// or
noDup = 0;
for(int x: arr) noDup ^= x;
System.out.println(nonDup); // 36. To find the length of the number
Instead of str.length()
int len = String.valueOf(num).length();use Math.log10()
int len = (int) Math.log10(num)+1;
len = (int) Math.log10(Math.abs(num))+1; // base case for -ve
len = (int) Math.log10(Math.abs(num==0?1:num))+1; // base case for 07. To check subString at a specific index
Instead of using str.substring().eqauls(subStr)
String str = "HelloWorld!";
String sub = "World";
int i = 5;
boolean isPresent = str.substring(i, i + sub.length()).equals(sub);Use str.startsWith(i, subStr)
boolean isPresent = str.startsWith(sub, i);8. Logical AND “&&” vs Bitwise AND “&” Operators
boolean foo() {
sout("foo");
return ture;
}
boolean bar() {
sout("bar");
return false;
}
boolean qux() {
sout("qux");
return true;
}
if(foo() && bar() && qux()) {
sout("inside-&&-if");
}
// prints "foo bar" --> so, stops traverse if we get one False
if(foo() & bar() & qux()) {
sout("inside-&-if");
}
// prints "foo bar qux" ---> traverse all, but goes inside if all are TrueIn the “Bitwise & if block”, both “foo” and “bar” will print, but don’t go inside of that if condition.
In the “Logical && if block”, only “foo” will print and so it stops there
Because short-circuit && and bit-wise & is different. Here we can use Bitwise OR “|” also.
boolean a(){
System.out.println("a");
return true;
}
boolean b(){
System.out.println("b");
return false;
}
boolean c(){
System.out.println("c");
return true;
}
if (a() || b() || c())) {
System.out.println("inside-||-if");
}
// prints: a inside-||-if ---> so, stops traverse untill if we get one True
if (a() | b() | c())) {
System.out.println("inside-|-if");
}
// prints: a b c inside-|-if ---> traverse all, but goes inside if atleast 1 T9. Use Bitwise OR “|” to catch multiple exceptions
try {
//logic
} catch(WebClientResponseExecption | IllegalStateException e){
if(e instanceof IllegalStateException) {} else {}
}10. Use java.util.function.Optional for short circuits like js
String foo = Optional.ofNullable(f1).orElse(f2); // which is simalar to JavaScript -> var foo = f1 || f2
// escape emtpy String in Optional
String str=“”;
String optionalString = Optional.ofNullable(str).filter(Predicate.not(String::isBlank)).orElse("backup string")
Optional<String> ostr = Optional.ofNullable(str).filter(o -> !o.isBlank());11. Use incre++/decre — operator in the condition
Instead of using an integer in condition and updating in the logic later like
while (groupPrev != null && k > 0) {
groupPrev = groupPrev.next;
k--;
}decrement and compare at the same time
while (groupPrev != null && k-- > 0)
groupPrev = groupPrev.next;Similarly, we can also update & compare int[] or Integer[] array in the if(arr[i]++>0);
12. Use “e” scientific notation for “exponent of 10”:
1e9 means (1*10)⁹ → 1.0E9 → 1 billion
2e-3 means (2*10)^-3 → 0.002
Similarly 1e9 + 7 means 1.000000007E9
Note that “e” returns double. so, cast it accordingly.
int mod1 = (int) (1e9 + 7); //1000000007
int mod2 = (int) 1e9 + 5; //100000000513. Integer Literals “_” in between numbers:
int mod1 = 1_000_000_007; // instead of 1000000007 or (int) (1e9 + 7)14. Use JNI native methods
In-built Java methods with “public static native” are called JNI native methods.
Even though Java is a high-level language with a rich standard library, there are some scenarios where native (C/C++) code is necessary. That’s where JNI (Java Native Interface) comes in.
Use JNI when Java alone can’t do the job — either due to performance, platform access, or legacy C/C++ code integration.
Use
System.arraycopy(merged, 0, nums1, 0, m + n);instead of traditional for loop copy
And other JNI native methods like Arrays.sort(), Math.sqrt(), Math.pow(), Math.sin(), Math.abs(), Math.min(), Math.max(), System.currentTimeMillis(), System.nanoTime(), Object.hashCode(), Thread.sleep(), Integer.valueOf(), String.intern(), Class.forName(), Class.getName().
Note: Arrays.sort() uses native code (JNI-backed or heavily optimized intrinsics) but Collections.sort() is Pure Java implementation — no JNI involved







