【问题标题】:Casting Parameter Variables from int to char and vice-versa将参数变量从 int 转换为 char,反之亦然
【发布时间】:2014-05-01 05:02:29
【问题描述】:

如果我在调用东西时传递一个 char 作为参数,它会编译吗?传递一个 int 而不是一个 char 也可以吗?我知道你可以从 int 转换为 char 但它不应该是明确的吗?

我有一个 Test 类,它有一个返回类型为 String 的静态方法,以 char a 和 int x 作为参数。

public class Test {
    public static String stuff(char a, int x)
    {
        char b = (char)x; String s = "";
        while (a<b)
        s+=a+b--;
        return s;
    }
    public static void main(String args[])
    {
         System.out.println(stuff('a','d'));
    }
}

【问题讨论】:

  • char 最多可以占用 255
  • 是的,它会编译。
  • 为什么可以将 char 作为 int 传递?传递 'd' 而不是 int。
  • 因为 char 最多可以支持 255,超过该值它将不支持并且编译器会抱怨精度损失
  • 为什么不需要你显式地转换它

标签: java parameters casting char int


【解决方案1】:

向上转换(隐式)-

byte –> short –> int –> long –> float –> double

向下转换(显式)-

double –> float –> long –> int–> short–> byte

int 占用 4 个字节的内存,而 char 占用 2 个字节的内存,因此需要显式转换。 int 可以取负值,char 只能取正值。

      public class Test {
      public static void main(String args[]) { 
      int i = 78;     // 4 bytes 
      // char ch = i;   // error, 4 bytes to 2 bytes
      char ch = (char) i; // int is type converted to char
      System.out.println(ch); // prints N (78 ASCII value for N)

      System.out.println("Max int:"+Integer.SIZE+"bit");
      System.out.println("Max char:"+Character.SIZE+"bit");

       }
     } 

【讨论】:

    【解决方案2】:

    是的,传递一个字符是合法的,但不是好的做法。

    【讨论】:

      猜你喜欢
      • 2020-03-01
      • 2021-06-10
      • 2011-05-16
      • 2014-01-23
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      相关资源
      最近更新 更多