public class Typecast {
public static void main(String[] args) {
int a=0;
boolean b=(boolean)a;
System.out.println(b);
}
}
It gives me an error "Cannot cast from int to boolean".Can someone help?
public class Typecast {
public static void main(String[] args) {
int a=0;
boolean b=(boolean)a;
System.out.println(b);
}
}
It gives me an error "Cannot cast from int to boolean".Can someone help?
You can't cast an int to a boolean; but you can compare that int to another number, and that comparison expression will be of boolean type, for example:
boolean b = (a != 0);
Not every type can be cast to another. int to boolean is one of those that is not permitted in Java. The Java Language Specification explains what is and what isn't possible.
A Boolean value is one with two choices- true or false, yes or no, 1 or 0.
Boolean can't be type casted into any other data type.
What is your train of thought here? What are you trying to do exactly?
Are you thinking that 0 would cast to false and 1 would cast to true like in binary? As others mentioned an integer is a numeric data type and can only be cast to other numericals.
It can also be converted to a string using wrapper classes. Ie: String str = Integer.toString(a)
If you are trying to convert 0s to booleans, try this line of code to replace your line3:
b = (a != 0);
If you
You cannot cast an integer to boolean in java. int is primitive type which has value within the range -2,147,483,648 to 2,147,483,647 whereas boolean has either true or false. So casting a number to boolean (true or false) doesn't makes sense and is not allowed in java.
You need to check the basic data types in java which will give you more clarity.