java语言基础(11)——字符数据与字符串数据参与运算
原创
©著作权归作者所有:来自51CTO博客作者梧桐深院的原创作品,请联系作者获取转载授权,否则将追究法律责任
在java中,单引号里的内容是字符,且只能是单个字符,比如 'a' 'b' 而不能是 'ab'。双引号里的内容是字符串,可以有多个内容,如 "hello world"。
字符参与运算:
class CharPlus
{
public static void main(String[] args){
System.out.println('a'); // a
System.out.println('a'+1); // 98
}
}
前面我们说过,byte short char 类型的数据在参与运算时,会先转换为int类型。而字符转换为int类型,对应于ASCII表中的数字。对应关系为:'a' -> 97 'A' -> 65 '0'->48
字符串参与运算:
class StringPlus
{
public static void main(String[] args){
System.out.println("hello"+'a'+1); // helloa1
System.out.println('a'+1+"hello"); // 98hello
System.out.println("5+5="+5+5); // 5+5=55
System.out.println(5+5+"=5+5"); // 10=5+5
}
}
字符串在与其它类型的数据运算时,'+'不是加法运算,而是字符串拼接符。结果是字符串类型。而 'a'+1+"hello" 和 5+5+"=5+5"实例中,因为运算顺序是从左到右的,先进行了数值运算,再进行字符串拼接。