简体   繁体   中英

Why mixing + and cast does not produce an error in “+(int)+(long)-1”?

Why does this print 1?

import java.util.*;
import java.lang.*;
import java.io.*;


class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        System.out.println((byte)+(short)-(int)+(long)-1);
    }
}

Can we mix casting and +,- unary operators? I know that we can do casting multiple times, but why doesn't putting + ,- unary operators in between produce an error?

You are not adding nor substracting. Those + and - operators are unary sign operators.

See documentation at The Unary Operators section.

The sequence at stake:

(byte)+(short)-(int)+(long)-1

is evaluated from right to left like this:

the initial value is -1
casting to long (which is still -1)
unary + sign (still -1)
casting to int (still -1)
unary - sign (now the value is 1)
so on (the value remains 1 until the end)

These + and - are unary ones.

More specifically, it is in fact:

System.out.println((byte) (+((short) (-((int) (+((long) -1)))))));

if you remove all casting from your example, because in this case it will do nothing

System.out.println((byte)+(short)-(int)+(long)-1);

will become

System.out.println( + - + -1);

now you can see that just the operators are still there and because minus and minus are plus your result will be 1

basically you can think of it like:

var mylong  = +(long)-1;      <- -1
var myint   = -(int)mylong;   <-  1
var myshort = +(short)myint;  <-  1
var mybyte  =  (byte)myshort; <-  1

I know we can do casting multiple times. But putting + ,- unary operators in between doesn't give error?

It is simply a consequence of the consistency of Java's grammar. When you write

+ 1

what you actually wrote is a unary numeric expression which decomposes into two parts:

  1. the unary plus operator: +
  2. a numeric expression , in this case the int literal 1 .

Another example of a numeric expression is a cast expression (also unary):

(int) 1

Therefore you can substitute this for the original 1 above:

+ (int) 1

Repeating the same consistent process we can end up with a nested unary expression of arbitrary complexity. To return to your key question:

why?

Because Java would actually need a specific rule against such expressions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM