Difference between x++ and x= x+1 in Java programming

Java 8Object Oriented ProgrammingProgramming

x++ automatically handles the type casting where as x= x + 1 needs typecasting in case of x is not an int variable. See the example below.

Example

 Live Demo

public class Tester {
   public static void main(String args[]) {
      byte b = 2;
      //Type casting is required
      //as 1 is int and b is byte variable
      b = (byte) (b + 1);
      System.out.println(b);
      byte b1 = 2;
      //Implcit type casting by the compiler
      b1++;
      System.out.println(b1);
   }
}

Output

3
3
raja
Published on 01-Nov-2018 16:39:33
Advertisements