Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assertions

 
Harikrishna Gorrepati
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Stephan van Hulst
Bartender
Pie
Posts: 5589
54
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Sven Mathijssen
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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."
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic