Wednesday, 22 May 2019

Java: concatenation of characters return an integer


In Java, when you try to concatenate two characters using '+' operator, then the character is interpreted as integer value.

Example
char ch1 = 'a';     //97 in decimal
int result = ch1 + ch1; //97 + 97 = 194

App.java
package com.sample.app;

public class App {

 public static void main(String args[]) {
  char ch1 = 'a'; // 97 in decimal
  int result = ch1 + ch1; // 97 + 97 = 194

  System.out.println("ch1 : " + ch1 + " -> " + (int) ch1);

  System.out.println("(ch1 + ch1) : " + result + " -> " + (char) result);

 }
}

Output
ch1 : a -> 97
(ch1 + ch1) : 194 -> Â


You may like

No comments:

Post a Comment