2
  1. char ch = 'A';

  2. ch += 32;. //This works fine

  3. ch = ch + 32; //this doesn't work

Why does line 2 work and line 3 doesn't, although they represent the same operation?

hotfix
  • 3,376
  • 20
  • 36
sahanir
  • 63
  • 4

1 Answers1

4

Why don't you use Character class static methods?

https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html

Character.toUpperCase(ch)

Nevertheless to answer your question, java requires you to cast primitives when you would loose precision during the assignment, so when on the righand site you have 32bit int and on the lefthand side 16bit you need to explicitly cast it. So when a righthand side is an int, you need to cast. If you cast to char your code will work fine. Still just use Character class

    long l = 34; //this is fine     
    int i = 2L; //compile error, you loose precision in that assigment

Also check Why are we allowed to assign char to a int in java?

maslan
  • 2,078
  • 16
  • 34