Why are my longs turning into ints?
I'm working on a JSP page, but I'm running into a null pointer at run time. In an attempt to isolate the problem, I hard-coded the expected variable response instead of using a getter (it was previously action.getName(psi.getLong()) )
). Sure enough, I got an error when I tried to run the page with the raw long.
An error occurred at line: 70 in the jsp file: /auth/foo/viewBar.jsp
The literal 9000000000 of type int is out of range
70: <%long 开发者_高级运维sarah = 9000000000; %>
71: <td> <%= StringEscapeUtils.escapeHtml(""+action.getName(sarah)) %></td>
getName is defined elsewhere as follows
public String getName(long mid) throws DBException {
try {
return personnelDAO.getName(mid);
} catch (fooException e) {
e.printStackTrace();
return "exception retrieving name";
}
But judging by the above, I'd guess that the 9000000000 isn't even getting passed that far. Can .JSP not handle longs?
Furthermore, could this error have caused the nullpointer error I was experiencing at runtime, or is that a wholly separate error? (That's all the stacktrack says: NullPointerException: null
)
Edit: D'oh. Using a factory, forgot to instantiate one of the DAOs I'm using. That'd be the cause of the NullPointer then. Case closed.
Change long sarah = 9000000000;
to long sarah = 9000000000L;
. Without the 'L' suffix, any integer literal is an int
in Java.
Try to use
9000000000L.
You need to specify the type in this case. Or use
new Long("9000000000")
To understand what is going on here, you need to understand a bit about integer literals.
In Java there are two kinds of integer literals.
A Long literal has a suffix 'L', and must fall in the range -2^63 to +2^63 - 1. It has type
long
.An Int literal has no suffix, and must fall in the range -2^31 to +2^31 - 1. It has type
int
.
An integer literal that falls outside of the prescribed range is a compilation error, no matter what the context. Thus:
long sarah = 9000000000;
is a compilation error, despite the fact that that "number" is compatible with the type on the LHS. Similarly:
Long fred = new Long(9000000000);
is a compilation error ... for the same reason.
The solution is to add an L suffix; e.g.
long sarah = 9000000000L;
Long fred = new Long(9000000000L);
(Actually, I told a small white lie in the above. The JLS actually states that an Integer literal is unsigned, and that what looks like a "negative literal" is actually an expression using the Unary minus operator. The legal integer literal values are therefore 0 to +2^31 - 1 (for int) and 0 to +2^63 - 1 (for long). The literals 2^31 and 2^63 used to express Integer.MIN_VALUE and Long.MIN_VALUE are special cases ... they are only legal when preceded by Unary minus.)
精彩评论