Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Integer.MAX_VALUE vs Kotlin Int.MAX_VALUE

Tags:

java

kotlin

I noticed, one interesting thing.
Java's Integer.MAX_VALUE is 0x7fffffff (2147483647)
Kotlin's Int.MAX_VALUE is 2147483647
but if you write
in Java:
int value = 0xFFFFFFFF; //everything is fine (but printed value is '-1')
in Kotlin:
val value: Int = 0xFFFFFFFF //You get exception The integer literal does not conform to the expected type Int

Interesting right? So you're able to do something like new java.awt.Color(0xFFFFFFFF, true) in Java but not in Kotlin.

Color class works with that int on "binary" level, so everything works fine for both platforms with all constructors (Color(int rgba) or Color(int r, int g, int b, int a)).
Only workaround which I found for kotlin is java.awt.Color(0xFFFFFFFF.toInt(), true).

Any idea why is it like this in Kotlin?

like image 399
Kikju Avatar asked Nov 23 '17 20:11

Kikju


People also ask

What is the integer MAX_VALUE in Java?

Integer.MAX_VALUE is a constant in the Integer class of java.lang package that specifies that stores the maximum possible value for any integer variable in Java. The actual value of this is. 2^31-1 = 2147483647.

What is integer Min_value & integer MAX_VALUE in Java?

The Integer. MIN_VALUE is a constant in the Integer class that represents the minimum or least integer value that can be represented in 32 bits, which is -2147483648, -231. This is the lowest value that any integer variable in Java can hold.

What happens when int exceeds max value?

If you exceed the MaxValue, then you get into negative territory. Anything with the top bit set in a signed integer is a negative number, and the Max value is a single 0 bit in an otherwise 1 filled 32 bit word. If you add a value to that, then the new value will have the top bit set, and thus be negative.


2 Answers

I think, this problem should be solved by Kotlin 1.3 and UInt See more here: https://kotlinlang.org/docs/reference/whatsnew13.html#unsigned-integers

like image 104
Kikju Avatar answered Oct 04 '22 19:10

Kikju


This is partially answered here:

In Kotlin you need to prepend the - sign to denote negative Int which is not true in Java.

So it seems that Java will interpret hex literals as signed, whereas Kotlin will treat them as unsigned.

The negation would have to be done manually.

Small aside: JetBrains' Kotlin converter actually converts

int a = 0xffffffff;

to

var a = -0x1

but this may just be it realizing exactly what you have noticed.


The part of the spec for hexadecimal literals doesn't mention this at all, however.

like image 25
Salem Avatar answered Oct 04 '22 21:10

Salem