Can someone please explain how this Java code is working?

I am beginner in Java and I am looking at a problem that I can’t figure out the output to? On the 16th line, why is it giving me the output of -2? Can someone explain the math here?

public class Test2
{
   public static void main(String[] args)
   {
     int score = 0;
     System.out.println(score);
       
     score++;
     System.out.println(score);
       
     score *= 0;
     System.out.println(score);
       
     int penalty = 5;
     score -= penalty/2;
     System.out.println(score);
   }
}
public class Test2
{
   public static void main(String[] args)
   {
     int score = 0;
     System.out.println(score);
    
//first_result = 0* (because score = 0)

     score++;
     System.out.println(score);
       
//*second_result = 0 + 1 = 1 (because you increment)*

     score *= 0;
     System.out.println(score);

 //***Third_result = second_result (score = 1) * 0 = 1 * 0 = 0***

     int penalty = 5;
     score -= penalty/2;
     System.out.println(score);

//***fourth_result = third_result  (score = 0) - penalty / 2 = 0 - (5 / 2) = 0 - 2 = -2 (because of the integer division you get 2 and not 2.5!)***

   }
}

I hope the explanation helps a little!

3 Likes