Showing posts with label jhtp. Show all posts
Showing posts with label jhtp. Show all posts

22 November 2025

Java SE version history (updated)

Version Name Release Major new features
25 (LTS)

9/2025 simplifications: top level methods, instance main, IO package
module imports
16
3/2021 record
15
9/2020 Text blocks
14
3/2020 Switch expressions
11 (LTS)

9/2018 Run (single file) source code
9
2016 JSR 294: modular JDK (Jigsaw)
Searchable javadoc 
8 (LTS)
Spider
3/2014 JSR 335: lambda expressions
Collections Stream Framework
JSR 310: Date and Time API
Compact profiles
JSR 308: annotations outside declarations (on usage)
7 Dolphin 7/2011 language (project coin): switch on strings, multi catch, try with autoclosing resources, empty generics (diamond operator), binary literal, underscores in numbers NIO.2 file handling
Fork/Join concurrency
JAX-WS 2.2 (SOAP 1.2, WS-I 2.0, metro 2.0)
6 Mustang 12/2006 JSR 223: scripting language support
JSR 224: JAX-WS2.0 (metro 1.x)
JSR 221: JDBC 4 (driver autoloading))
Perfomance enhancements in synchronisation and garbage collection
5 Tiger 9/2004 language (JSR 201): Enumerations, autoboxing, enhanced for loop, static import, vararg
JSR 175: Annotations
JSR 14: Generics
java.util.concurrent
java.util.Scanner
RMI automatic stub generation
1.4 Merlin 2/2002 language: assert
regular expressions
JSR 51: NIO
JSR 47: java.util.logging
JSR 54: JDBC 3 (metadata API, autogenerated keys, transaction savepoints, multiple || resultsets/statement)
security and cryptography
1.3 Kestrel 5/2000 HotSpot JVM
RMI/CORBA support
JNDI
1.2 Playground 12/1998 Collections
Swing
JIT compiler
Browser plugin
JDBC 2.1 (datasources, distributed transactions, connection pooling,RowSet, ResultSet backscrolling and updating )
1.1
2/1997 AWT events reorganisation
inner classes
JavaBeans
JDBC
RMI
reflection
1.0
1/1996
Here's an overview of Java EE versions

27 April 2016

NetBeans hints (edit)

Your first NetBeans project
  1. On the start page click the Learn & Discover tab
  2. Under Demo's and Tutorials select Java SE applications
  3. Start the Java Quick Start Tutorial 
NetBeans 7.4 Developer Guide
If you're searching how to do someting in netbeans just type it in the ... search box, it will not only search in your project,  but also in the online help.
Keyboard shortcuts
  • view, search & change shortcuts: tools => options => keymap
    • You can set the keymap to a profile from another IDE (Eclipse, IntelliJ...) here as well.
  • help => keyboard shortcuts card. The pdf that is shown, lives in
    netbeansInstallDir
    /nb/shortcuts.pdf. 
  • Some additional useful shortcuts:
    • Go to
      • to definition: CTRL click
        • to implementation: CTRL ALT click
    • Edit
      • Code completion
        • autocomplete popup (+ javadoc): CTRL SPACE
        • javadoc inline popup: CTRL SHIFT SPACE
          • ALT F1 to see in browse
          • Netbeans bundles plenty of javadoc you can browse supplied javadoc for your project libraries from help>Javadoc references
        • complete to recently typed word: CTRL k
      • Add semicolon at end of line:  CTRL ;
      • Add new line below + go there: SHIFT ENTER
    • View
      • fold/unfold code: CTRL –/+
      • members/herarchy of current selection: CTRL/ALT SHIFT F12
      • zoom: ALT + mousewheel up/down 
      • editor only: CTRL SHIFT ENTER (>= 7.4)
Running code
  • After you ran a program, and corrected some errors Rerun using the >> buttons.

  • The lighter double arrows below allow you to rerun with different parameters. You can change the arguments you run with in the Ant properties window.
 
  • Similar options are available for (individual) tests.
    • You can also launch an individual test by  positioning the cursor in the method and selecting "Run focused test" from the right click menu. 


Samples
Netbeans comes with plenty of sample projects for you to explore

HTTP Monitor

The server side monitor is enabled by default for Tomcat and can be enabled in the properties of GlassFish. You may have to undeploy/redeploy your webapp for the monitor to show up.
When the server receives an HTTP request, NetBeans will show a window with all request details. It extracts all parameters and stuff for you, but does not show the raw bodies of POST requests. It does not show responses either.
There is also a client monitor. If you use the internal browser (or the NetBeans Chrome plugin) you can use Window > Web > Network Monitor (NetBeans >= 7.4). It does not show all client side traffic but is targeted at in-page initiated traffic (AJAX, websockets) and failed requests.

4 November 2013

A JUnit 4 Test class

package infotool;

import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

public class InfoModelTest {

    private InfoModel instance;

    @Before
    public void setUp() {
        instance = new InfoModel();
    }

    /**
     * Test of getMessage method, of class InfoModel.
     */
    @Test
    public void testGetMessage() {
        assertEquals("welcome to mvc", instance.getMessage());
    }

    /**
     * Test of getWeather method, of class InfoModel.
     */
    @Test
    public void testGetWeather() {
        assertEquals("Sunny", instance.getWeather());
    }

    /**
     * Test of setMessage method, of class InfoModel.
     */
    @Test
    public void testSetMessage() {
        String wthString = "JUnit @Rules";
        instance.setMessage(wthString);
        assertEquals(wthString, instance.getMessage());
    }

    /**
     * Test of setWeather method, of class InfoModel.
     */
    @Test
    public void testSetWeather() {
        String wthString = "It's going to rain";
        instance.setWeather(wthString);
        assertEquals(wthString, instance.getWeather());
    }

    /**
     * Test of addModelChangeListener method, of class InfoModel.
     */
    @Test
    public void testAddModelChangeListener() {
        InfoModel instance = new InfoModel();
        InfoView view = new InfoViewTestSupport(instance);
        instance.addModelChangeListener(view);
        instance.setMessage("From testAddModelChangeListener");
        assertTrue(((InfoViewTestSupport) view).getNotification());
    }
}

1 November 2013

Java programming: extra labs

 Lesson 3

Extra Practice 3-2, Task 3

Step e. Add a method addEmployees that adds multiple employees

Lesson 4

  Extra Practice 3-2: Equals method

  1.  Add an equals method to the employee class
    1. Use employee id to test equality
      1. Make  sure that it takes into account null values and references to other classes being passed in
      2. You can use ALT+INSERT in NetBeans to insert a sample equals method
    2. Test and correct until the code succeeds
  2. Modify the equality test to use the social security number
    1. Test and correct until the code runs correctly

Lesson 5

  Extra Practice: Deck

  1. Start from the Deck lab from Java Funcamentals
  2. Replace the CardNames and CardValues arrays with enums Suit and Face
  3. Replace the decksize (52) with a number calculated from the available enums 
    1. hint: using the values() method on your enum, returns an array of all values
  4. Test and correct the code until the program runs correctly
  5. Extend the Suit enums with the corresponding unicode characters
    SPADES('\u2660'),CLUBS('\u2663'),DIAMONDS('\u2666'),HEARTS('\u2665');
  6. Extend the Face enum with numbers/names
     ACE("Ace"), TWO("2"), THREE("3"), FOUR("4"), FIVE("5"), SIX("6"),SEVEN("7"), EIGHT("8"), NINE("9"), TEN("10"), JACK("Jack"), QUEEN("Queen"), KING("King");
  7. Modify the code to display the cards using the new data
  8. Test and correct the code until the program runs correctly

Lesson 7

  Extra Practice: Couple

  1. Write a generic class Couple<S,T> that stores two values each with its own generic type
  2. Write a constructor without parameters and a constructor with two parameters
  3. Write getters and setters for each of the members
  4. Write a test, creating a Couple <Integer,String> 
    1. Try to call getters and setters respecting the given types
    2. Try to call getters and setters that do not respect the given types

Extra practice: EmployeeDAOMapImpl

  1. Write an EmployeeDAOMapImpl for practice 6-2 using a Map as internal storage. Start from a copy of the EmployeeDAOMemoryImpl 
  2. Have the factory return the  EmployeeDAOMapImpl
  3. Test and correct until the program runs well

Lesson JUnit

practice DAO

  1. Add a reset() method to the EmployeeDAO from practice 6-2 that clears the employee storage
  2. Create  a JUnit 4 testcase for the EmployeeDAO
    1. Right click on the class and select tools > create Tests
      1. The testcase is created in a dedicated test directory
      2. in which package does the testcase reside?
  3. Complete the generated testcase
    1. In the @BeforeClass method create the DAO object and store it in a static attribute
    2. In the @Before method, initialise the employee table with 3 records
      1. Hint: to make a Date object use Calendar cal = Calendar.getInstance();  
        // you can reuse the same cal object for multiple dates // set the date to januari 6th 2013
        cal.set(2013, 0, 6);
        Date d = cal.getTime();
    3. Write tests for all operations
      1. You may add a setter method to Employee for testing the update operation
  4. Right click the project and select Test (or press ALT+F6)
    1. Test until all tests succeed

Lesson 8

 Extra practice: CSV changer

Write a unit test that replaces all blanks in a file by colons. Multiple blanks should be replaced by only one colon.


25 September 2013

Java fundamentals: extra labs

Lesson 6

Extra practice: Extend Customer Info

  1. Modify lab 6.1 to ask the user to enter the attributes of the customer
  2. Use java.util.Scanner to read the attributes
    1. Take care: after reading an int, you also need to read the return (newline) to advance to the next line of input

Lesson 7

Practice 7.1:

Modify the exercise to:
  1.     Use a java.util.Scanner to read the time of the day from the user input.
  2.     Allow the user to use the format hh:mm:

Extra practice: Seasons

  1.  Create a class Meteo with a method
  2.     public String getSeason(String month) 
  3.  Implement the method and let it return the meteorological season for the month 
    1. (e.g. for december to february return winter)
  4. Create a class MeteoTest
  5. Write a main method that
    1. Creates a Meteo object
    2. Asks the user for the name of a month
    3. Uses the Meteo object to get the corresponding season
    4. Prints out the season
  6. Run the test program and correct errors until it succeeds
  7. Modify the program to make it work no matter which case the user uses when entering the month.
  8. Run the test program and correct errors until it succeeds

Lesson 8

Extra practice: Deck

  1. Create a class Deck  
  2. Initialise a cardNames array with the value of all cards (ace, two, three..., jack, queen, king)
  3. Initilise a cardSuites array with the suites of all cards (hearts, spades, clubs, diamonds)
  4. Create a method called printSize, which
    1. prints the number of cardValues
    2. prints the number of cardSuites
    3. prints the number of cards
  5.  Create a class DeckTest
  6. Write a main method that
    1. Creates a Deck object
    2. Calls printSize on it
    3. Run the test program and correct errors until it succeeds
  7. Write a method drawCard, which prints the name of a random card (e.g. jack of spades)
    1. Hint: use Math.random()
  8. Draw two cards from the main method
  9. Run the test program and correct errors until it succeeds

Lesson 9

Extra practice: Dice

  1.  Create a class DiceStat with a method
  2.     public void printStat () 
  3. The method should roll 2 dice 10.000 times (Hint: use Math.random()
  4. Print the number of times each number was rolled
  5.  Create a class DiceTest
  6. Write a main method that
    1. Creates a DiceStat object
    2. Calls printStat
  7. Run the test program and correct errors until it succeeds
  8. For each result, express as a percentage, how often it is thrown
  9.  Run the test program and correct errors until it succeeds

Extra practice: Factorials

A factorial (n!) is the product of all numbers less than or equal to n. Example:

3!= 3*2*1

Create an application, called factor that will print the factorial of the number given as an argument to the application:

$ java FactorTest 3
3! = 6

Lesson10

Extra practice: Quiz

  1.  Create a class Quiz with keywords and definitions.You can find the keywords and definitions here.
  2. Create a method with signature
  3.     public boolean askQuestion()
    1. The method asks the user to give the keyword that corresponds to a randomly chosen definition
    2. The method compares the answer with the  keyword
    3. The method informs the user about the correctness of the result.
    4. If the answer was wrong, it shows the correct keyword
    5. The method returns if the respons is correct
  4. Create a class QuizTest
  5. Write a main method that
    1. Creates a Quiz object
    2. Calls askQuestion
  6. Run the test program and correct errors until it succeeds
  7. Add a method with this signature
  8.       public int askQuestions(int number) 
    1. The method asks multiple questions
    2. The method returns the number of correct answers
  9. Call the method from the main class
  10. Run the test program and correct errors until it succeeds
  11. Add a method with this signature
    1.  public boolean certify (int numberOfQuestions, int passPercentage)
    2. The method prints out your score percentage.
    3. The method prints out whether you passed the certification or not.
    4. The method returns a boolean with the pass result.
  12. Call the certify method from the main class
  13. Run the test program and correct errors until it succeeds

Extra practice: Hypothenuse

The hypotenuse is the longest side in a right angled triangle. Pythagore's theorem states that the length of the hyothenuse (h) relates to the two other sides (x and y)  as:

Write a program, using that calculates the hypothenus, using java's Math class:

$ java HypothenuseTest 2 3
Hypothenuse = 3.6

Lesson 11

Extra practice: Unique object ID's

  1.  Modify the Rectangle class to assign a unique ID to each object that is created.
    1. Start the ID's at 1 and increment for each new object
    2. Print the rectangle ID in the creation message from the constructor
  2.  Run the test program and correct errors until it succeeds

Extra practice: Deck

  1.  Add a Card class to the Deck project
    1. Add a suit and value attribute and methods to retrieve them
    2. Add a Constructor 
    3. Add a method that returns the card name (e.g. queen of hearts) with signature
         public String toString(); 
  2. Add a constructor to the Deck class that generates a Deck of 52 cards.
  3. Modify the drawCard method to return a Card
  4. After calling drawCard, print out the card name from the main method.

Extra practice: Dice constructor

  1. Add a constructor to the DiceStat class that accepts the number of dies, the number of sides each dice has and the number of throws.
  2. Make the Deck class generic to work with these variables.
  3. Run the test program and correct errors until it succeeds

Lesson 12

Extra practice: Rectangle class hierarchy

  1. Make a class Square, that is a subclass of the Rectangle class. 
    1. Add a Constructor that takes the side as an aargument
  2. Draw a square from the RetcangleTest main method
  3. Run the test program and correct errors until it succeeds
  4. Make rectangle a subclass of Shape. Make a class Shape with an abstract draw method.
    1. In Rectangle you can also use Refactor => extract interface
  5. Make a Triangle class that extends Shape (In the interface, you can press ALT+ENTER to generate a class that implements the interface)
    1. This class is a right angled triangle, with equal width and height. Example:
    2. *
      **
      ***
      ****
    3. Implement the necessary methods
  6. Draw a triangle from the RetcangleTest main method
  7. Run the test program and correct errors until it succeeds
  8.  Make a Canvas class, with a method with signature
  9. public void draw (List shapes)
    1. In the draw method  loop over the list
    2. Assign the objects from the list to a Shape variable
    3. Draw each Shape
  10. In the main method of TestRectangle, create a Canvas
  11. Add a number of rectangles, Squares and triangles to an Arraylist.
  12. Call the draw method on the canvas, and pass the arraylist to it.
  13. Run the test program and correct errors until it succeeds
  14. Make a Parallellogram class that extends Shape (you can make a copy of the Rectangle class and name it Parallellogram to start)
    1. This class draws a parallellogram with a slope that indents one character:
    2. ****
       ****
        ****
    3.  Implement the necessary methods
  15. In the main method of TestRectangle, add some paralellograms to the ArrayList
  16. Run the test program and correct errors until it succeeds

16 May 2012

Java 7 (Dolphin) new features (edit)

Now that Java 7 will soon become the default Java JRE version for download, let's have a look at some new features:

String switch

You can use a String as a selector for a switch/case statement now

Enhanced try/catch

  • multicatch: catch multiple exceptions in one catch statement
    try {  
     ... 
    
    }catch(IOException | FileNotFoundException ex){…}
  • resources implementing java.lang.AutoCloseable resources (most resources in the JDK) can be automatically closed in a try-with-resources. You do not need a finally clause for this anymore.
    • Java 6 code
      try {                
        Scanner input = new Scanner (new File(“client.txt”));            
        …             
      } finally {             
        input.close();
      }
    • Java 7 code
      try(Scanner input = 
        new Scanner (new File(“client.txt”))){ 
        …
      }
    • You can also have multiple resources in a try
      try(Scanner input = 
        new Scanner (new File(“client.txt”)); 
        Formatter output = 
        new Formatter (new File(“adress.txt”)){ 
        …
      }

NIO.2 revamped file handling

is discussed in a separate blog entry.

Small syntax enhancements

  • Diamond operator
  • When the compiler can infer a generics type in a constructor, you can leave it empty
    List<Currency> currencies= new ArrayList<> ();
  • Literal enhancements
  • // binary numbers
    int localhost=0b1111111000000000000000000000001; 
    //underscores (for readability)
    double million=2_000_000.00; 

static java.util.Objects utilities

Examples:
  • null tolerant equals/hashCode/toString

  • hash (Object... values)

CSS styled javadoc 

With Java 7 Oracle is starting to modernise javadoc. In this release javadoc is restyled:












I'm not a big fan of the new look because the method names do not stand out enough for easy scanning the text for the method you need. Fortunatly the pages are styled using CSS. So I went to the topdirectory of the javadoc API and appended the contents of this file to stylesheet css, et voila:











The -stylesheetfile <path> option can be used to specify a stylesheet other than the default when using the javadoc command to generate the documentation.

Fork/Join

Fork/Join is an additional concurrent ExecutorService. It allows a pool of threads to concurrently work on a task, that can dynamically be split up into parallel subtasks. A busy thread is able to chew of a part of the task he’s doing and make it available for other threads.

JDK7

This is not really part of the Java language, but some tools in the JDK were upgraded.

JavaDB

JavaDB was updated to a more recent version of Apache Derby (10.8). Some noteworthy new features:
  • SQL Sequences
  • In memory databases (with disk based backup/restore)
  • SSL/TLS client/server communication
  • role based authorisations
  • stored procedures with elevated permissions

15 April 2012

Java enum demo

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

public enum EnumDemo {
  // For this enum each value has an identification code
  // other than the internal ordinal value
  DEMANDED(10),
  SPECIFIED(20),
  EVALUATED(30),
  DUPLICATE(33),
  ESTIMATED(35),
  WORKAROUND (36),
  ACCEPTED(37),
  PLANNED(40),
  BUSY(50),
  IMPLEMENTED(60),
  REJECTED(100);

  private int code;

  /**
   * @param code  constructor takes code to  be associated with enum
   */
  EnumDemo(int code) {
    this.code = code;
  }

  /**
   * Helper map for reverse lookup in getByCode method
   */
  private static Map<Integer,EnumDemo> enumByCode;
  static{
    enumByCode = new HashMap<Integer, EnumDemo>();
    for (EnumDemo val: EnumDemo.values()) {
      enumByCode.put(val.getCode(),val);
    }
  }

  public int getCode() {
    return code;
  }

  /**
   * reverse lookup
   * @param code the code of the enum
   * @return the enum or null if the code does not exist
   */
  public static EnumDemo getByCode(int code){
    return enumByCode.get(code);
  }

  /**
   * test if a code exists
   * @param code
   * @return  true if the code exists
   */
  public static boolean isCodeValid(int code){
    return enumByCode.containsKey(code);
  }

  /**
   * enumToString: EnumDemo.DEMANDED to "DEMANDED"
   * @return enum value name as a String
   */
  public String getName(){
    return toString();
  }

  /**
   * StringToEnum: "  demanded" to EnumDemo.DEMANDED
   * @param name case insensitive and leading and trailing spaces are ignored
   * @return  the enum constant
   */
  public static EnumDemo getByName(String name){
    return EnumDemo.valueOf(name.trim().toUpperCase());
  }
 
  /**
   * convert between enum and internal ordinal number
   * not recommended to expose this, just here for demo purposes
   * @return internal ordinal number of the constant
   */
  public int getOrdinal(){
    return getOrdinal();
  }
 
  /**
   * convert from ordinal number to enum. Not recommended.
   * @param ordinal
   * @return  the enum
   */
  public static EnumDemo getByOrdinal(int ordinal){
    return EnumDemo.values()[ordinal];
  } 
 
  // some tests and subsets
  // alternate methods can be written using the codes
    
  /**
   *
   * @return  is this enum in a range?
   */
  public boolean isOK(){
    return ACCEPTED.compareTo(this) <= 0 && IMPLEMENTED.compareTo(this)  >= 0;
  }

  /**
   * @return  an enum subrange
   */
  public static EnumSet<EnumDemo> getOK(){
    return EnumSet.range(ACCEPTED,IMPLEMENTED);
  }

  /**
   * @return  is this enum in a subset?
   */
  public boolean isNOK(){
    return this == DUPLICATE
      || this == WORKAROUND
      || this == REJECTED;
  }

  /**
   *
   * @return  get an enum subset
   */
  public static EnumSet<EnumDemo> getNOK(){
    return EnumSet.of(DUPLICATE,WORKAROUND,REJECTED);
  }
} 

18 March 2012

NetBeans 7 new features (edit)

NetBeans 7 is approved for release now. Here's a list of new features
  • Remote glassfish interaction
  • Java 7 support
    • Maven 3 support
    • HTML 5 support
    • JSON formatter
    • Git natively integrated
    • JUnit is now an unbundled plugin (Oracle legal had problems with the old CPL license)
    • easy JPA 2 metamodel generation
    The netbeans 7/Java 7/Glassfish 3.1 combination is still a bit flaky though.

        15 March 2012

        Java How To Program: alternate labs

        Chapter 2

        Preparation

        1. Make sure your PATH environment variable contains the JDK bin directory
          1. On windows separate PATH entries using ; (semicolon)
        Blogger Rijkswatch - Edit post - Mozilla Firefox_2012-03-14_21-40-17 - cropped

        Body Mass Index Calculator

        1. Using an editor create a file called BmiTest.java
        2. Add a public class called BmiTest to the file
        3. Add a main method to the BmiTest class. In the main method
          1. Ask the user for his weight in grams
          2. Ask the user for his height in centimeters
          3. Print the Body Mass Index of the user, using the formula
            BMI = weight x 10 / (height x height)
        4. Save the file
        5. Compile the file using the javac compiler
        6. Run the file using the java command
        7. Correct any errors.
        8. Compile, run and correct errors until all is well.

        Chapter 3

        Body Mass Index Calculator

        1. Create a new Java Application project called javase
          1. Consult the tutorial on creating a NetBeans Java project
            1. Do not create a main class
        2. In the project browser window, right click your project and select New => Java Class
          1. Call the class Bmi
        3. Add private double fields to the class called weight and height
        4. Add a constructor to the class
          1. constructor signature: public Bmi (double myWeight, double myHeight)
          2. In the constructor initialise the object fields using the constructor parameters
        5. Add a method that calculates the BMI
          1. Signature: public double calculate()
          2. In the method return the calculated bodymass. Adapt the calculation to use weight in kilogram and height in meters.
        6. Copy the BmiTest class to the project
        7. Modify the class to
          1. Request weight in kilogram and height in meters
          2. Accept floating point numbers
          3. Replace the calculation with
            1. Creation of a Bmi object called bmi
            2. Calculate the body mass index using the calculate() method on the  bmi object
        8. In the main method, print out the result of the calculation
        9. Run the main method by clicking on the green arrow button in the top toolbar
        10. Correct any errors and run again until all is well.

        Chapter 4

        Body Mass Index Calculator

        A normal BMI is between 18.5 and 24.9.
        1. In the BMI class add a method with signature: public double deviation()
          1. The method should return 0.0 if the BMI is within the normal range
          2. The method should return a negative number indicating the difference with 18.5 if the BMI is lower
          3. The method should return a positive number indicating the difference with 24.9 if the BMI is higher
        2. In the BmiTest main class
          1. print a message indicating that the weight is normal if the difference with the bounds is less than 0.1
          2. otherwise print a message indicating how much the weight should change to be within the normal range
        3. create a main class

        Chapter 5

        Facebook Growth Prediction

        In July 2010 facebook had 500 million users and was growing with a rate of 5% each month.
        Assume the  growth continues at this pace.
        Write a class called FacebookFuture with a main method that lists the number of users for each of the following months, until the number of users exceeds one billion. For each month print out a line with
        • an incrementing number indicating how many months this is from the start date
        • the month and year in a mm/yyyy format
        • the number of users
        Align numbers vertically in each line of output.
        Tip: since Java 7 you may use underscores in numbers to enhance readability. Example:
        long billion=1_000_000_000;
        Info: At the beginning of 2012 facebook numbered 850.000 users

        Chapter 6

        Facebook Growth Prediction

        To calculate the target amount you have after a number of months the formula is
        target = (1 + rate)months X amount
        To calculate the number of months it takes to the target amount, the formula is
        log(target/amount)/log(1+rate)=months
        1. Create a class GrowthPrediction. 
          1. Add an attribute for the current amount (double)
          2. Add a constructor that initializes the amount.
          3. Add a method with signature: public int growthCycles(double target, double rate).
        2. Create a test class called GrowthPredictionTest
          1. Right click the GrowthPrediction class and select Tools => Create JUnit Tests
            1. Accept all defaults
            2. Use JUnit 4
          2. In the testGrowthCycles method add a test that verifies the numbers you obtained in the previous excercise.
            1. Put the number of months obtained in the previous exercise in the expResult variable
            2. Remove the fail statement and the comment above it
            3. Print out a message saying how many months it would take for the number of facebook users to reach one billion
          3. Run the test using the top menu Run => test
          4. Using the same conditions add code to the test method to calculate how many months it would take for facebook to have as many users as a world population of 7_000_000_000
            1. Print out the result

        Chapter 7

        Game of Craps

        1. Make these modifications to the Craps code (Fig 6.9):
          1. Comment out all printing in the Craps class
          2. Make the number of rolls and the result attributes instead of local variables
          3. Add methods
            1. public int getRolls();
            2. public boolean getResult();
        2. Make these modifications to the CrapsTest class.
          1. Run the games for a number of times passed as a command like argument 
            • Run CrapsTest from the command line
            • If you run in netbeans, in the project pane, right click the project => properties => run and set the command line arguments
          2. Print out how many games were won and lost on the first, second,… , twentieth roll and after the twentieth roll.
          3. Print out the percentage of games won
          4. Print out the average number of rolls in a game

        Chapter 8

        Bank

        Implement the Bank case study.
        1. Put classes in two packages
          1. jhtp.bank
          2. jhtp.bank.atm
        2. Start with the classes at the right bottom of Fig 8.24 and work up
        3. Return dummy 0 equivalents from the methods to comply with the method return types
        4. Add attributes for the relations in Fig 8.25

        Cards

        1. Add two new enum classes to example 7.09:
          1. Face
          2. Suit
        2. Modify the example to use the enums
        3. Replace the decksize (52) with a number calculated from the available enums
        4. Run the test program and correct errors until it succeeds

        Chapter 9

        Bank

        1. Make the SavingsAccount from exercise 8.6 a subclass of the Account from the ATM case study.
        2. Replace the usage of the savingsBalance with getter/setter methods using the totalBalance of the Account class.
          1. Add the necessary support to the Account class
        3. Remove the savingsBalance attribute
        4. Test the modified savingsBalance using the SavingsAccount test and correct errors until it succeeds

        Javadoc

        1. Comment the bank classes, methods and attributes with javadoc
        2. In the project browser richt click on the project and select Generate javadoc
        3. Review the generated javadoc, adapt and regenerate
        4. Go to the files prowser tab and open the dist/javadoc directory where the javadoc is generated. Open the file stylesheet.css and append the contents of this file to it and save it. Reload the javadoc in another browser tab and check if anything changed in the presentation.

        Chapter 10

        Bank

        1. Add The Transaction class to the Bank exercise

        CommissionEmployee

        1. Start from the BasePlusCommissionEmployee code in example fig09_12_14
        2. BasePlusCommissionEmployee inherits from CommissionEmployee. We will replace inheritance with composition.
        3. Rename CommissionEmployee to CommissionOnlyEmployee
        4. Create an interface CommissionEmployee that contains the public methods of CommissionOnlyEmployee (except toString())
          1. In CommissionOnlyEmployee choose Refactor => Extract Interface
        5. Adapt BasePlusCommissionEmployee  to delegate to CommisionOnlyEmployee instead of inheriting from it
          1. Replace inheritance in BasePlusCommissionEmployee  with inplementation of the CommissionEmployee interface.
          2. Add an attribute CommissionOnlyEmployee called delegate to BasePlusCommissionEmployee 
          3. Instantiate the attribute in the constructor
          4. Replace all calls to super with calls to delegate
          5. implement all interface methods and call the corresponding method on delegate from them.

        Chapter 13

        Game Of Craps

        Add exception handling to handle bad program parameters to the CrapsTest class in the Game Of Craps from Chapter 7.
        Handle two specific exceptions using one catch statement:
        1. no command line parameter was supplied
        2. the command line parameter was not an integer

        Chapter 19

        FileMatch 1: Collections

        1. Rewrite exercise 14.8, this time loading all accounts in a Collection in memory.
        2. Make sure the output is still ordered by account number.

        FileMatch 2: ResourceBundles

        Localise the messages in the application using resource bundles.
        1. Pass a parameter to FileMatchTest indicating the language (fr or nl)
        2. In the main method construct a ResourceBundle with parameters
          1. “errormsg” as name for the properties files
          2. If the language was passed,  a Locale for this language
            1. if no language was passed, use the one parameter constructor
        3. Pass the ResourceBundle to the FileMatch constructor and save it in an attribute
          1. Print errormessages using the ResourceBundle
          2. Use MessageFormat to substitute parameters in the message
        4. In the src directory create
          • errormsg.properties (english)
          • errormsg_fr.properties  (french)
          • errormsg_nl.properties (dutch)
        5. Add the keys used in the FileMatch error messages to all files and add translated messages in the three languages

        Chapter 23

        FileMatch

        In this exercise we will process multiple transaction files concurrently.
        1. Create a class bank.TransactionProcessor that implements Runnable
          1. Add a constructor TransactionProcessor(Map<Integer, Account> accounts, Path transactionFile)
            1. store the parameters in attributes.
          2. Implement the run method of TransactionProcessor. Move the code from FileMatch that reads the transaction file and adds the transaction amount to the corresponding accounts here. Adapt the code to use the instance attributes.
        2. Make about 5 copies of the trans.txt file.
          1. Give them similar names so you can retrieve them using a wildcard.
        3. Adapt the FileMatch class
          1. Make the Account Collection synchronised to allow concurrent access.
          2. Read the oldmast.txt file and store all accounts in the Account Collection
          3. Create an ExecutorService cached trheadpool
          4. For each transaction file
            1. create a TransactionProcessor thread. Pass the Account collection and the file Path to it.
            2. execute the thread
          5. shutdown the threadpool and awaitTermination of all threads
          6. Write the updated Account Collection to the newmast.txt file.
        4. Add some System.out.println statements throughout your code to  track the processing of the files
        5. Run the program and verify the results.

        Chapter 30

        FileMatch

        Write a program that replaces the blank character separators in oldmast.txt with a colon (:) separator. A sequence of blank characters should be replaces with only one colon separator.

        7 November 2010