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.

Results 1 to 16 of 16

Thread: Common Java Mistakes

  1. #1
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Common Java Mistakes

    Introduction

    Here's a list of common problems you can encounter when programming in Java. Anyone else can feel free to add to this list. I'll try to update this "table of contents" when I can. Do not post in this topic requesting help with a problem you have.

    Compile-time Problems

    This category will cover a variety of problems with compiling your code. On compile, you will immediately be notified of these errors. They are fairly easy to find and fix.



    Common Run-time errors

    This section is for common problems you could encounter at run-time. These problems usually are the direct cause of a crash. In general, these problems are a little more difficult to find, and may or may not be easy to fix.



    Logic problems

    This section is for common problems with logic. These problems usually result in the outputs being wrong, which in turn could crash another part of your program, though they do not need to (in fact, the ones that don't crash are the most difficult to find and fix). These can be very difficult to find and are also the hardest to fix even when you find the problem. You are probably better off putting a post inside the appropriate forum category (Again, do not post in this topic requesting help for specific problems you are having).



    Contributing to this list

    Please follow the template outlined in this post.
    Last edited by copeg; March 17th, 2011 at 10:47 AM.

  2. The Following User Says Thank You to helloworld922 For This Useful Post:

    JavaPF (October 12th, 2010)


  3. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Common Java Problems

    Here's a template you can use if you want to contribute. Try to stick to the template as much as you can, but some deviation is ok. Try to make your post as generic as possible without losing too much detail so a user could figure out what it is they're doing wrong, and how they can apply your suggested fix to their problem. Please keep discussion here to a minimum, post a new topic in the appropriate forum for any questions you may have.


    [size=5]Problem description: A short description of the problem
    Problem category: One of the above listed categories
    [/size][size=3]
    Diagnosis Difficulty: Easy, medium, or hard
    Difficulty to Fix: Easy, medium, or hard
    [/size]

    A longer description of the problem should go here. This should include when a programmer might encounter this problem, and some sample code of what this problem would look like. If there is an error message (either compiler or run-time) which can specifically pin point this type of problem, please post it.

    [size=4]Suggested fixes[/size]

    Suggestions for how the user can fix this problem should go here.

    Last edited by helloworld922; October 11th, 2010 at 06:17 PM.

  4. #3
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Common Java Problems: Parenthesis, Brackets, Braces, etc. mis-match

    Problem description: Parenthesis, Brackets, Braces, etc. mis-match
    Problem category: Compile-time Problems

    Diagnosis Difficulty: Easy
    Difficulty to Fix: Easy


    This problem occurs when you forget to close an open parenthesis/etc., or accidentally put too many closing parenthesis/etc.

    Missing closing ]
    public class Test
    {
    	public static void main(String[ args)
    	{
    	}
     
    	public static void doIt()
    	{
     
    	}
    }

    Too many closing parenthesis

    public class Test
    {
    	public static void main(String[] args)
    	{
    		int a = (1 + 2) / (3 + 4));
    	}
    }

    Error Messages

    In general, the error messages produced for this type of problem are very similar. Here's an example error message for the first piece of problem code. Sometimes the compiler might spit out the wrong location of the problem because it's matching different parenthesis/etc.

    The best way to detect these problems is to properly format your code. See: http://java.sun.com/docs/codeconv/CodeConventions.pdf

    Test.java:3: ']' expected
    public static void main(String[ args)
    Suggested fixes

    Add/remove the appropriate syntax marker.

    Missing closing ]
    public class Test
    {
    	public static void main(String[] args)
    	{
    	}
     
    	public static void doIt()
    	{
     
    	}
    }

    Too many closing parenthesis

    public class Test
    {
    	public static void main(String[] args)
    	{
    		int a = (1 + 2) / (3 + 4);
    	}
    }
    Last edited by helloworld922; January 11th, 2011 at 11:20 AM.

  5. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Common Java Problems

    Problem description: Abstract method in non-abstract class
    Problem category: Compile-time Problems

    Diagnosis Difficulty: Easy-medium
    Difficulty to Fix: Easy


    This problem usually occurs when you inherit an abstract class or implement an interface. It can also occur if you forget to declare your class as abstract after you've declared an abstract method.

    public abstract class Base
    {
    	public abstract void doIt();
    }
    public class Child extends Base
    {
     
    }

    Error Messages

    In general, these error messages are very indicative of the problem, though their may be many error messages if you have multiple abstract methods.

    Child.java:1: Child is not abstract and does not override abstract method doIt()
    in Base
    public class Child extends Base
    Suggested fixes

    There are two common fixes to this problem. The more common of the two is to implement the methods. The other fix is to declare your class as abstract. Both fixes fulfill different purposes (one is providing an actual implementation for that method, the second only declares that an implementation exists and will be defined by inheriting classes), and you should pick the fix that fits your situation.

    Fix 1: Implement the method.

    // using the same Base class as above
    public class Child extends Base
    {
    	/**
    	 * 
    	 **/
    	@Override
    	public void doIt()
    	{
    		// sample implementation
    		System.out.println("I did it.");
    	}
    }

    Fix 2: Declare your class abstract.
    // using the same Base class as above
    public abstract class Child extends Base
    {
     
    }
    Last edited by helloworld922; October 12th, 2010 at 12:29 PM.

  6. #5
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Common Java Mistakes

    Problem description: Code outside of a method
    Problem category: Compile-time Problems

    Diagnosis Difficulty: Medium
    Difficulty to Fix: Easy-medium


    The two most common incarnations of this problem are not putting your code inside of the main method, or not putting initializing code inside of a static initializer block or constructor.

    Missing main method:
    public class Test
    {
        int a = 5;
        for(int i = 0; i < a; ++i)
        {
            System.out.println(i);
        }
    }

    Attempting to perform multi-statement initialization outside of a static initializer block/constructor.
    public class Test
    {
        public static int[] myArray;
        myArray = new int[5];
        for(int i = 0; i < myArray.length; ++i)
        {
            myArray[i] = i * i;
        }
    }

    Error Messages

    Unfortunately, this type of problem doesn't really have any indicative error message. You will probably get tens if not hundreds of error messages of other problems the Java compiler is finding because of this problem.

    Suggested fixes

    Missing main method: Add a main method
    public class Test
    {
        public static void main(String[] args)
        {
            int a = 5;
            for(int i = 0; i < a; ++i)
            {
                System.out.println(i);
            }
        }
    }

    Attempting to perform multi-statement initialization outside of a static initializer block/constructor: add a static initializer block (or a constructor, depending on if you want to initialize static or instance variables).
    public class Test
    {
        public static int[] myArray;
        static
        {
            myArray = new int[5];
            for(int i = 0; i < myArray.length; ++i)
            {
                myArray[i] = i * i;
            }
        }
    }
    Last edited by helloworld922; October 12th, 2010 at 12:30 PM.

  7. #6
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Common Java Mistakes

    Problem description: Referencing Non-static variables/methods in a static way
    Problem category: Compile-time Problems

    Diagnosis Difficulty: Easy
    Difficulty to Fix: Easy-medium


    This problem occurs when you try to access an instance variable in a static way. The most common way this happens is to try to use an instance variable from a static method (such as the main method) without creating an instance of that object. For more information on static and instance variables/methods, see Understanding Instance and Class Members.

    public class Point
    {
        public int    x, y;
     
        public static void main(String[] args)
        {
            x = 5;
            y = 3;
        }
    }

    The second common mistake is to forget to declare your static variables as static (the default is as an instance variable)

    Public class Test
    {
        public int count;
     
        public static void main(String[] args)
        {
            count = 0;
            while(count < 5)
            {
                ++count;
            }
        }
    }

    This problem can also manifest itself by trying to call a non-static method.

    public class Test
    {
        public void doIt()
        {
            System.out.println("Hello world!");
        }
     
        public static void main(String[] args)
        {
            doIt();
        }
    }

    Error Messages

    The error message for this error is very common, and easily indicates what the actual problem is.

    Test.java:7: non-static variable a cannot be referenced from a static context
    a = 5;
    Test.java:10: non-static method doIt() cannot be referenced from a static context
    doIt();
    Suggested fixes

    Depending on your situation, you will either want to change the variable/method declaration to be static, or you will want to create a new instance of the object and reference the field/method from that object.

    public class Point
    {
        public int    x, y;
     
        public static void main(String[] args)
        {
            Point p = new Point();
            p.x = 5;
            p.y = 3;
        }
    }

    Public class Test
    {
        public static int count;
     
        public static void main(String[] args)
        {
            count = 0;
            while(count < 5)
            {
                ++count;
            }
        }
    }
    Last edited by helloworld922; October 12th, 2010 at 12:30 PM.

  8. #7
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Common Java Mistakes

    Problem description: Case Sensitivity, spelling
    Problem category: Compile-time Problems

    Diagnosis Difficulty: Easy
    Difficulty to Fix: Easy


    Java is case sensitive, as well as spelling sensitive. So, the following would all be viewed as different variables in Java:

    double value;
    double Value;
    double valeu;

    Error Message

    Usually Java will complain about a missing declaration. However, you will have to check the spelling/case of both the definition and the usage as either of these could be the problem.

    public class Test
    {
        public static void main(String[] args)
        {
            double Value;
            value = 3;
        }
    }
    Test.java:6: cannot find symbol
    symbol : variable value
    location: class Test
    value = 3;
    Suggested fixes

    Determine which item is misspelled (or in the wrong case), and fix it.

    public class Test
    {
        public static void main(String[] args)
        {
            double value;
            value = 3;
        }
    }
    Last edited by helloworld922; October 12th, 2010 at 12:30 PM.

  9. #8
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: 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);
        }
    }

    Error Message

    Probably 90% of the time this problem will manifest itself with a Null Pointer Exception when you try to run it. However, this exception will pop up at where the null value will cause a problem, not where you need to fix the problem.

    Exception in thread "main" java.lang.NullPointerException
    at NodeTester.main(NodeTester.java:6)
    Suggested fixes

    Look for where the value should have been initialized (almost always in the constructor if it's an object field), then initialize it to an appropriate value.

    public class Node
    {
        public Node[] neighbors;
        public int value;
        public Node(int value)
        {
            this.value = value;
            this.neighbors = new Node[5]; // can have 2 neighbors
        }
    }
    Last edited by helloworld922; October 12th, 2010 at 12:14 PM.

  10. #9
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: 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 ==).

    public Class Point
    {
        public int x, y;
        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
     
        /**
          * Two points are equal if they have the same x and y value
          */
        public boolean equals(Point o)
        {
            if(o == null)
            {
                return false;
            }
            return o.x == x && o.y == y;
        }
     
        public static void main(String[] args)
        {
            Point p1 = new Point(4,5);
            Point p2 = new Point(4,5);    // p2 is a physically in a different location in memory, but it contains the same value as p1
            if(p1.equals(p2))
            {
                System.out.println("p1 and p2 have the same value");
            }
            if(p1 == p2)
            {
                System.out.println("p1 and p2 are the same object in memory");
            }
        }
    }

    Suggested fixes

    You must determine which behavior you want in your particular instance. Sometimes you do want to compare two objects to see if they are the exact same object. However, in the majority of cases you will want to use the equals() method when comparing two objects.

  11. #10
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: 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
    }

    This piece of code demonstrates two off-by-one errors:

    1. You're starting from the first element in the array, so you skip the first item.
    2. You're going until i is greater than myArray.length. This means you will at one point have i = myArray.length. However, this is not a valid array index. Array indices run from [0, length - 1] (using mathematical set notation)

    Error messages:

    If you're lucky, you will get an error message because you over-stepped the bounds of the array.

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at Test.main(Test.java:8)
    However, it's very possible that you may not get an out of bounds exception.

    For example:

    int[] myArray = new int[]{2, 5, 1, 3};
    for(int i = 1; i < myArray.length; ++i)
    {
        // increase every element in myArray by 5
        myArray[i] += 5;
    }

    These are much harder to find because there is no exception telling you what's wrong.

    Suggested fixes

    Ensure that you are properly indexing your arrays, as well as correctly utilizing the length field of your arrays.

    This discussion applies to other types of data structures as well, such as ArrayLists and Vectors which are basically arrays.

    int[] myArray = new int[]{2, 5, 1, 3};
    for(int i = 0; i < myArray.length; ++i)
    {
        // increase every element in myArray by 5
        myArray[i] += 5;
    }

    Note: this is not the only way you can get an off by 1 error, though it is probably the most common.

  12. #11
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: 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:
    java -Xmx512M myprogram

    One can increase this further (for example -Xmx1G) depending upon the available memory on the computer launching the program. For those using an IDE such as Eclipse, one should be able to pass the JVM arguments automatically. In Eclipse, go Run->Run Configurations->Arguments and enter the -Xmx option into the VM Arguments area.

    The problem gets a bit more difficult for deployment. Specifying the maximum memory for an executable jar is not possible without platform specific options (batch files, application bundles, etc...), however deploying applications via Java webstart allows the memory to be set via the max-heap-size parameter.

    Note: One can also set the minimum size of the JVM using the -Xms option in a similar way.

  13. The Following User Says Thank You to copeg For This Useful Post:

    JavaPF (November 1st, 2010)

  14. #12
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: 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. Oracle provides detailed instructions for doing this on the command line. For those using Eclipse, right click the project and select Properties. Go to Java Build Path -> Libraries -> Add External Jar and select the driver jar.

  15. #13
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: 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).

    Each integer type is organized with the sign bit being the most significant bit (furthest left, MSB) and all the other bits representing the magnitude of the number (note that char's don't have the sign bit and all bits represent the magnitude of the number). *Note: Floats and doubles are represented differently, and won't run into this "wrapping problem". However, they will run into other problems concerning floating-point math.

    Now how the computer represents negative numbers is using two's compliment.
    Two's compliment works by inverting all the bits and adding one. So, for example:
    11111111b: invert all the bits results in 00000000b, then adding one is 1b. So 11111111b=-1
    Note that two's compliment is only computed for numbers with the MSB set.

    What happens when you try to increment the number 01111111b (127)? It becomes 10000000b, which represents -128.

    		byte counter = 0;
    		for (int i = 0; i < 0x100; i += 8)
    		{
    			System.out.print(counter + " ");
    			counter += 8;
    		}

     
    0 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120 -128 -120 -112 -104 -96 -88 -80 -72 -64 -56 -48 -40 -32 -24 -16 -8



    Suggested fixes

    The easiest fix is to simply use a larger data type.

    Byte < char (note you'll have to worry about the no sign bit part, I'd skip this for most integer calculations) < int < long

    So if you currently have a byte and it's overflowing, go to an int and so on and so forth.

    What could you do if your longs are overflowing? The only other option is to go to the BigInteger class. This class is designed to handle integers using a "theoretical" infinite bit length. For the purposes of this post I won't discuss how they do this. However, even BigInteger is limited by your computer's physical memory to how large of numbers it can hold (but even with ~64 bytes, your number range would be 2^511-1, or 67039039649712985497870124991029230637396829102961 96688861780721860882015036773488400937149083451713 84501592909324302542687694140597328497321682450304 2047, which is significantly larger than a Google).

    		int counter = 0;
    		for (int i = 0; i < 0x100; i += 8)
    		{
    			System.out.print(counter + " ");
    			counter += 8;
    		}
    Last edited by helloworld922; January 3rd, 2011 at 01:57 PM.

  16. #14
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: 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 objects
                      ^
                    char

    So for example, a byte can be implicitly cast to a short, but a short cannot be implicitly cast to a byte. The most common problems for beginners is dealing with casting of primitive types (particularly between floating point data types and integer data types).

    *Note:
    Strings are objects, and as such can be casted implicitly between Objects and Strings (there are some slight reservations on casting Objects to Strings). When casting an Object to a String, the Object's toString() method is called. Also, the implicit cast from Objects to Strings only occurs you use the append operator for Strings (kind of a strange thing in Java).
    String a = 3; // fails, no cast from int to String
    String b = (String) 3; // also fails for the same reason as above
    String c = "" + 3; // succeeds because of the weird behavior of the + operator with Strings which automatic convert 3 to a String

    Additionally, an object can be implicitly cast up the inheritance chain, but must be explicitly cast if traversing down the inheritance chain.

    public class Base
    {}
     
    public class Derive extends Base
    {}
    //...
    Base a = new Derive(); // implicit cast (polymorphism) from type Derive up to type Base
    Derive b = (Derive) a; // must be explicitly cast back down the inheritance chain

    Examples of some common bad casts:
    // simple examples
    // 1
    int a = 5.5; // casting from double to int
    // 2
    long b = 1;
    int c = b; // casting from long to int
    // 3
    double d = 3;
    int e = d; // casting from double to int
     
    // more complex/subtle examples
    // 4
    double f = 5;
    int g = 1 + 3 * b; // casting from double to int
    // 5
    short h = 3; // casting from int to short
    // 6
    float i = 3.5; // casting from double to float
    byte

    Suggested fixes

    For most cases (especially those involving number data types) you can usually specify an explicit cast. This is done by placing the type name in parenthesis, then an expression you want casted after that.

    int a = (int) 5.5; // 5.5 is explicitly cast into an int, a=5

    Note that when dealing with polymorphic objects and casting them down the inheritance chain will still perform type checking. For example:

    public class Base
    {}
     
    public class Derive1 extends Base
    {}
     
    public class Derive2 extends Base
    {}
     
    //...
    Base a = new Derive1();
    Derive2 b = (Derive1) a; // technically should compile, however on runtime you'll get a ClassCastException. You'll probably even get a warning saying this is an unsafe cast.

    In the above example, the compiler cannot determine if a is a Derive1 object, a Derive2 object, or something else entirely.

    Additionally, sometimes a cast demotion does not exist, even though a promotion cast does exist (for example a String to an int).

    int a = (int) "5"; // invalid, there's no cast for a String to an int, implicit or explicit

    In these cases, you have 2 options:

    1. Search for a method which performs the desired option you want
    int a = Integer.parseInt("5"); // using the Integer class method parseInt to convert a String to an int
    2. Manually extract the data you want
    Point a = new Point(3,5);
    int xCoord = a.x;
    int yCoord = a.y;

    Number constants

    The last major problem when dealing with casts are number constants.
    float a = 3.5; // 3.5 is actually a double literal, invalid implicit cast
    int b = 3L; // 3 is actually a long literal, invalid implicit cast
    byte c = 256; // out of the range for a byte, treated as an int literal, invalid implicit cast

    There are two solutions to this problem:
    1. Use the "general" solution of specifying an explicit cast.
    float a = (float) 3.5;
    int b = (int) 3L;
    byte c = (byte) 256;
    2. Use the appropriate suffixes (or lack there-of) when specifying the literal type. These suffixes are:
    byte - none (must be in the range of a byte)
    short - none (must be in the range of a short)
    int - none (must be in the range of an int)
    long - 'L' (must be in the range of a long)
    float - 'f'
    double - none

    float a = 3.5f;
    int b = 3;
    long c = 1000000000000L;
    // there's no appropriate equivalent for this case since it's basically a guaranteed loss of precision
    // byte c = 256;
    Last edited by helloworld922; March 8th, 2011 at 11:42 AM.

  17. #15
    Member
    Join Date
    Jan 2013
    Posts
    34
    My Mood
    Busy
    Thanks
    2
    Thanked 4 Times in 4 Posts

    Default Re: Common Java Mistakes

    Actually, you can show a double with 'd' / 'D'.

  18. #16
    Junior Member codingninja's Avatar
    Join Date
    Aug 2014
    Posts
    8
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default

    Subscribing, thank you.

Similar Threads

  1. [SOLVED] Sets and creating a new set containing a common number
    By mds1256 in forum Collections and Generics
    Replies: 2
    Last Post: February 26th, 2010, 06:00 PM