-2

I have the following code:

public class MyFirstJavaProgram {
        public static void main(String []args) { 
          boolean b = true; 
          int x = b; 
          System.out.println(x);
    }
} 

As the title say, can I convert boolean type into another data type (in the above example, char), using Java?

Vito Gentile
  • 13,336
  • 9
  • 61
  • 96
Anish Rai
  • 698
  • 9
  • 16

9 Answers9

5

No you cannot.

If you are looking for a one-line solution to set your int, you can use a ternary operation, as such:

int x = b ? 1 : 0;
Mena
  • 47,782
  • 11
  • 87
  • 106
3

You can't do it directly, but you can do it on this way:

int myIntBool = (someBoolean) ? 1 : 0;

Also, you can use BooleanUtils from Apache.

BooleanUtils.toInteger(true)  = 1
BooleanUtils.toInteger(false) = 0
Michael Kazarian
  • 4,376
  • 1
  • 21
  • 25
3

You can do int x = b ? 1 : 0;.

Martin
  • 1,274
  • 12
  • 23
2

NO You use ternary operation

          int X = value ? 1: 0;
1

ternary operation will yield the result

int y = booleanvalue ? 1: 0;
Jiju Induchoodan
  • 4,236
  • 1
  • 22
  • 24
1

Boolean To int

int convertedInt=0;

if(booleanToConvert)
  convertedInt=1;

Boolean to char

char convertedChar='';

if(booleanToConvert)
  convertedChae='Y';
else
  convertedChae='N';
Ninad Pingale
  • 6,801
  • 5
  • 32
  • 55
0

you cannot directly convert but manually like so:

int x = b ? 1 : 0; //sets x to 1 if b is true, 0 otherwise

The question now is why would you want to do this?

shillner
  • 1,806
  • 15
  • 24
0

char c = Boolean.parseBoolean("true") ? '1' : '0'; would set c to 1. not quite sure if that is what you want.

nafas
  • 5,283
  • 3
  • 29
  • 57
0

boolean to int:

return booleanValue ? 1 : 0;

boolean to char:

return booleanValue ? 'Y' : 'N';

boolean to String:

return booleanValue ? "YES" : "NO";

And so on...

Binyamin Regev
  • 914
  • 5
  • 19
  • 31