Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "int i = (byte) + (char) - (int) + (long) - 1" is 1? [duplicate]

Tags:

java

I stumbled upon this code on internet

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int i = (byte) + (char) - (int) + (long) - 1;
        System.out.println(i);

    }

}

It prints 1.

Can i know why ?

Here is the source --> http://www.javacodegeeks.com/2011/10/weird-funny-java.html

like image 757
Abhishek Singh Avatar asked Jul 16 '14 13:07

Abhishek Singh


2 Answers

int i = (byte) + (char) - (int) + (long) - 1;
            ^-------^--------^-------^ Type casting

+ - + - are assigning the sign (Unary Operators) to the number, so - then + then - and finally + gives you 1.

If we just ignore the type casts we have (+(-(+(-(1)))))=1

Equivalent code:

long a = (long) - 1;
int b = (int) + a;
char c = (char) - b;
int finalAns = (byte) + c;
System.out.println(finalAns); // gives 1
like image 113
akash Avatar answered Sep 19 '22 08:09

akash


Because after operator precedence rules are applied it becomes equivalent to:

int i = (byte) ((char) -((int) ((long) -1)));

which evaluates to -(-1) which is 1.

like image 30
OldCurmudgeon Avatar answered Sep 18 '22 08:09

OldCurmudgeon