Typecasting of the variables | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Typecasting of the variables

typecasting means which convert the one data type into another but boolean never change into another

26th Nov 2020, 6:16 AM
Sakshi Sharma
6 Answers
+ 7
Avinesh The Python bool is a bit controversial IMO. In fact, it took over 10 years before Python eventually implemented bool as a built-in data type. The decision making details for this PEP make for an interesting read: https://www.python.org/dev/peps/pep-0285/
26th Nov 2020, 8:02 AM
David Carroll
David Carroll - avatar
+ 5
You can say that it is a design choice. A boolean value is basically a representation of a bit which is either 1 or 0. Now converting this to any other data type could raise ambiguity and be prone to errors. That is just my assumption. You can read this for understanding, also under "casting conversions" checkout the first tabulation which shows that boolean cannot be casted. https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.4
26th Nov 2020, 6:35 AM
Avinesh
Avinesh - avatar
+ 4
Sakshi Sharma In order for typecasting to work, the source and target types would need to be part of the same inheritance hierarchy or shared interfaces. In this context, which types would you expect Boolean to share in its inheritance hierarchy / common interfaces?
26th Nov 2020, 7:20 AM
David Carroll
David Carroll - avatar
+ 4
Unlike in Python where boolean type inherits from integer type, Java doesn't have this inheritance I guess. A workaround when necessary could be achieved using a ternary operator. boolean bool = true; int value = bool ? 1 : 0;
26th Nov 2020, 7:40 AM
Avinesh
Avinesh - avatar
+ 2
Why would you want to cast a boolean I'm just curious I cant think of any use for it 🤔 boolean a = true; //boolean true String b = a+""; //converted to string so now the boolean becomes an object which has methods so this casts it in a sort of way but it's not the same value as above so its converted rather then casted. int c = b.length();//string converted to int, again this is a new value being stored so it not the same as variable a or b but value can be casted to double, or wrapped inside Interger ect.. a = c==b.length(); //gets the original boolean back into the variable, again this is a new value replacing the existing value of a which cant be casted. System.out.print(a); //prints boolean true my guess is that boolean can be manipulated through other class methods so type casting isnt necessary.
26th Nov 2020, 10:25 AM
D_Stark
D_Stark - avatar
+ 1
It is optional but I see no reason to Typecast boolean
26th Nov 2020, 7:25 AM
George S Mulbah II
George S Mulbah II - avatar