Java Reference
In-Depth Information
The following code is that of the Stock class:
public class Stock {
private String symbol;
private String name;
private double shares;
public Stock(String symbol, String name, double
shares) {
this.symbol = symbol;
this.name = name;
this.shares = shares;
}
public String getSymbol() {
return symbol;
}
public String getName() {
return name;
}
public double getShares() {
return shares;
}
public String toString() {
return shares + " shares of " + symbol + " ("
+ name + ")";
}
}
The main() method creates a StockPortfolio and then calls the add()
method to add a number of stocks to the portfolio. Both variations of the foreach
loop (legacy and new Java 8 forEach implementation) are then used to loop over and
print all the stocks in the portfolio. Running the StockPortfolio class results in
the following output:
50.0 shares of IBM (IBM)
300.0 shares of MCD (McDonalds)
100.0 shares of GOOG (Google)
200.0 shares of AAPL (Apple)
500.0 shares of ORCL (Oracle)
Search WWH ::




Custom Search