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

Java

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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)

Solution 2 - Java

These + and - are unary ones.

More specifically, it is in fact:

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

Solution 3 - Java

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

Solution 4 - Java

> 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionprab2112View Question on Stackoverflow
Solution 1 - JavaPaco AbatoView Answer on Stackoverflow
Solution 2 - Javajohnchen902View Answer on Stackoverflow
Solution 3 - JavaWiiMaxxView Answer on Stackoverflow
Solution 4 - JavaMarko TopolnikView Answer on Stackoverflow