Why can't I write ch=ch+1; instead of ch++; though they have same meaning

  • A+
Category:Languages
package practicejava;  public class Query {      public static void main(String[] args) {         char ch = 66;         System.out.println("character= " + ch);          ch++;          System.out.println("character = " + ch);      } } 

Technically ch++; and ch=ch+1; are the same but why do I get an error when I write ch=ch+1; instead of ch++;?

 


You need to provide a cast in order to do that :

ch = (char) (ch + 1); 

This is because the expression ch + 1 is is promoted (upcast) to an int. In order for you to reassign this expression to a char you need to explicitly downcast it.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: