Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

  • Common Java Mistakes

    by Published on March 8th, 2011 01:47 AM
    1. Categories:
    2. Common Java Mistakes

    Problem description: Type Mismatch/Invalid Cast
    Problem category: Compile-Time Problem

    Diagnosis Difficulty: Easy
    Difficulty to Fix: Easy


    This problem usually occurs when you're trying to perform calculations using floating point numbers and then storing the results into an integer data type. Java has no problem promoting the data type of a value implicitly, however the designers decided that because an implicit demotion/down cast is likely an accident, the programmer must explicitly specify that's what they want.

    The promotion diagram for Java data types looks like (follow the arrows for implicit promotions/casts):

    `
                    byte
                      v
                    short
                      v
                    int
                      v
                    long
                      v
                    float
                      v
                    double
                      v
          boolean > String < Object < Polymorphic object
                      ^
                    char
    ...
    by Published on March 5th, 2011 02:02 PM
    1. Categories:
    2. Common Java Mistakes

    Problem description: JDBC Connection Error
    Problem category: Runtime Error

    Diagnosis Difficulty: Easy to medium
    Difficulty to Fix: Easy


    When trying to connect to a database using JDBC, a java.lang.ClassNotFound exception is thrown at the point where the database driver should be loaded (eg when Class.forName is called for the appropriate database driver).

    Suggested fixes

    This typically occurs when the database driver is not on the classpath. There are two steps to fix this problem. First, download the driver for the database you wish to access (mysql, postgres, Oracle, Microsoft SQL). Second, place the downloaded jar file on the classpath of the program. ...
    by Published on March 5th, 2011 02:02 PM
    1. Categories:
    2. Common Java Mistakes

    Problem description: byte/char/integer/long values wrapping around (either back to 0 or to a really negative number)
    Problem category: Logic Error

    Diagnosis Difficulty: Easy-Hard
    Difficulty to Fix: Easy-Medium


    In java (and most other programming languages) integer data is represented using binary numbers. While in theory these numbers could be of infinite bit length, this notion is impractical for most computations. So Java defines several data types with different fixed bit lengths. These are:
    byte - at least 8 bits
    char - at least 16 bits (technically this shouldn't be used as an integer data type, but it can be used as one)
    int - at least 32 bits
    long - at least 64 bits

    What does the "at least" mean? Well, in almost all Java implementations (definitely in Sun/Oracle's implementation) this could be dropped. So a byte is exactly 8 bits and so on and so forth. I used "at least" because technically that's what the language specification says explicitly (actually, it states the min/max range of each data type should at least cover, but that could roughly be translated to these bit lengths if we ignore any potential overhead).
    ...
    by Published on March 5th, 2011 02:01 PM
    1. Categories:
    2. Common Java Mistakes

    OutOfMemoryError: Java heap space
    Problem category: Runtime Error

    Diagnosis Difficulty: Medium-Hard
    Difficulty to Fix: Easy


    The JVM's default memory allocation is typically enough for a simple program. However, larger programs with memory intensive computation may result in throwing a java.lang.OutOfMemoryError exception during the execution of a program. A more fundamental analysis of memory usage and object allocation should be performed to confirm that the problem isn't an issue with the program design (such as keeping references to non-needed object), otherwise setting the maximum heap size may just cover up a more fundamental problem.

    Suggested fixes

    Increase the java virtual machine's default memory using the -Xmx option. By default, the maximum memory usage for the JVM is 64M. To increase this value, upon execution of the program pass the JVM the -Xmx* option, where * equals the requested memory (typically divisible by 64 until it reaches the gigabyte stage). For example, to run the program from the command line, call:
    ...
    by Published on March 5th, 2011 02:00 PM
    1. Categories:
    2. Common Java Mistakes

    Problem description: Array Indices/Off by 1 errors
    Problem category: Logic Problem/ Runtime Error

    Diagnosis Difficulty: Easy-medium
    Difficulty to Fix: Easy-medium


    Array indices in Java always start at 0. This is different from some other languages, notably Python, Matlab, etc..

    ex: take an array {2, 5, 1, 3}

    The first item is 2. So, the offset from the first item is 0. Thus, the index of the first item is 0.

    The second item is that the length of arrays is the total number of items in that array. Because of this, an array with 4 item will have a length a 4, and the last item will have an index of length - 1, or 3. This concept trips a lot of people up, so make sure you fully understand it.

    This problem almost always manifests itself when someone tries to use a loop to iterate over an array:

    int[] myArray = new int[]{2, 5, 1, 3};
     
    for(int i = 1; i <= myArray.length; ++i)
    {
         // do stuff to the array
    }
    ...
    by Published on March 5th, 2011 01:59 PM
    1. Categories:
    2. Common Java Mistakes

    Problem description: == operator or equals() method
    Problem category: Logic Problems

    Diagnosis Difficulty: Easy-Medium
    Difficulty to Fix: Easy-Medium


    A common problem among many beginning (and some not so beginning) programmers is the incorrect use of the equal operator and equals() method.

    The equals operator is used exclusively to compare the value of primitives, or to compare the references (memory addresses) of objects.

    // proper usage of the == operator
    int a = 5;
    int b = 5;
    if(a == b) // test if the value a equals the value b
    {
        System.out.println("a and b have the same value");
    }

    The equals() method is used to define when two object values are equal. They do not necessarily have to be the same object (though, if they are they should return true for equals() as well as ==).
    ...
    by Published on March 5th, 2011 01:58 PM
    1. Categories:
    2. Common Java Mistakes

    Problem description: Forgetting to initialize a variable
    Problem category: Runtime problem

    Diagnosis Difficulty: Easy-medium
    Difficulty to Fix: Easy-medium


    This problem occurs when you forget to initialize an object variable. It will usually manifest itself as a Null Pointer Exception when you try to run the code.

    public class Node
    {
        public Node[] neighbors;
        public int value;
        public Node(int value)
        {
            this.value = value;
        }
    }

    public class NodeTester
    {
        public static void main(String[] args)
        {
            Node myNode = new Node(5);
            myNode.neighbors[0] = new Node(3);
        }
    }
    ...
    Page 1 of 2 12 LastLast