1

I'm new to Java programming and I was playing round with a code:

public class Main {
    public static void main(String[] args){
        byte x = 10;
        x = x*10;
        System.out.println(x);
    }
}

This gives a compilation error and I know why. But what I don`t understand is why the code below does not give an error:

public class Main {
    public static void main(String[] args){
        byte x = 10;
        x *= 10;
        System.out.println(x);
    }
}

From what I know

    x *= x;

and

   x = x*x;

are same.

What am I missing then?

khelwood
  • 55,782
  • 14
  • 81
  • 108

1 Answers1

0

The compound assignment operators will perform automatic type-casting. You could find more details on https://www.geeksforgeeks.org/compound-assignment-operators-java/

rnonnon
  • 76
  • 4