wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Assertions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Assertions" Watch "Assertions" New topic
Author

Assertions

Harikrishna Gorrepati
Ranch Hand

Joined: Sep 23, 2010
Posts: 422
Hi, The following code is from Whizlabs. How can we declare 2 variables with the same variable name (assertEnabled ) as per the code given below.


OCPJP 6.0-81% | Preparing for OCWCD
http://www.certpal.com/blogs/cert-articles | http://sites.google.com/site/mostlyjava/scwcd |
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  16

It's not declared twice.

"boolean assertEnabled = false;" first declares assertEnabled as a boolean, and then assigns the value false to it.
"assert assertEnabled = true;" doesn't declare anything. It merely checks whether the boolean assertEnabled is true, which it would be, because it gets true assigned to it before the boolean is asserted.

Note that the assert statement will only be run if assertions are enabled, by running Java with the -ea option.
If you run "java Question23_Read_Ask" the program will print "Assertions are disabled".
If you run "java -ea Question23_Read_Ask", it will print "Assertions are enabled".
Trivikram Kamat
Ranch Hand

Joined: Sep 26, 2010
Posts: 155
It's a tricky question, as there is only single assignment operator:


Someone might get confused by considering it will throw Assertion Error at the above line as assertEnabled is false, when assertions are enabled.


OCPJP6
Sven Mathijssen
Greenhorn

Joined: Aug 29, 2010
Posts: 19
Stephan van Hulst wrote:
"assert assertEnabled = true;" doesn't declare anything. It merely checks whether the boolean assertEnabled is true, which it would be, because it gets true assigned to it before the boolean is asserted.


More complete would be: "[...] which it would be, as the result of an assignment expression is the value that's assigned to the variable."
 
GeeCON Prague 2014
 
subject: Assertions