-1
 class Example {
    public static void main(String args[]){
        System.out.println(12+8/5%4*(5-4/5)+4*5);
    }
 }

Why the output is 37? Can anyone explain? I'm a beginner in java

Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
Nelumi
  • 1
  • 3

2 Answers2

1

Check the precedence of the operators in java:

12+8/5%4*(5-4/5)+4*5
12+8/5%4*(5-0)+4*5
12+8/5%4*5+4*5
12+1%4*5+4*5
12+1*5+4*5
12+5+20
37
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
user3134614
  • 140
  • 1
  • 2
  • 11
0

You have: 12+8/5%4*(5-4/5)+4*5

In the post of user3134614

12+8/5%4*(5-4/5)+4*5
12+8/5%4*(5-0)
12+8/5%4*5+4*5
12+1%4*5+4*5
12+1*5+4*5
12+5+20
37

You have the basic operators

  • + add two numbers
  • - subtract two numbers
  • * Multiply two numbers
  • / divide two numbers

And these, a little more advanced

  • % gets the remainder of two numbers, that is, that divides them and obtains the remainder, if the number is even, then the rest is zero, and if it is odd, it is another number

    For example 4%4 would be 4 divided by 4 results in 2 and 2 + 2 = 4, there is no remainder, on the other hand 5%4 = 1, because 2 + 2 = 4 and over 1 of 5

  • The parentheses () separate a mathematical expression and return it as a single quantity, example

    5 - (3-2) * 2 is equivalent to 5 - (1) * 2 = 5 - 2 = 3

Then

12+8/5%4*(5-4/5)+4*5
12+8/5%4*(5-0) is 12+8/5%4*(5 - (4/5) = 0.8, but converted to integer is 0, then 5 - 0 = 5)
12+8/5%4*5+4*5 is 12+ (8/5 = 1.6, but to integer is 1) %4*5+4*5
12+1%4*5+4*5 is 12+ (1%4 = 1 (1 is different of 4 then result is 1)) *5+4*5
12+1*5+4*5 is 12 + (1*5 = 5) + (4*5 = 20)
12+5+20 and 12 + 5 + 20 = 37
37
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Héctor M.
  • 2,302
  • 4
  • 17
  • 35