Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

K&B Page 814 Q7 Regarding Assertions in Java

 
Peter Swiss
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the question



Which sets of commands will compile and run without exception or error?

A. javac Antique.java
java Antique
B. javac Antique.java
java -ea Antique
C. javac -source 6 Antique.java
java Antique
D. javac -source 1.4 Antique.java
java Antique
E. javac -source 1.6 Antique.java
java -ea Antique


Answer says A and C are correct.
A is obvious.
What is the difference between C and D? Since Assertions were added to Java 1.4, options C and D are the same. So even D should be correct.

Please reply.

Thank you.
 
Vijay keshava
Ranch Hand
Posts: 40
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
D would have been correct, if instead of List<String> myList = new ArrayList<String>(); we had List myList = new ArrayList(); Generics were introduced only in java 1.5. The question is tricky, since you are focusing on assertion, but the catch is with usage of generics
 
Peter Swiss
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh, yes!! LOL that was good!
Thanks Vijay!
 
Glen Iris
Ranch Hand
Posts: 172
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is B wrong? - I guess assertions are enabled by default but what is wrong with explicitly enabling them too?

Why is E wrong?
 
Helen Ma
Ranch Hand
Posts: 451
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose, we are using Java 6 to compile.
B and E will compile, but it will throw the error as there is no argument from the command-Line.
assert (args.length>0) will be false and print an AssertionError message.
 
Glen Iris
Ranch Hand
Posts: 172
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you helen
 
dennis deems
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Glen Iris wrote:Why is B wrong? - I guess assertions are enabled by default but what is wrong with explicitly enabling them too?

Assertions are disabled by default. That's why A works. The line that would cause an AssertionError is ignored unless assertions are explicitly enabled.
 
Glen Iris
Ranch Hand
Posts: 172
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Dennis. I had figured that out in the mean time but its always good to have a solid Java person back up my assumptions.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic