输出有不同的数据类型?

时间:2017-06-26 09:27:01

标签: java types

我为了好玩而编写了一些东西,发现了一些令人困惑的东西。

我首先编写类似这样的代码。

public class Testing(){
  public static void main(String args[]){
     int a=1;
     char b='A';
     System.out.print('A'+a);
        }
}

输出是66?

然后我像这样修改第二个代码。

public class Testing(){
      public static void main(String args[]){
         int a=1;
         char b='A';
         System.out.print((char)('A'+a));
            }
    }

第二个代码的输出是B.

有人可以帮我解释这里发生的事情。

谢谢!

4 个答案:

答案 0 :(得分:0)

当你做

 System.out.print('A'+a);

' A'将被用作数字(实际上是一个截断的整数),结果将表示为数字......

当你这样做时:

 System.out.print((char)('A'+a));

你将它转换成一个char,所以结果将是ascii中映射到66的结果

答案 1 :(得分:0)

当您添加charint时(如'A'+a中所述),char会提升为int,结果为int

因此,第一个代码段会打印int

在第二个代码段中,您将int投放到char,因此会显示'B'值为int的字符66

您的两个代码段调用PrintStream的不同方法 - 第一个将int转换为String,第二个将char转换为String

/**
 * Prints an integer.  The string produced by <code>{@link
 * java.lang.String#valueOf(int)}</code> is translated into bytes
 * according to the platform's default character encoding, and these bytes
 * are written in exactly the manner of the
 * <code>{@link #write(int)}</code> method.
 *
 * @param      i   The <code>int</code> to be printed
 * @see        java.lang.Integer#toString(int)
 */
public void print(int i) {
    write(String.valueOf(i));
}

/**
 * Prints a character.  The character is translated into one or more bytes
 * according to the platform's default character encoding, and these bytes
 * are written in exactly the manner of the
 * <code>{@link #write(int)}</code> method.
 *
 * @param      c   The <code>char</code> to be printed
 */
public void print(char c) {
    write(String.valueOf(c));
}

答案 2 :(得分:0)

在内部,char是映射到字符符号的整数值。这就是你可以将它添加到int的原因。如果告诉Java将结果作为char处理,则会得到一个char。

答案 3 :(得分:0)

'A'+a的情况下,操作被视为整数加法,并且char转换为其等效的ASCII编号。因此结果是整数。

如果情况2发生了相同的事情,并且最终输出从您的ASCII转换为char,那么

相关问题