简体   繁体   English

将参数变量从int转换为char,反之亦然

[英]Casting Parameter Variables from int to char and vice-versa

If I pass a char as a parameter when calling stuff, will it compile? 如果在调用stuff时将char作为参数传递,它将编译吗? Will passing an int instead of a char work too? 传递int而不是char也会起作用吗? I know you can cast from int to char but shouldn't it be explicit? 我知道您可以将类型从int转换为char,但这不应该明确吗?

I have a class Test with one static method of return type String with char a and int x as parameters. 我有一个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'));
    }
}

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

Up-casting(implicit)- 向上投射(隐式)-

byte –> short –> int –> long –> float –> double 字节–>短–>整数–>长–>浮点–>双精度

Down-casting(Explicit)- 向下转换(明确)-

double –> float –> long –> int–> short–> byte double –>浮点–> long –> int–> short–>字节

int takes 4 bytes of memory and char takes 2 bytes of memory, so requires explicit casting. int占用4个字节的内存,而char占用2个字节的内存,因此需要显式转换。 int can take negative values and char takes only positive values. 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");

       }
     } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM