If I pass a char as a parameter when calling stuff, will it compile? Will passing an int instead of a char work too? I know you can cast from int to char but shouldn't it be explicit?
I have a class Test with one static method of return type String with char a and int x as parameters.
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
int takes 4 bytes of memory and char takes 2 bytes of memory, so requires explicit casting. int can take negative values and char takes only positive values.
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");
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments