Java Reference
In-Depth Information
for (Stock stock : stocks) {
System.out.println(stock.toString());
}
}
}
5.
Run the program. If all goes well—the website or your Internet connection might be down—you
should see the following:
STOCK IBM: International Bus
============================
* Retrieved at: Thu Apr 17 16:02:00 CEST 2014
* Last / High / Low / Open: 190.01 / 190.7 / 187.01 / 187.29
* Previous close: 196.4
* Volume: 11255493
* Market Cap: 197.9B
* Change (%): 6.39 (3.25%)
* Annual range High / Low: 211.98 / 172.19
* Earns: 14.942
* P/E: 13.14
How It Works
Here's how it works:
1.
In the Stock class, you created instance variables to hold all the information the web service
will provide, together with a constructor to initialize Stock objects. You used private variables
with generated getters and setters to do so. While it is generally a good idea to access data in
objects from the outside world by using methods provided by the object (instead of using pub-
lic fields), for “data‐heavy” classes such as the Stock class, feel free to resort to public final
fields if you don't want to make your code too verbose. Especially when none of the getters
and the setters have side effects (meaning that they just return or change one field), this is an
okay approach.
2.
At this point, it might also be prudent to note that—generally speaking—it is not a good idea to
store monetary values and amounts as doubles or floats, not only in Java, but in most program-
ming languages. The reason for this is that the internal representation of a floating point number
cannot accurately represent fractions, which will introduce subtle rounding errors over time once
you start performing addition, multiplication, subtraction, and division on them, as monetary
software tends to do. There are ways to work around this, for example, by using the built‐in
BigDecimal class in Java. For these exercises, it's simpler to work with doubles, but keep this
remark in mind when working with monetary values in a real‐life setting.
3.
The StockFactory class includes a number of methods to construct a set of Stock objects from
a received SOAP message. The newStocksFromSOAPReplyMessage method extracts the reply
string from the message, which is then passed to a separate method, newStocksFromXMLString .
This method converts the string to an XML document, which is then passed to another method,
newStocksFromXMLDocument , which iterates over all the “Stock” tags and parses them using
newStockFromXMLElement . getEl is a helper method defined to get the text content from the
Search WWH ::




Custom Search