mpmp
mpmp

Reputation: 2459

Java: Addition of integers with parentheses

Consider the two following lines of code:

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

This is the output that I get:

0
1

Why is this the case? Does Java arithmetic follow PEMDAS rules?

Upvotes: 0

Views: 1029

Answers (3)

Malik Brahimi
Malik Brahimi

Reputation: 16711

I don't see the issue, your code does follow PEMDAS. The only issue is that you're not getting 0.5 because you're using integer division. Try this:

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

Upvotes: 2

Anthony Palumbo
Anthony Palumbo

Reputation: 314

Yes, it follows the PEMDAS rule and it also truncates answers (cuts off digits after the decimal place without rounding).

Upvotes: 1

Oskar Persson
Oskar Persson

Reputation: 6765

The first one is just (1 + 0)/2 = 1/2 which gives you 0 since you are working with integers.

The second one is 1 + 0/2 = 1 + 0 = 1 which gives you 1.

Upvotes: 0

Related Questions