Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of Integer.MAX_VALUE in Java without using the Integer class

I have this question that has completely stumped me. I have to create a variable that equals Integer.MAX_VALUE... (in Java)

// The answer must contain balanced parentesis
public class Exercise{

  public static void main(String [] arg){
    [???]
    assert (Integer.MAX_VALUE==i);
  }
}

The challenge is that the source code cannot contain the words "Integer", "Float", "Double" or any digits (0 - 9).

like image 934
madsword19 Avatar asked Apr 06 '14 01:04

madsword19


2 Answers

Here's a succinct method:

int ONE = "x".length();
int i = -ONE >>> ONE; //unsigned shift

This works because the max integer value in binary is all ones, except the top (sign) bit, which is zero. But -1 in twos compliment binary is all ones, so by bit shifting -1 one bit to the right, you get the max value.

11111111111111111111111111111111 // -1 in twos compliment
01111111111111111111111111111111 // max int (2147483647)
like image 148
Bohemian Avatar answered Nov 15 '22 06:11

Bohemian


As others have said.

int i = Integer.MAX_VALUE;

is what you want.

Integer.MAX_VALUE, is a "static constant" inside of the "wrapper class" Integer that is simply the max value. Many classes have static constants in them that are helpful.

like image 35
Reuben Tanner Avatar answered Nov 15 '22 06:11

Reuben Tanner