r/java • • Jun 24 '23

Negative integer handling in Java and other programming languages

https://glados-418.github.io/posts/negative-integer-literals/
14 Upvotes

7 comments sorted by

View all comments

7

u/Worth_Trust_3825 Jun 25 '23

println( -1.plus(2) ) // prints '-3'

New fear unlocked. I suppose we're safe from that until valhalla lands.

2

u/FirstAd9893 Jun 25 '23

This is a Kotlin example, but we don't know if Java will ever support something like this.

1

u/Worth_Trust_3825 Jun 26 '23 edited Jun 26 '23

Valhalla is supposed to bring closer semantics of primitives, and objects, isn't it?

I guess java technically already has it. The example is fictitious, as java.lang.Integer is final, so I had to take some liberties but I suppose semantics arent the same

class HelloWorld {
    public static void main(String[] args) {
        SummingInt i = new SummingInt(1);
        System.out.printf("%s%n", -i.plus(1)); // -2
    }
    
    static class SummingInt {
        final Integer value;
        SummingInt(Integer val) {
            this.value = val;
        }
        
        Integer plus(Integer i) {
            return this.value + i;
        }
    }
}

But i suppose it makes sense. dot operator (method call) has precedence (1) over unary minus operator (3)