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


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

Updated on: 26-Jun-2020

525 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements