Addition of primitive double

Run this class
class TestD
     public static void main(String[] arg)
          double d1=13.09d;
          double d2=10.1d;
          System.out.println(d1);
          System.out.println(d2);
          System.out.println(d1+d2);
Result:
13.09
10.1
23.189999999999998
is it reasonable?

This is due to internal representation error and happens with any other language. Search in threads for "internal representation error", "IEEE representation" and related issues. Precision required? use BigDecimal class.

Similar Messages

  • How to roundoff addition of two double variables

    class Example
         public static void main(String args[])
              double k=1.236+2.138;
              System.out.println(k);
    }output of program:
    3.3739999999999997
    so how will i get the exact value of the addition

    etgohomeok wrote:
    If you know it's going to be 3 decimal places every time, you could always do:
    double d1 = 1.236;
    double d2 = 2.138;
    int i1 = (int) d1 * 1000;
    int i2 = (int) d2 * 1000;
    int iResult = i1 + i2;
    double dResult = ((double) iResult) / 1000;You could collapse that into a couple of lines and eliminate alot of the variables, but that's the general point...Unfortunately, that gives the wrong answer. Try running it and see.

  • Class not found for: double

    Does anyone know how to get the class for a primitive double?
    I am trying to invoke a method that has a double parameter and I need the primitive double class.
    java.lang.ClassNotFoundException: double

    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Doub
    le.html#TYPEThanks for responding but,
    I forgot to add that I am using j2se 1.4.2 so I dont have that class :-(
    I am I am not trying to invoke a method I am actually trying to get a method
    args = Class[]{Class.forName("double")};
    obj.getClass().getMethod(methodName, args)Message was edited by:
    jwstudent
    Message was edited by:
    jwstudent

  • Double click on the left arrow on the tab bar creates a New Tab at the right hand end.

    With Firefox 29.0.1 double clicking on either the left or right hand arrows in the tab bar creates a new tab at the right hand end of the tab bar. This is annoying behaviour that violates standards around UI design single click and double click. A double click should extend the behaviour of the single click rather than doing something completely different (opening a new tab). An example would be , in Word a single click selects a word, a double click selects the sentence and a triple click selects the paragraph. Note that this is a separate issue from double clicking on the tab bar itself to create a new tab.
    When there are more tabs on the tab bar than will fit in the viewport the tabs scroll sideways so show the tab in use. I can click the left and right arrows at the ends of the tab bar to scroll the bar in that direction to bring a tab that I want to select into view. I believe that double clicking the left arrow would scroll the bar fully right, exposing the left-most tab. Double clicking the right arrow would scroll the bar fully left exposing the right-most tab.
    This is a logical and expected extension of the behaviour of the single click. Single click - scroll once (seems to be about three tab's worth), double click - scroll all the way.
    At the moment, if I want to scroll to the left-most tab I have to click the arrow slowly and carefully until I reach it. I used to single click rapidly on the left arrow until the tabs stopped scrolling without having to count how many clicks. It's possible that my rapid single clicks were actually double clicks. Nevertheless, the tab bar would stop scrolling when it reached the end.
    Now the behaviour is really annoying and unexpected. A double click on the left arrow scrolls the tabs fully right and then fully left and creates a New Tab at the right hand end. Ditto the right hand arrow in the opposite direction.
    While I can (maybe) see that value of a double click on the tab bar itself creating a new tab, double clicking one of the scroll arrows should not produce a new tab.
    Double clicks on the tab arrows should scroll the tab bar fully to that end. If the tab bar is already fully scrolled to that end then additional clicks (single, double and triple...) should be ignored.
    I like the idea of opening a new tab to the right of the one that currently has focus. This should be a right click context menu option.

    That shouldn't happen if you click the scroll buttons on the tab bar.
    A double-click should act as page up/down and move a full screen and a triple-click should move to the far left (first tab) or the far right (last) tab.
    Start Firefox in <u>[[Safe Mode|Safe Mode]]</u> to check if one of the extensions (Firefox/Tools > Add-ons > Extensions) or if hardware acceleration is causing the problem.
    *Switch to the DEFAULT theme: Firefox/Tools > Add-ons > Appearance
    *Do NOT click the Reset button on the Safe Mode start window
    *https://support.mozilla.org/kb/Safe+Mode
    *https://support.mozilla.org/kb/Troubleshooting+extensions+and+themes

  • Error adding double values

    Processing in my application requires adding huge double values,
    for instance i am adding 36561584400629760 and 1152062986011661
    and instead of getting 37713647386641421 I get 37713647386641424.
    Does somebody have a clue as to what the problem could be?
    I tried using BigInteger and primitive double datatypes.
    Thanks

    doubles precision is about 16 digits. Try this     BigDecimal bd1 = new BigDecimal("36561584400629760"),
                  bd2 = new BigDecimal("1152062986011661");
         System.out.println(bd1.add(bd2));
    or
         BigInteger bi1 = new BigInteger("36561584400629760"),
                  bi2 = new BigInteger("1152062986011661");
         System.out.println(bi1.add(bi2));

  • Supressing the Scientifc Notation for  double

    Hi folks,
    I have a requirement , that i have to supress the scientific representation of a primitive
    double value , while displaying the double value in a form elememt ( textbox).
    eg.
    for 80000000, display will show 8.0E7, which is not desired.
    I need the display as 80000000 itself .
    Can some one throw some lights on this.
    Thanks in advance

    http://forum.java.sun.com/thread.jsp?forum=45&thread=527375&start=0&range=15#2531742

  • Is (double[]).getClass().getName() defined?

    I have a simple class that holds an ArrayList of a single type of Objects.
    Most of the time it will be a double[] but other times it might be a data
    holding class.
    I want to be able to query the holding class for what type of objects are
    in the ArrayList. I was going to return a Class object.
    public Class getObjectType(){
    return some Class;
    I get "[D" as the Class name for double[]. Can i rely on that name or
    should i just wrap the double[] array into a wrapper class?
    I wrote this test class:
    public class ArrayClassTest{
    public static void main(String[] args) {
         new ArrayClassTest();
    public ArrayClassTest(){
         System.out.println("This Class: " + this.getClass().getName());
         double[] dblArray = {0.0, 1.0, 2.0};
         int[] intArray = {1, 2, 3};
         Object[] objArray = {null};
         ArrayClassTest[] actArray = {this};
         System.out.println("Array Class: " + dblArray.getClass().getName());
         System.out.println("Array Class: " + intArray.getClass().getName());
         System.out.println("Array Class: " + objArray.getClass().getName());
         System.out.println("Array Class: " + actArray.getClass().getName());
    }Which yields these results:
    This Class: ArrayClassTest
    Array Class: [D
    Array Class: [I
    Array Class: [Ljava.lang.Object;
    Array Class: [LArrayClassTest;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I think so, the names of the array classes have been stable at least since Java 1.2, as far as I know.
    The '[' says that it's an array. D, I etc. specifies a primitive (double, int etc.) '[L' means it's an object array, followed by the fully qualified name of the element type. So [Ljava.lang.String; would be a String[] etc.

  • Using an array of primitive

    How can I truncate an array of (primitive) double?
    Is it like the following, or some more obviously legitimate way?
    double[] dArr=new double[12345678];
    dArr = Arrays.copyOf(dArr,7234567); I don't want to have both sizes allocated at the same time.
    Also, (not as important to me) can I extend this array?
    And this reminds me of another related question:
    Why can't java allocate heap space by itself without my
    having to use, e.g., -Xmx999m manually and guessingly?
    Or can it?
    Or am I missing some procedure?

    hillmi wrote:
    How can I truncate an array of (primitive) double?
    Is it like the following, or some more obviously legitimate way?
    double[] dArr=new double[12345678];
    dArr = Arrays.copyOf(dArr,7234567); I don't want to have both sizes allocated at the same time.
    Also, (not as important to me) can I extend this array? Extend NO.
    Make a new one YES, but both would be in memory at the same time.
    You could use an ArrayList with Double, then you could extend it.
    And this reminds me of another related question:
    Why can't java allocate heap space by itself without my
    having to use, e.g., -Xmx999m manually and guessingly? I do not believe it can.

  • How do you make a double to a string

    I have a GUI program and I need to take whats in the text box and +,-,*,/ it an I need it to be a varable to do this so how can I.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ALEC{
         public static void main(String args[])
              JFrame f1=new JFrame("Applet");
              JTextField tf1=new JTextField(10);
              JButton b1=new JButton("Click Here");
              JLabel l1=new JLabel(" ");
              JPanel p1=new JPanel();
              b1.addActionListener(new ActionListener(){
                   public void actionPreformed(ActionEvent ae){
              String var=tf1.getText();
              Double var2=Double.parseDouble(var);
              l1.setText(var2);
              f1.setSize(300,300);
              p1.add(tf1);
              p1.add(b1);
              p1.add(l1);
              f1.add(p1);
              f1.setVisible(true);
    }

    String to double:
    double var = Double.parseDouble(str);String to java.lang.Double:
    Double obj = Double.valueOf(str);Prefer the primitive double because it's simpler, unless you have a reason to use java.lang.Double.

  • A double can be NaN?

    I have a simple question...
    I knew that a double can't be NaN, but in orden to test an exception, i write this code:
    try {
      double s = 0;
      s = s / 0;
      System.out.println(s);
    }throws no exception at all.. and prints "NaN" in the Output...
    Is it posible that the native double is convert to Double to avoid the exception???
    I try others way to obtain an exception but i can't understand nothing...
    PS: my english is not too good... sorry about that...
    Thx! Javier.

    I knew that a double can't be NaN, but in orden to
    test an exception, i write this code:Obviously, you "knew" wrong. A double can have the value NaN.
    Is it posible that the native double is convert to
    Double to avoid the exception???I have no idea what you mean. Or are you confused about the fact that NaN is a static field defined in class Double? It's still a double (i.e. primitive double, not Double).
    I try others way to obtain an exception but i can't
    understand nothing...

  • Reflection using Primitive types

    Hi all,
    I need to call a method using reflection which takes and array of primitive double objects and I am getting a class cast exception. I am using a convertTypes method to try to return a double[] class. I know primitives are not classes in Java so how can I achieve this?
    Method method = collectionClass.getMethod("setAll"+columnNames, convertTypes(columnTypes[i]));
                        method.invoke(this, columnValues[i]);
    private Class[] convertTypes(Object columnType){
              String colType = (String)columnType;
              if (colType.equalsIgnoreCase("int"))
    return new Class[]{Integer.class};
    else if (colType.equalsIgnoreCase("float"))
         return new Class[] { double[].class };
    //      return new Double[]{Double.TYPE};
    //      return double[].class;
    //      return double[].class;
    else if (colType.equalsIgnoreCase("varchar"))
         return new Class[]{String[].class};
              return null;

    Please clarify, do you need an array of Class objects or a Class object representing the correct array type?
    If you need the latter you can use:private Class<?> getArrayClass(String colType) {
        if (colType.equalsIgnoreCase("int")) return int[].class;
        if (colType.equalsIgnoreCase("float")) return float[].class;
        if (colType.equalsIgnoreCase("varchar")) return String[].class;
        return null;
    }

  • Generically calling a method on an object

    Hello,
    I am trying to write a small utility method to generically call a method on an object.
    This is what I have.
        public static void doCall(Object o, String methodName, Object ... args){
            Class[] types = new Class[args.length];
            int i = 0;
            for(Object arg : args){
                types[i] = arg.getClass();
            try {
                Method m = o.getClass().getMethod(methodName, types);
                m.invoke(o, args);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("Error dynamically calling method " + methodName + " on " + o.toString());
        }It doesn't work because it can't find the method. If I hard code the parameter types as "new Object[] {Double.TYPE}" it works fine (on methods that take a double).
    So, my question is, how can I generically set up the parameter types based on the types of the arguments?
    Thanks,
    ~Eric

    The problem is not on calling agr.getClass(), your primitive double is already autoboxed to a Double object. It is the doCall(...) method who expects an object, not a primitive. So when giving it a primitive value, java autoboxes it to the corresponding object type.
    This means your attempt will only work if the methods to call do not have any primitives as parameters.
    Test this code:
    public class GenericMethodCaller {
         public static void doCall(Object o, String methodName, Object ... args){
            Class[] types = new Class[args.length];
            int i = 0;
            for(Object arg : args){
                types[i++] = arg.getClass();
            try {
                Method m = o.getClass().getMethod(methodName, types);
                m.invoke(o, args);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("Error dynamically calling method " + methodName + " on " + o.toString());
         public static void main(String[] args) {
              Callable callee = new Callable();
              callee.callabelMethod(10d);          
              GenericMethodCaller.doCall( callee, "callabelMethod", 10d ); // 10d gets autoboxed to a Double object.
    class Callable {
         public void callabelMethod(Double o) {
              System.out.println("callabelMethod(Double o) called");
         public void callabelMethod(double o) {
              System.out.println("callabelMethod(double o) called");
    }The output will be:
    callabelMethod(double o) called
    callabelMethod(Double o) called
    - Roy

  • Memory leak using xslprocessor.valueof in 11.1.0.6.0 - 64bit ??

    My company has made the decision to do all of our internal inter-system communication using XML. Often we may need to transfer thousands of records from one system to another and due to this (and the 32K limit in prior versions) we're implementing it in 11g. Currently we have Oracle 11g Enterprise Edition Release 11.1.0.6.0 on 64 bit Linux.
    This is a completely network/memory setup - the XML data comes in using UTL_HTTP and is stored in a CLOB in memory and then converted to a DOMDocument variable and finally the relevant data is extracted using xslprocessor.valueof calls.
    While this is working fine for smaller datasets, I've discovered that repeated calls with very large documents cause the xslprocessor to run out of memory with the following message:
    ERROR at line 1:
    ORA-04030: out of process memory when trying to allocate 21256 bytes
    (qmxdContextEnc,)
    ORA-06512: at "XDB.DBMS_XSLPROCESSOR", line 1010
    ORA-06512: at "XDB.DBMS_XSLPROCESSOR", line 1036
    ORA-06512: at "XDB.DBMS_XSLPROCESSOR", line 1044
    ORA-06512: at "SCOTT.UTL_INTERFACE_PKG", line 206
    ORA-06512: at line 28
    Elapsed: 00:03:32.45
    SQL>
    From further testing, it appears that the failure occurs after approximately 161,500 calls to xslprocessor.valueof however I'm sure this is dependent on the amount of server memory available (6 GB in my case).
    I expect that we will try and log a TAR on this, but my DBA is on vacation right now. Has anyone else tried calling the xslprocessor 200,000 times in a single session?
    I've tried to make my test code as simple as possible in order to track down the problem. This first block simply iterates through all of our offices asking for all of the employees at that office (there are 140 offices in the table).
    DECLARE
    CURSOR c_offices IS
    SELECT office_id
    FROM offices
    ORDER BY office_id;
    r_offices C_OFFICES%ROWTYPE;
    BEGIN
    OPEN c_offices;
    LOOP
    FETCH c_offices INTO r_offices;
    EXIT WHEN c_offices%NOTFOUND;
    utl_interface_pkg.get_employees(r_offices.office_id);
    END LOOP;
    CLOSE c_offices;
    END;
    Normally I'd be returning a collection of result data from this procedure, however I'm trying to make things as simple as possible and make sure I'm not causing the memory leak myself.
    Below is what makes the SOAP calls (using the widely circulated UTL_SOAP_API) to get our data and then extracts the relevant parts. Each office (call) should return between 200 and 1200 employee records.
    PROCEDURE get_employees (p_office_id IN VARCHAR2)
    l_request utl_soap_api.t_request;
    l_response utl_soap_api.t_response;
    l_data_clob CLOB;
    l_xml_namespace VARCHAR2(100) := 'xmlns="' || G_XMLNS_PREFIX || 'EMP.wsGetEmployees"';
    l_xml_doc xmldom.DOMDocument;
    l_node_list xmldom.DOMNodeList;
    l_node xmldom.DOMNode;
    parser xmlparser.Parser;
    l_emp_id NUMBER;
    l_emp_first_name VARCHAR2(100);
    l_emp_last_name VARCHAR2(100);
    BEGIN
    --Set our authentication information.
    utl_soap_api.set_proxy_authentication(p_username => G_AUTH_USER, p_password => G_AUTH_PASS);
    l_request := utl_soap_api.new_request(p_method => 'wsGetEmployees',
    p_namespace => l_xml_namespace);
    utl_soap_api.add_parameter(p_request => l_request,
    p_name => 'officeId',
    p_type => 'xsd:string',
    p_value => p_office_id);
    l_response := utl_soap_api.invoke(p_request => l_request,
    p_url => G_SOAP_URL,
    p_action => 'wsGetEmployees');
    dbms_lob.createtemporary(l_data_clob, cache=>FALSE);
    l_data_clob := utl_soap_api.get_return_clob_value(p_response => l_response,
    p_name => '*',
    p_namespace => l_xml_namespace);
    l_data_clob := DBMS_XMLGEN.CONVERT(l_data_clob, 1); --Storing in CLOB converted symbols (<">) into escaped values (&lt;, &qt;, &gt;).  We need to CONVERT them back.
    parser := xmlparser.newParser;
    xmlparser.parseClob(parser, l_data_clob);
    dbms_lob.freetemporary(l_data_clob);
    l_xml_doc := xmlparser.getDocument(parser);
    xmlparser.freeparser(parser);
    l_node_list := xslprocessor.selectNodes(xmldom.makeNode(l_xml_doc),'/employees/employee');
    FOR i_emp IN 0 .. (xmldom.getLength(l_node_list) - 1)
    LOOP
    l_node := xmldom.item(l_node_list, i_emp);
    l_emp_id := dbms_xslprocessor.valueOf(l_node, 'EMPLOYEEID');
    l_emp_first_name := dbms_xslprocessor.valueOf(l_node, 'FIRSTNAME');
    l_emp_last_name := dbms_xslprocessor.valueOf(l_node, 'LASTNAME');
    END LOOP;
    xmldom.freeDocument(l_xml_doc);
    END get_employees;
    All of this works just fine for smaller result sets, or fewer iterations (only the first two or three offices). Even up to the point of failure the data is being extracted correctly - it just eventually runs out of memory. Is there any way to free up the xslprocessor? I've even tried issuing DBMS_SESSION.FREE_UNUSED_USER_MEMORY but it makes no difference.

    Replying to both of you -
    Line 206 is the first call to xslprocessor.valueof:
    LINE TEXT
    206 l_emp_id := dbms_xslprocessor.valueOf(l_node, 'EMPLOYEEID');
    This is one function inside of a larger package (the UTL_INTERFACE_PKG). The package is just a grouping of these functions - one for each type of SOAP interface we're using. None of the others exhibited this problem, but then none of them return anywhere near this much data either.
    Here is the contents of V$TEMPORARY_LOBS immediately after the crash:
    SID CACHE_LOBS NOCACHE_LOBS ABSTRACT_LOBS
    132 0 0 0
    148 19 1 0
    SID 132 is a SYS session and SID 148 is mine.
    I've discovered with further testing that if I comment out all of the xslprocessor.valueof calls except for the first one the code will complete successfully. It executes the valueof call 99,463 times. If I then uncomment one of those additional calls, we double the number of executions to a theoretical 198,926 (which is greater than the 161,500 point where it usually crashes) and it runs out of memory again.

  • Advanced template to drill down from one dimension to another

    Dear all:
    Situation
    I am trying to create an report that displays my Accounts by month. In addition, after I double-click each account (if it is a base member), it drills down to open Entity (in my case Cost Center) associated with that Account number. In the Entity drill-down section, once the Entity becomes a base member, it drills down to IO (internal orders) associated with a particular cost center.
    Data
    1. I tried to manipulate existing "Double Drill Down" dynamic template, and disabled the column expansion (because my columns consist of months of actual vs. budget and some ratio calculation). The problem is that after I drilled down, my EVGTS formula was not replicated in the other dimension
    2. I tried to integrate EVEXP into EVDRE but was unsuccessful too... The expansion worked as if everything got expanded at the same time.
    Question
    Is my approach correct? Is this an even good practice to do, or I should keep it as standard as possible?
    Thank you!
    Have a great day!
    Sincerely,
    Brian

    The double-drill down dynamic template accommodate my need, except I didn't modify the report to my format correctly.

  • What's the deal with enums?

    Hello,
    I'm trying to familiarise myself with the new Java features that project Tiger (Java 1.5) will introduce. I come from a C++ programming background. I very briefly studied enums whilst I learned C++ and never used them in my programs, so I was, quite frankly, relieved when I learned that Java didn't support them.
    But now it does.
    I'm wondering, from a software design and engineering perspective, what benefit enums will add to the Java language and software engineering in general. I have read some pleas and arguments for enums. As I understand those arguments, proponents feel that minor ledgibility improvements to switch statements (which some OO programmers don't use on the basis that it weakens the object-orientedness through its goto-esque break statements) necessitate the addition of a whole other structure.
    Out of curiosity, wouldn't it be more advantageous for Sun to put their efforts into supporting constant strings in switches in addition to primitive data types if people are so concerned with clarity?
    I fail to understand what enums will do that constant string arrays or constant values cannot. I would like to think that Sun wouldn't add C++ features unless if there was a reason to do so, so I believe that there are good reasons to introduce this feature.
    Please help clarify this confusion.
    Thank you!

    Comments on the previous posting inline. Note: I'll go off on a few tangents, but try to always return to the issue of enums. The fact that I go off on tangents (related initially to an enum type example) should show that enums help eliminate numerous problems.
    Fair enough, but wouldn't this accomplish the same thing in
    a slightly wordier wayPretty much. But you still have the validation code in there yourself:
    currentDirection = ( direction > 0 && direction < 5 ? direction : 0 );People can still accidentally enter an invalid value, and it won't get caught by the compiler. So, I could call set(Compass.WEST) and hope/expect that is equivalent to set(Direction.LEFT). This will only occur if both Compass.WEST and Direction.LEFT are the same int value. If they are not, then we are in trouble. Worse, still if Compass.WEST and Direction.RIGHT are the same value, the code will compile, and run without any illegal value flagging, but our traveller will go off in the wrong direction.
    Error handling tangent: Given the implementation, the error handling is not performed in set, rather the illegal value is captured as a zero, which must be dealt with at a later time - say in a switch statement that calls get. This is not a good idea - it increases the "distance" between the error occuring (bad call to set) and the error being detected (if xInt != 0). The larger the distance, the harder debugging is. If you throw an exception in set the bug is immediately flagged. With enums, none of this should be necessary.
    Implementation tangent: set, get and currentDirection are static. This is not a good idea - it only allows one direction. If you have multiple travellers, each would have a Direction object, but (sticking with constants) UP, etc. would still be static.
    I keep the switch statement in my enum workaround, but I believe that
    the second reply suggested that enum could altogether eliminate the
    use for switch statements. How exactly would it do that?enum in its simplest form would not remove switch. However, using an extension of the type-safe enum idiom (i.e. the current Java approach to enums), you can embed direction specific logic in each of the "enum" members. If I understand the enum-spec correcly, this will also be possible with the Java 1.5 enum language facility.
    So, for an example, sticking with the domain: Consider a class Location, with x and y elements, and a Direction. The non-OO, non-enum approach would be as follows:
    class Location {
        int x,y;
        void move (final int direction) {
            switch (direction) {
                case UP:
                    --y;
                    break;
                case DOWN:
                    ++y;
                    break;
                case LEFT;
                    --x;
                    break;
                case RIGHT:
                    ++x;
                    break;
                default;
                    throw new RuntimeException("Invalid direction " + direction);
    class Direction {
        public static final int UP = 1;
        public static final int DOWN = 2;
        public static final int LEFT = 3;
        public static final int RIGHT = 4;
    }Note that I've deliberately been loose with my visibility. All logic is in Location, and Direction is dumb. If we go with a type safe-enum idiom, we get:
    class Location {
        int x,y;
        void move (final Direction direction) {
            if (direction == Direction.UP) {
                --y;
            } else if (direction == Direction.DOWN) {
                ++y;
            } else if (direction == Direction.LEFT) {
                --x;
            } else if (direction == Direction.RIGHT) {
                ++x;
            } else { // direction is null
                throw new NullPointerException("null direction");
    class Direction {
        public static final Direction UP = new Direction();
        public static final Direction DOWN = new Direction();
        public static final Direction LEFT = new Direction();
        public static final Direction RIGHT = new Direction();
        private Direction () {} // the ctor is private to limit instances
    }This code is a rewrite of the int approach, but is "type-safe". We've moved from switch to if as we can't switch on object references. Note: there is still error handling code, as you're not "null-safe" (I don't know what the Java 1.5 spec says about this)
    Little else has changed - the responsibilities are still the same. We can address this by going OO, which removes the if (formerly a switch) statement, but does couple the classes.
    class Location {
        int x,y;
        void move (final Direction direction) {
            direction.move(this);
    class Direction {
        private final int xOffset, yOffset;
        private Direction (final int xOffset, final int yOffset) {
            this.xOffset = xOffset;
            this.yOffset = yOffset;
        public static final Direction UP = new Direction(0,1);
        public static final Direction DOWN = new Direction(0,-1);
        public static final Direction LEFT = new Direction(-1,0);
        public static final Direction RIGHT = new Direction(1,0);
        void move(final Location location) {
            location.x += xOffset;
            location.y += yOffset;
    }This removes any conditional logic, embedding (constructor parameterised) logic within Direction. It also eliminates the "null-safe" check, as direction.move(this) will throw an NPE if a null is passed.
    Also, I've read some things saying that enum reduces 'boilerplate'
    code. What exactly does that and 'boilerplate' mean?The Direction class is an example of the type-safe enum approach currently used in Java. It has been enhanced with logic for movement. Even if I dropped this logic, there is still functionality worth adding to the Direction class - a toString method that returns one of "UP", "DOWN", etc (shown next); a way to serialize the object and retain reference equality - you have to write a readResolve method (not shown).
    class Direction {
        private final String name;
        private Direction (final String name) {
            this.name = name;
        public static final Direction UP = new Direction("UP");
        public static final Direction DOWN = new Direction("DOWN");
        public static final Direction LEFT = new Direction("LEFT");
        public static final Direction RIGHT = new Direction("RIGHT");
        public String toString() {
            return name;
    }Once you've written this code for one type-safe enum, you've written them for them all. You copy-cut-paste, and rename the class/elements. All this code is predictable. It is "boiler plate". Now, if you gave me a compiler that generated all this code for me, when I present it with
    enum Direction {UP, DOWN, LEFT, RIGHT}; then I've got something that reduces my boiler plate code to zip.... Enter the Java 1.5 compiler.

Maybe you are looking for