9

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

4
  • 2
    Can i know why the downvote ? Jul 16, 2014 at 13:23
  • Break the line yup and look at the values
    – mmmmmm
    Jul 16, 2014 at 13:24
  • 2
    These are all unary operators and casts.
    – blgt
    Jul 16, 2014 at 13:24
  • -1 Because it is copy question; link shows it isn't... so LMGTFY
    – ST3
    Jul 23, 2014 at 6:14

3 Answers 3

20
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
15

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.

8

Due to type casting it's equivalent to

public class Test {

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

}

}

Not the answer you're looking for? Browse other questions tagged or ask your own question.