Home
IT Knowledge
Inspiration
Languages
EN

# Java - how to get long max and min value with bitwise operations?

12 points
Created by:
351

Short solution:

``````long MAX_VALUE = -1L >>> 1L;
long MIN_VALUE = -1L << 63L;

System.out.println(MAX_VALUE); //  9223372036854775807
System.out.println(MIN_VALUE); // -9223372036854775808``````

Other short solution:

``````long MAX_VALUE = ~0L >>> 1L;
long MIN_VALUE = ~MAX_VALUE;

System.out.println(MAX_VALUE); //  9223372036854775807
System.out.println(MIN_VALUE); // -9223372036854775808``````

## 1. Using bit shift operators

``````public class Example1 {

public static void main(String[] args) {

long MAX_VALUE = -1L >>> 1L;
long MIN_VALUE = -1L << 63L;

System.out.println(MAX_VALUE); //  9223372036854775807
System.out.println(MIN_VALUE); // -9223372036854775808

// 0111111111111111111111111111111111111111111111111111111111111111
// 1000000000000000000000000000000000000000000000000000000000000000
}

private static String toBinaryWithLeadingZeros(long MAX_VALUE) {
String binaryString = Long.toBinaryString(MAX_VALUE);
return String.format("%64s", binaryString).replace(' ', '0');
}
}``````

## 2. Using bit shift and NOT operators

``````public class Example2 {

public static void main(String[] args) {

long MAX_VALUE = ~0L >>> 1L;
long MIN_VALUE = ~MAX_VALUE;

System.out.println(MAX_VALUE); //  9223372036854775807
System.out.println(MIN_VALUE); // -9223372036854775808

// 0111111111111111111111111111111111111111111111111111111111111111
// 1000000000000000000000000000000000000000000000000000000000000000
}

private static String toBinaryWithLeadingZeros(long MAX_VALUE) {
String binaryString = Long.toBinaryString(MAX_VALUE);
return String.format("%64s", binaryString).replace(' ', '0');
}
}``````

## 3. Stanrad way of getting Long MAX and MIN value in java

``````public class Example3 {

public static void main(String[] args) {

System.out.println( Long.MAX_VALUE ); //  9223372036854775807
System.out.println( Long.MIN_VALUE ); // -9223372036854775808
}
}``````