Difference between arithmetic + (Plus) operator and ++ (Increment) operator.

Difference between arithmetic + (a+1) operator and ++ (a++) operator.

Here is some example to understand both operators.

Source 1:

package com;
public class DiffBtwArthOperAndIncreOperator {

public static void main(String args[]) {

byte b = 2;

b = b+1;

System.out.println("Print a value   "+b);

}

}

 

Response 1:

Compile Time Error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

Type mismatch: cannot convert from int to byte

at com.DiffBtwArthOperAndIncreOperator.main(DiffBtwArthOperAndIncreOperator.java:6)

After getting Response First question arise , why this error appear.

Reason behind this is when we use + operator response type = max (int, type 1st value, type 2nd value)

For above message response type max (int, byte, int) = int

In above program 2nd value type is int because default any integral number is int type.

Similar to Source 1 we will get compile time error in source 2.

Source 2:

package com;

public class DiffBtwArthOperAndIncreOperator {

public static void main(String args[]) {

byte b = 2;

byte c = 1;

b =  b+c;

System.out.println("Print a value   "+b);

}

}

 

Response 2:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

Type mismatch: cannot convert from int to byte

at com.DiffBtwArthOperAndIncreOperator.main(DiffBtwArthOperAndIncreOperator.java:7)

 

Reason for above error:

+ Operator response type = max (int, type 1st value, type 2nd value)

For above message response type max (int, byte, byte) = int

Source 3:

package com; public class DiffBtwArthOperAndIncreOperator { public static void main(String args[]) { byte b = 2; b = (byte) (b+1); System.out.println("Print a value "+b); } }

 

Response 3:

Print a value 3


 

In Source 3 we are using external type casting.

Source 4:

package com;

public class DiffBtwArthOperAndIncreOperator {

public static void main(String args[]) {

byte b = 2;

b++;

System.out.println("Print a value   "+b);

}

}

 

Response 4:

Print a value 3


 

When we use ++ increment operator it will type cast internally because of this we are not getting any error in Source 4.

Leave a Reply

Your email address will not be published. Required fields are marked *