function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
KeithJKeithJ 

Cannot convert String to Boolean???

Hi there. I have the following code:

 

public class TestController { public TestController() { castIt(); } private void castIt() { String s = 'TRUE'; try { Boolean b = Boolean.valueOf(s); }catch(Exception e) { System.debug('******** THERE WAS AN EXCEPTION: ' + e.getMessage()); } } }

 This will not work!

I get an exception everytime I try to do this and I can't figure out for the life of me why.

Any ideas? It seems so simple.

Thanks

 

 

Best Answer chosen by Admin (Salesforce Developers) 
JimRaeJimRae

Why are you trying to do that?  It appears that the Boolean valueOf has to do with history field values.

 

What about something like this instead:

 

 

public class TestController { public TestController() { castIt(); } private void castIt() { String s = 'TRUE'; try { Boolean b = s.equals('TRUE'); }catch(Exception e) { System.debug('******** THERE WAS AN EXCEPTION: ' + e.getMessage()); } } }

 

 

All Answers

JimRaeJimRae

Why are you trying to do that?  It appears that the Boolean valueOf has to do with history field values.

 

What about something like this instead:

 

 

public class TestController { public TestController() { castIt(); } private void castIt() { String s = 'TRUE'; try { Boolean b = s.equals('TRUE'); }catch(Exception e) { System.debug('******** THERE WAS AN EXCEPTION: ' + e.getMessage()); } } }

 

 

This was selected as the best answer
KeithJKeithJ

Thanks for that Jim.

What I was trying to do is perfectly feasible. You should be able to cast a string to a boolean.

What exactly does this method do? The apex reference states:

 

Casts x, a history tracking table field of type anyType,
to a Boolean. For more information on the anyType data
valueOf anyTypex Boolean
type, see Field Types in the Force.comWeb Services API
Developer's Guide.

 

Seems a little confusing...

Regards

JimRaeJimRae
I don't disagree with you, but it doesn't seem to work.  I believe the use case for the boolean valueof is more for history related processing where you are checking for the existance of a field value in the history tables.
fatmonkfatmonk

Try this :

string str = 'true';

boolean TrueOrFalse {get;set;}

 public void convertB(){

     TrueOrFalse = Boolean.valueOf(str);

}