Total Pageviews

Tuesday, 26 January 2016

What is a final modifier? Explain other Java modifiers?

A final class can’t be extended i.e. A final class may not be subclassed. A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (i.e. it is a constant).
Statics
Note: Be prepared for tricky questions on modifiers like, what is a “volatile”? Or what is a “const”? Etc. The reason it is tricky is that Java does have these keywords “const” and “volatile” as reserved, which means you can’t name your variables with these names but modifier “const” is not yet added in the language and the modifier “volatile” is very rarely used.
The “volatile” modifier is used on member variables that may be modified simultaneously by other threads. Since other threads cannot see local variables, there is no need to mark local variables as volatile. E.g. volatile int number; volatile private List listItems = null; etc. The modifier volatile only synchronizes the variable marked as volatile whereas “synchronized” modifier synchronizes all variables.
Java uses the final modifier to declare constants. A final variable or constant declared as “final” has a value that is immutable and cannot be modified to refer to any other objects other than one it was initialized to refer to. So the “final” modifier applies only to the value of the variable itself, and not to the object referenced by the variable. This is where the “const” modifier can come in very useful if added to the Java language. A reference variable or a constant marked as “const” refers to an immutable object that cannot be modified. The reference variable itself can be modified, if it is not marked as “final”. The “const” modifier will be applicable only to non-primitive types. The primitive types should continue to use the modifier “final”.

What is serialization? How would you exclude a field of a class from serialization or what is a transient variable? What is the common use?

Serialization is a process of reading or writing an object. It is a process of saving an object’s state to a sequence of bytes, as well as a process of rebuilding those bytes back into a live object at some future time. An object is marked serializable by implementing the java.io.Serializable interface, which is only a marker interface -- it simply allows the serialization mechanism to verify that the class can be persisted, typically to a file.
Serial
Transient variables cannot be serialized. The fields marked transient in a serializable object will not be transmitted in the byte stream. An example would be a file handle or a database connection. Such objects are only meaningful locally. So they should be marked as transient in a serializable class. 
Serialization can adversely affect performance since it:
  • Depends on reflection.
  • Has an incredibly verbose data format.
  • Is very easy to send surplus data.
When to use serialization? Do not use serialization if you do not have to. A common use of serialization is to use it to send an object over the network or if the state of an object needs to be persisted to a flat file or a database. Deep cloning or copy can be achieved through serialization. This may be fast to code but will have performance implications.
The objects stored in an HTTP session should be serializable to support in-memory replication of sessions to achieve scalability . Objects are passed in RMI (Remote Method Invocation) across network using serialization.

What is the main difference between a String and a StringBuffer class?

String
String is immutable: you can’t modify a string object but can replace it by creating a new
instance. Creating a new instance is rather expensive.
//Inefficient version using immutable String
String output = “Some text”
Int count = 100;
for(int I =0; i<count; i++) {
output += i;
}
return output;
The above code would build 99 new String objects, of which 98 would be thrown away immediately. Creating new objects is not efficient.
StringBuffer / StringBuilder
StringBuffer is mutable: use StringBuffer or StringBuilder when you want to modify the contents. StringBuilder was added in Java 5 and it is identical in all respects to StringBuffer except that it is not synchronised, which makes it slightly faster at the cost of not being thread-safe.
//More efficient version using mutable StringBuffer
StringBuffer output = new StringBuffer(110);
Output.append(“Some text”);
for(int I =0; i<count; i++) {
output.append(i);
}
return output.toString();
The above code creates only two new objects, the StringBuffer and the final String that is returned. StringBuffer expands as needed, which is costly however, so it would be better to initilise the StringBuffer with the correct size from the start as shown.
Another important point is that creation of extra strings is not limited to ‘overloaded mathematical operators’ (“+”) but there are several methods like concat(), trim(), substring(), and replace() in String classes that generate new string instances. So use StringBuffer or StringBuilder for computation intensive operations, which offer better performance.

What are the benefits of the Java collection framework?

Collection framework provides flexibility, performance, and robustness.
  • ô€‚ƒPolymorphic algorithms – sorting, shuffling, reversing, binary search etc.
  • Set algebra - such as finding subsets, intersections, and unions between objects.
  • Performance - collections have much better performance compared to the older Vector and Hashtable classes with the elimination of synchronization overheads.
  • Thread-safety - when synchronization is required, wrapper implementations are provided for temporarily synchronizing existing collection objects.
  • Immutability - when immutability is required wrapper implementations are provided for making a collection immutable.
  • Extensibility - interfaces and abstract classes provide an excellent starting point for adding functionality and features to create specialized object collections.

When is a method said to be overloaded and when is a method said to be overridden?

Method Overloading
Overloading deals with multiple methods in the same class with the same name but different method signatures.
class MyClass {
    public void getInvestAmount(int rate) {…}
    public void getInvestAmount(int rate, long principal)
    { … }
}
Both the above methods have the same method names but different method signatures, which mean the methods are overloaded.
Overloading lets you define the same operation in different ways for different data.
Method Overriding
Overriding deals with two methods, one in the parent class and the other one in the child class and has the same name and signatures.
class BaseClass{
    public void getInvestAmount(int rate) {…}
}
class MyClass extends BaseClass {
    public void getInvestAmount(int rate) { …}
}
Both the above methods have the same method names and the signatures but the method in the subclass MyClass overrides the method in the superclass BaseClass.
Overriding lets you define the same operation in different ways for different object types.

Why there are some interfaces with no defined methods (i.e. marker interfaces) in Java?

The interfaces with no defined methods act like markers. They just tell the compiler that the objects of the classes implementing the interfaces with no defined methods need to be treated differently. Example Serializable , Cloneable etc

What is the difference between an abstract class and an interface and when should you use them?

What is the difference between an abstract class and an interface and when should you use them?
In design, you want the base class to present only an interface for its derived classes. This means, you don’t want anyone to actually instantiate an object of the base class. You only want to upcast to it (implicit upcasting, which gives you polymorphic behaviour), so that its interface can be used. This is accomplished by making that class abstract using the abstract keyword. If anyone tries to make an object of an abstract class, the compiler prevents it.
The interface keyword takes this concept of an abstract class a step further by preventing any method or function implementation at all. You can only declare a method or function but not provide the implementation. The class, which is implementing the interface, should provide the actual implementation. The interface is a very useful and commonly used aspect in OO design, as it provides the separation of interface and implementation and enables you to:
  • Capture similarities among unrelated classes without artificially forcing a class relationship.
  • Declare methods that one or more classes are expected to implement.
  • Reveal an object's programming interface without revealing its actual implementation.
  • ô€‚ƒ Model multiple interface inheritance in Java, which provides some of the benefits of full on multiple inheritances, a feature that some object-oriented languages support that allow a class to have more than one superclass.
diamond
Abstract class
  • Have executable methods and abstract methods.
  • Can only subclass one abstract class.
  • Can have instance variables, constructors and any visibility: public, private, protected, none (aka package).
Interface
  • Have no implementation code. All methods are abstract.
  • A class can implement any number of interfaces.
  • Cannot have instance variables, constructors and can have only public and none (aka package) visibility.
When to use an abstract class?: In case where you want to use implementation inheritance then it is usually provided by an abstract base class. Abstract classes are excellent candidates inside of application frameworks. Abstract classes let you define some default behaviour and force subclasses to provide any specific behaviour. Care should be taken not to overuse implementation inheritance.
When to use an interface?: For polymorphic interface inheritance, where the client wants to only deal with a type and does not care about the actual implementation use interfaces. If you need to change your design frequently, you should prefer using interface to abstract. CO Coding to an interface reduces coupling and interface inheritance can achieve code reuse with the help of object composition. Another justification for using interfaces is that they solve the ‘diamond problem’ of traditional multiple inheritance as shown in the figure. Java does not support multiple inheritances. Java only supports multiple interface inheritance. Interface will solve all the ambiguities caused by this ‘diamond problem’.

Monday, 25 January 2016

What is design by contract? Explain the assertion construct?

Q. What is design by contract? Explain the assertion construct? 
Ans : Design by contract specifies the obligations of a calling-method and called-method to each other. Design by contract is a valuable technique, which should be used to build well-defined interfaces. The strength of this programming methodology is that it gets the programmer to think clearly about what a function does, what pre and post conditions it must adhere to and also it provides documentation for the caller. Java uses the assert statement to implement pre- and post-conditions. Java’s exceptions handling also support design by contract especially checked exceptions. In design by contract in addition to specifying programming code to carrying out intended operations of a method the programmer also specifies:
1. Preconditions – This is the part of the contract the calling-method must agree to. Preconditions specify the conditions that must be true before a called method can execute. Preconditions involve the system state and the arguments passed into the method at the time of its invocation. If a precondition fails then there is a bug in the calling-method or calling software component.
On public methods
Preconditions on public methods are enforced by explicit checks that throw particular, specified exceptions. You should not use assertion to check the parameters of the public methods but can use for the non-public methods. Assert is inappropriate because the method guarantees that it will always enforce the argument checks. It must check its arguments whether or not assertions are enabled. Further, assert construct does not throw an exception of a specified type. It can throw only an AssertionError.
public void setRate(int rate) {
    if(rate <= 0 || rate > MAX_RATE){
         throw new IllegalArgumentException(“Invalid rate ô€ƒ† ” + rate);
    }
    setCalculatedRate(rate);
}
On non-public methods
You can use assertion to check the parameters of the non-public methods.
private void setCalculatedRate(int rate) {
    assert (rate > 0 && rate < MAX_RATE) : rate;
    //calculate the rate and set it.
}
Assertions can be disabled, so programs must not assume that assert construct will be always executed: 
//Wrong: if assertion is disabled, CarpenterJob never Get removed
assert jobsAd.remove(PilotJob);
//Correct:
boolean pilotJobRemoved = jobsAd.remove(PilotJob);
assert pilotJobRemoved;
2. Postconditions – This is the part of the contract the called-method agrees to. What must be true after a method completes successfully. Postconditions can be used with assertions in both public and non-public methods. The postconditions involve the old system state, the new system state, the method arguments and the method’s return value. If a postcondition fails then there is a bug in the called-method or called software
component.
public double calcRate(int rate) {
    if(rate <= 0 || rate > MAX_RATE){
        throw new IllegalArgumentException(“Invalid rate !!! ”);
    }
    //logic to calculate the rate and set it goes here
    assert this.evaluate(result) < 0 : this; //this ô€ƒ† message sent to AssertionError on failure
    return result;
}
3. Class invariants - what must be true about each instance of a class? A class invariant as an internal invariant that can specify the relationships among multiple attributes, and should be true before and after any method completes. If an invariant fails then there could be a bug in either calling-method or called-method. There is no particular mechanism for checking invariants but it is convenient to combine all the expressions required for checking invariants into a single internal method that can be called by assertions. For example if you have a class, which deals with negative integers then you define the isNegative() convenient internal method:
class NegativeInteger {
    Integer value = new Integer (-1); //invariant
    //constructor
    public NegativeInteger(Integer int) {
        //constructor logic goes here
        assert isNegative();
    }
   //rest of the public and non-public methods goes here. public methods should call              assert isNegative(); prior to its return
   //convenient internal method for checking invariants. Returns true if the integer value      is negative
   private boolean isNegative(){
       return value.intValue() < 0 ;
   }
}
The isNegative() method should be true before and after any method completes, each public method and constructor should contain the following assert statement immediately prior to its return.
assert isNegative();
Explain the assertion construct? The assertion statements have two forms as shown below:
assert Expression1; assert Expression1 : Expression2;

Where:
Expression1 ô€ƒ† is a boolean expression. If the Expression1 evaluates to false, it throws an AssertionError without any detailed message.
Expression2 ô€ƒ† if the Expression1 evaluates to false throws an AssertionError with using the value of the Expression2 as the errors’ detailed message.
Note: If you are using assertions (available from JDK1.4 onwards), you should supply the JVM argument to enable it by package name or class name.
Java -ea[:packagename...|:classname] or Java -enableassertions [:packagename ... |:classname]
Java –ea:Account

How do you express an ‘is a’ relationship and a ‘has a’ relationship or explain inheritance and composition? What is the difference between composition and aggregation?

Q. How do you express an ‘is a’ relationship and a ‘has a’ relationship or explain inheritance and composition? What is the difference between composition and aggregation? DC
Ans. The ‘is a’ relationship is expressed with inheritance and ‘has a’ relationship is expressed with composition. Both inheritance and composition allow you to place sub-objects inside your new class. Two of the main techniques for code reuse are class inheritance and object composition.
inheritance_1
Inheritance is uni-directional. For example House is a Building. But Building is not a House. Inheritance uses extends key word. Composition: is used when House has a Bathroom. It is incorrect to say House is a Bathroom. Composition simply means using instance variables that refer to other objects. The class House will have an instance variable, which refers to a Bathroom object.
Which one to use? The guide is that inheritance should be only used when subclass ‘is a’ superclass.
  • Don’t use inheritance just to get code reuse. If there is no ‘is a’ relationship then use composition for code reuse. Overuse of implementation inheritance (uses the “extends” key word) can break all the subclasses, if the superclass is modified.
  • Do not use inheritance just to get polymorphism. If there is no ‘is a’ relationship and all you want is polymorphism then use interface inheritance with composition, which gives you code reuse.
What is the difference between aggregation and composition?
Aggregation Aggregation is an association in which one class belongs to a collection. This is a part of a whole relationship where a part can exist without a whole. For example a line item is a whole and product is a part. If a line item is deleted then corresponding product need not be deleted. So aggregation has a weaker relationship.
Composition 
Composition is an association in which one class belongs to a collection. This is a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted. For example An order is a whole and line items are parts. If an order deleted then all corresponding line items for that order should be deleted. So composition has a stronger relationship.

Explain static vs. dynamic class loading?

Static class loading
1.Classes are statically loaded with Java’s “new” operator.
class MyClass {
    public static void main(String args[]) {
        Car c = new Car();
    }
}
2. A NoClassDefFoundException is thrown if a class is referenced with Java’s “new” operator (i.e. static loading) but the run time system cannot find the referenced class.
Dynamic class loading
Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. Let us look at how to load classes dynamically.
Class.forName (String className); //static method which returns a Class
The above static method returns the class object associated with the class name. The string className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other runtime conditions. Once the class is dynamically loaded the following method returns an instance of the loaded class. It’s just like creating a class object with no arguments.
class.newInstance (); //A non-static method, which creates an instance of a class (i.e. creates an object).
Jeep myJeep = null ;
//myClassName should be read from a properties file or Constants interface. //stay away //from hard coding values in your program. 
String myClassName = "au.com.Jeep" ;
Class vehicleClass = Class.forName(myClassName) ;
myJeep = (Jeep) vehicleClass.newInstance();
myJeep.setFuelCapacity(50);
ClassNotFoundException is thrown when an application tries to load in a class through its string name using the following methods but no definition for the class with the specified name could be found:
  1. 􀂃 The forName(..) method in class - Class.
  2. 􀂃 The findSystemClass(..) method in class - ClassLoader.
  3. 􀂃 The loadClass(..) method in class - ClassLoader.
What are “static initializers” or “static blocks with no function names”? When a class is loaded, all blocks that are declared static and don’t have function name (i.e. static initializers) are executed even before the constructors are executed. As the name suggests they are typically used to initialize static fields.
public class StaticInitilaizer {
    public static final int A = 5;
    public static final int B;
    //Static initializer block, which is executed only once when the class is loaded.
    static {
        if(A == 5)
            B = 10;
        else
            B = 5;
    }
    public StaticInitilaizer(){} // constructor is called only after static initializer block
}
The following code gives an Output of A=5, B=10.
public class Test {
    System.out.println("A =" + StaticInitilaizer.A + ", B =" + StaticInitilaizer.B);
}

Explain Java class loaders? Explain dynamic class loading?

Q. Explain Java class loaders? Explain dynamic class loading?
Answer : Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So how is the very first class loaded? The very first class is specially loaded with the help of static main() method declared in your class.All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.
class loader1
Class Loader2
Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true as explained in the above diagram.
Important: Two objects loaded by different class loaders are never equal even if they carry the same values, which mean a class is uniquely identified in the context of the associated class loader. This applies to singletons too, where each class loader will have its own singleton.

Sunday, 24 January 2016

CREATING JSPS WITH THE EXPRESSION LANGUAGE (EL)

Q.1 Consider the following code:
<html><body>
    ${(5 + 3 + a > 0) ? 1 : 2}
</body></html>
Select the correct statement from the options below:
a. It will print 1 because the statement is valid.
b. It will print 2 because the statement is valid.
c. It will throw an exception because a is undefined.
d. It will throw an exception because the expression’s syntax is invalid.
Answer: a Explanation
Using a letter in an EL statement is valid, and so is the statement’s syntax. So answers c and d are incorrect. Since the condition evaluates to true, the first of the two results will be displayed, and a is the correct answer.
Q.2 Which statement best expresses the purpose of a tag library descriptor (TLD) in an EL function?
a. It contains the Java code that will be compiled.
b. It invokes the Java method as part of the JSP.
c. It matches the tag library with a URI.
d. It matches function names to tags that can be used in the JSP.
Answer: d Explanation
The web.xml file matches tag libraries with URIs, so answer c is incorrect. Java code is contained in a .java file and methods are invoked from within a JSP (.jsp). Thus, answers a and b are incorrect. A tag library descriptor (.tld) matches function names with names that can be used in JSPs, so answer d is correct. To be more specific, it matches a Java method signature with a class name for use in JSPs.
Q.3 Which of the following variables is not available for use in EL expressions?
a. param
b. cookie
c. header
d. pageContext
e. contextScope
Answer: e Explanation
These implicit variables are similar to others used in JSPs. The param, header, and cookie variables access the same objects as those used in request/response access. The pageContext variable provides access to scope variables. So answers a through d are incorrect. But there’s no such thing as a contextS.
Q.4 Which tags tell the web container where to find your TLD file in your filesystem?
a. <taglib-directory></taglib-directory>
b. <taglib-uri></taglib-uri>
c. <taglib-location></taglib-location>
d. <tld-directory></tld-directory>
e. <taglib-name></taglib-name>
Answer: c Explanation
The <taglib-name> and <taglib-uri> elements provide the library’s name and URI, but not its place in filesystem, so b and e are incorrect. There are no <taglib-directory> or <tld-directory tags>, which means answers a and d are incorrect. The <taglib-location> elements specify the directory containing the TLD, starting with /WEB-INF/. Therefore, the answer is c.
Q.5 Which two of the following expressions won’t return the header’s accept field?
a. ${header.accept}
b. ${header[accept]}
c. ${header['accept']}
d. ${header["accept"]}
e. ${header.'accept'}
Answers: b and e Explanation
EL arrays can contain strings as long as they are surrounded by single or double quotes. So c and d will return the accept field, and b won’t. Similarly, the EL property operator (.) can contain a string as long as it isn’t surrounded by quotes. So a will return a value and e will cause an error.
6. When writing a TLD, which tags would you use to surround fnName(int num), a Java method declared in a separate class? 
a. <function-signature></function-signature>
b. <function-name></function-name>
c. <method-class></method-class>
d. <method-signature></method-signature>
e. <function-class></function-class>
Answer: a Explanation
Since EL describes these structures as functions, c and d are incorrect. Also, the function’s
name is contained in <name> tags, not <function-name>, so b is incorrect. Since <function-signature> declares the Java method, a is the correct answer.
Q.7 Which of the following method signatures is usable in EL functions? a public static expFun(void)
b. expFun(void)
c. private expFun(void)
d. public expFun(void)
e. public native expFun(void)
Answer: a Explanation
EL functions must refer to methods with modifiers of public and static. Therefore, a is the only acceptable answer. Similarly, the class containing the method must be public.

REUSABLE WEB COMPONENTS

Q.1 Which of the following JSP tags can be used to include the output of another JSP page into the output of the current page at request time? (Select one)
a. <jsp:insert>
b. <jsp:include>
c. <jsp:directive.include>
d. <jsp:directive:include>
e. <%@ include %>
Answer: b Explanation
The tags in answers a and d are not valid JSP tags. Answers c and e are valid tags in XML syntax and JSP syntax, respectively, but they are directives and include other JSP pages or HTML/XML files at translation time. Answer b is the right answer because it includes the output of another component, JSP page, or Servlet at request time.
Q.2 Consider the contents of the following two JSP files: File 1: test1.jsp
<html><body>
    <% String message = "Hello"; %>
    //1 Insert LOC here.
    The message is <%= message %>
</body></html>
File 2: test2.jsp
    <% message = message + " world!"; %>
Which of the following lines can be inserted at //1 in test1.jsp so that it prints "The message is Hello world!" when requested? (Select one)
a <%@ include page="test2.jsp" %>
b <%@ include file="test2.jsp" />
c <jsp:include page="test2.jsp" />
d <jsp:include file="test2.jsp" />
Answer: b Explanation
Since the test2.jsp file does not declare or define the variable message, it cannot compile on its own. This rules out dynamic inclusion using the <jsp:include> action. The file test1.jsp could print "Hello world" if it statically included test2.jsp. This could be done using the include directive: <%@ include %>. For the include directive, the valid attribute is file and not page, so answer b is correct.
Q.3 Which of the following is a correct way to pass a parameter equivalent to the query string user=mary at request time to an included component? (Select one)
a. <jsp:include page="other.jsp" >
       <jsp:param paramName="user" paramValue="mary" />
   </jsp:include>
b. <jsp:include page="other.jsp" >
       <jsp:param name="mary" value="user" />
   </jsp:include>
c. <jsp:include page="other.jsp" >
       <jsp:param value="mary" name="user" />
   </jsp:include>
d. <jsp:include page="other.jsp" >
       <jsp:param param="user" value="mary"/>
   </jsp:include>
e. <jsp:include page="other.jsp" >
       <jsp:param user="mary" />
   </jsp:include>
Answer: c Explanation
The only valid attributes that a <jsp:param> tag can have are name and value. This rules out answers a, d, and e. Answer b, <jsp:param name="mary" value="user" />, is equivalent to the query string mary=user. In the included component, a call to request.getParameter("mary"); will return "user". Answer c, <jsp:param value="mary" name="user" />, is equivalent to the query string user=mary. In the included component, a call to request.getParameter("user"); will return "mary". Therefore, answer c is the correct answer.
Q.4 Identify the JSP equivalent of the following code written in a servlet. (Select one)
RequestDispatcher rd = request.getRequestDispatcher("world.jsp");
rd.forward(request, response);
a. <jsp:forward page="world.jsp"/>
b. <jsp:action.forward page="world.jsp"/>
c. <jsp:directive.forward page="world.jsp"/>
d. <%@ forward file="world.jsp"%>
e. <%@ forward page="world.jsp"%>
Answer: a Explanation
The action tags in answers b through e are all invalid JSP tags. Answer a, <jsp:forward page="relativeURL" />, is the only valid way to write a forward action.
Q.5 Consider the contents of two JSP files:
File 1: test1.jsp
<html><body>
    <% pageContext.setAttribute("ninetyNine", new Integer(99)); %>
    //1
</body></html>
File 2: test2.jsp
The number is <%= pageContext.getAttribute("ninetyNine") %>
Which of the following, when placed at line //1 in the test1.jsp file, will allow the test2.jsp file to print the value of the attribute when test1.jsp is requested? (Select one)
a. <jsp:include page="test2.jsp" />
b. <jsp:forward page="test2.jsp" />
c. <%@ include file="test2.jsp" %>
d. None of the above because objects placed in pageContext have the page scope and cannot be shared with other components.
Answer: c Explanation
Objects placed in pageContext have the page scope and are accessible within a single translation unit. Since files included statically using the include directive become an integral part of the same translation unit as the including file, they can share objects in the page scope via the PageContext container. So the correct answer is c: <%@ include file="test2.jsp" %>.
Q.6 Consider the contents of two JSP files:
File 1: this.jsp
<html><body><pre>
    <jsp:include page="that.jsp" >
    <jsp:param name="color" value="red" />
    <jsp:param name="color" value="green" />
    </jsp:include>
</pre></body></html>
File 2: that.jsp
<%
    String colors[] = request.getParameterValues("color");
    for (int i=0; i<colors.length; i++) {
        out.print(colors[i] + " ");
    }
%>
What will be the output of accessing the this.jsp file via the following URL? (Select one)
http://localhost:8080/chapter12/this.jsp?color=blue
a. blue
b. red green
c. red green blue
d. blue red green
e. blue green red
Answer: c Explanation
The parameters passed via the <jsp:param> tag to an included component tag take precedence over the parameters already present in the request object of the including component. Also, the order of values passed via the <jsp:param> tag is the same as the order in which the tags appear. Thus, the correct answer is c. The output will be red green blue.
Q.7 Consider the contents of two JSP files:
File 1: this.jsp
<html><body>
    <%= request.getParameter("color") %>
    <jsp:include page="that.jsp" >
        <jsp:param name="color" value="red" />
    </jsp:include><%= request.getParameter("color") %>
</body></html>
File 2: that.jsp
<%= request.getParameter("color") %>
What will be the output of accessing the this.jsp file via the following URL? (Select one)
http://localhost:8080/chapter12/this.jsp?color=blue
a. blue red blue
b. blue red red
c. blue blue red
d. blue red null
Answer: a Explanation
The first call to request.getParameter("color") in the this.jsp file returns blue. This file then includes the that.jsp file and passes a value of red for the color attribute. Since the values passed via <jsp:param> take precedence over the original values, a call to request.getParameter("color") in that.jsp returns red. However, this new value exists and is available only within the included component—that is, that.jsp. So, after the that.jsp page finishes processing, a call to request.getParameter("color") in the this.jsp file again returns blue. Thus, the correct answer is a. The output will be blue red blue.
Q.8 Consider the contents of three JSP files:
File 1: one.jsp
<html><body><pre>
    <jsp:include page="two.jsp" >
        <jsp:param name="color" value="red" />
    </jsp:include>
</pre></body></html>
File 2: two.jsp
<jsp:include page="three.jsp" >
    <jsp:param name="color" value="green" />
</jsp:include>
File 3: three.jsp
<%= request.getParameter("color") %>
What will be the output of accessing the one.jsp file via the following URL? (Select one)
http://localhost:8080/chapter12/one.jsp?color=blue
a. red
b. green
c. blue
d. The answer cannot be determined.
Answer: b Explanation
The output is generated by the three.jsp file. Since the two.jsp file calls three.jsp and provides a value of green, this value takes precedence over all the previous values passed to one.jsp and two.jsp. Thus, the correct answer is b. The output will be green.