• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Assertions

 
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Saloon Keeper
Posts: 15510
363
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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".
 
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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."
 
reply
    Bookmark Topic Watch Topic
  • New Topic