Which two code snippets allow you to insert an integer value into the session? (Choose two.)
A.int pageVisits = 47;
session.setAttribute("visits", pageVisits);
B.int pageVisits = 47;
session.setIntAttribute("visits", pageVisits);
C.int pageVisits = 47;
session.setAttribute("visits", new Integer(pageVisits));
D.int pageVisits = 47;
session.setIntAttribute("visits", new Integer(pageVisits));
Source: SAI Mock
Answer: A,C
Option A is correct; while the setAttribute method requires an Object in the second parameter,
Java SE v5 uses autoboxing to convert the int primitive to an Integer object at runtime.
Option B is incorrect because there is no setIntAttribute method.
Option C is correct.
Option D is incorrect because there is no setIntAttribute method.
this is contradicting to this question of SCWCD EXAM STUDY KIT
2. Which of the following code snippets, when inserted in the doGet() method,
will correctly count the number of GET requests made by a user? (Select one)
a HttpSession session = request.getSession();
int count = session.getAttribute("count");
session.setAttribute("count", count++);
b HttpSession session = request.getSession();
int count = (int) session.getAttribute("count");
session.setAttribute("count", count++);
c HttpSession session = request.getSession();
int count = ((Integer) session.getAttribute("count")).intValue();
session.setAttribute("count", count++);
d HttpSession session = request.getSession();
int count = ((Integer) session.getAttribute("count")).intValue();
session.setAttribute("count", new Integer(count++));
Answer: d
Explanation
Remember that the setAttribute() and getAttribute() methods only work
with objects and not with primitive data types. The getAttribute() method
returns an object and so you need to cast the returned value to the actual type
(Integer, in this case). Similarly, you need to wrap the count variable into an
Integer object and pass it to the setAttribute() method.
I tested and the first one came as correct.