为什么一个char +另一个char =一个奇怪的数字 [英] why does a char + another char = a weird number

查看:303
本文介绍了为什么一个char +另一个char =一个奇怪的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是代码片段:

  public static void main(String [] arg)
{
char ca ='a';
char cb ='b';
System.out.println(ca + cb);
}

输出为:

  195 

为什么会这样?我认为'a'+'b'将是ab 12 3




解决方案

+ code>是算术加法,不是字符串连接。您必须执行+ ca + cb ,或使用 String.valueOf Character.toString 方法,以确保 + 的至少一个操作数是 String 将操作符设置为字符串连接。



JLS 15.18添加运算符




+ 运算符 String ,则操作是字符串连接。



否则, + 运算符的每个操作数的类型必须是可转换为原始数值类型的类型,否则会出现编译时错误。


至于为什么要获得195,这是因为在ASCII中,'a'= 97 'b'= 98 97 + 98 = 195




这执行基本的 int char 铸造。

  char ch ='a'; 
int i =(int)ch;
System.out.println(i); // prints97
ch =(char)99;
System.out.println(ch); // printsc

这忽略了字符编码方案的问题约...)。






注意,Josh Bloch指出,很不幸, + 对于字符串连接和整数加法重载(对于字符串连接重载+运算符可能是一个错误。 - Java Puzzlers 拼图11:最后笑)。






另请参阅




Here's the code snippet:

public static void main (String[]arg) 
{
    char ca = 'a' ; 
    char cb = 'b' ; 
    System.out.println (ca + cb) ; 
}

The output is:

195

Why is this the case? I would think that 'a' + 'b' would be either "ab" , "12" , or 3.

Whats going on here?

解决方案

+ of two char is arithmetic addition, not string concatenation. You have to do something like "" + ca + cb, or use String.valueOf and Character.toString methods to ensure that at least one of the operands of + is a String for the operator to be string concatenation.

JLS 15.18 Additive Operators

If the type of either operand of a + operator is String, then the operation is string concatenation.

Otherwise, the type of each of the operands of the + operator must be a type that is convertible to a primitive numeric type, or a compile-time error occurs.

As to why you're getting 195, it's because in ASCII, 'a' = 97 and 'b' = 98, and 97 + 98 = 195.


This performs basic int and char casting.

 char ch = 'a';
 int i = (int) ch;   
 System.out.println(i);   // prints "97"
 ch = (char) 99;
 System.out.println(ch);  // prints "c"

This ignores the issue of character encoding schemes (which a beginner should not worry about... yet!).


As a note, Josh Bloch noted that it is rather unfortunate that + is overloaded for both string concatenation and integer addition ("It may have been a mistake to overload the + operator for string concatenation." -- Java Puzzlers, Puzzle 11: The Last Laugh). A lot of this kinds of confusion could've been easily avoided by having a different token for string concatenation.


See also

这篇关于为什么一个char +另一个char =一个奇怪的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆