-3

the output of below code is 320.

    char a = ' ';
    int m = a* 10;
    System.out.println(m);

Can some one explain me how? Thank you in advance. On what basis its giving 320. As per my knowledge it should throw exception. But i am getting 320.

Hari
  • 89
  • 1
  • 2
  • 9
  • ASCII value of space is 32 so when you multiply by 32 i'ts giving 320. char can be multiplied by integer in java. – Pradeep Simha Apr 26 '19 at 19:52
  • See what happens when you run `System.out.println((int) a);` – TNT Apr 26 '19 at 20:04
  • @PradeepSimha, You are telling me to read basics of java. If you are explaining anything to others, explain it properly. The above process is called **Type promotion**. Whenever you are explaining to others, use technical terms. If you don't know, please read java doc in official site. – Hari Jun 09 '19 at 12:08

1 Answers1

2

All characters have a numeric value and as such can be subjects to mathematical operations.

The following:

      for (char c : "abcdefghijkln".toCharArray()) {
         System.out.println("c = " + c + ", c has value of " + (int) c
               + ", c * 10 = " + (c * 10));

      }

Produces the following output.

c = a, c has value of 97, c * 10 = 970
c = b, c has value of 98, c * 10 = 980
c = c, c has value of 99, c * 10 = 990
c = d, c has value of 100, c * 10 = 1000
c = e, c has value of 101, c * 10 = 1010
c = f, c has value of 102, c * 10 = 1020
c = g, c has value of 103, c * 10 = 1030
c = h, c has value of 104, c * 10 = 1040
c = i, c has value of 105, c * 10 = 1050
c = j, c has value of 106, c * 10 = 1060
c = k, c has value of 107, c * 10 = 1070
c = l, c has value of 108, c * 10 = 1080
c = n, c has value of 110, c * 10 = 1100

WJS
  • 36,363
  • 4
  • 24
  • 39