Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

javaPrepare -question

 
Sandya Bhaskara
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What gets printed when the following JSP code is invoked in a browser. Select the one correct answer.
<%= if(Math.random() < 0.5) %>
hello
<%= } else { %>
hi
<%= } %>


a.The browser will print either hello or hi based upon the return value of random.
b.The string hello will always get printed.
c.The string hi will always get printed.
d.The JSP file will not compile.

The answer was d...but i think it should give the following O/P...
if(Math.random()<5hello}else{hi}
am i wrong?
 
Roger Yates
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given the code:

I'd certainly say it wouldn't compile - there are a few things wrong with it.
1. It looks like an attempt to write script, but <%= is used for expressions and as each line is terminated with %> then each will be evaluated separately.
The result of "if(Math.random() < 0.5)" does not evaluate to anything printable, as there is no 'action' part of the if statement within the expression (stuff enclosed between <%= and %> ). As there is no action part, it would not compile. Neither would the other two script expression lines.
If you replaced the <%= with <%, the page would almost compile - but you'd need to add an opening '{' to the end line with the 'if' on it.
But then you'd still have a problem, since only the bits between the <% %> would be compiled. It's getting messy to take this further...: No - it wouldn't compile!

------------------------------------------------
Here's the output you get from Tomcat:
org.apache.jasper.JasperException: Unable to compile class for JSP

An error occurred at line: 8 in the jsp file: /test.jsp
Generated servlet error:
C:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\Beer-v1\org\apache\jsp\test_jsp.java:50: illegal start of expression
out.print( if(Math.random() < 0.5) );
^

An error occurred at line: 8 in the jsp file: /test.jsp
Generated servlet error:
C:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\Beer-v1\org\apache\jsp\test_jsp.java:50: ')' expected
out.print( if(Math.random() < 0.5) );
^

An error occurred at line: 10 in the jsp file: /test.jsp
Generated servlet error:
C:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\Beer-v1\org\apache\jsp\test_jsp.java:53: illegal start of expression
out.print( } else { );
^

[ October 11, 2004: Message edited by: Roger Yates ]
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic