52

In the same spirit of other platforms, it seemed logical to follow up with this question: What are common non-obvious mistakes in Java? Things that seem like they ought to work, but don't.

I won't give guidelines as to how to structure answers, or what's "too easy" to be considered a gotcha, since that's what the voting is for.

See also:

28 Answers 28

38
"a,b,c,d,,,".split(",").length

returns 4, not 7 as you might (and I certainly did) expect. split ignores all trailing empty Strings returned. That means:

",,,a,b,c,d".split(",").length

returns 7! To get what I would think of as the "least astonishing" behaviour, you need to do something quite astonishing:

"a,b,c,d,,,".split(",",-1).length

to get 7.

1
  • 1
    also note that split takes a regex, so to split on dot you would need to do "a.b".split("\\.") Commented Jun 13, 2017 at 8:21
37

Comparing equality of objects using == instead of .equals() -- which behaves completely differently for primitives.

This gotcha ensures newcomers are befuddled when "foo" == "foo" but new String("foo") != new String("foo").

3
  • 3
    Interestingly Groovy uses '==' as value comparison and not object identity comparison. Be careful when copy-pasting ! Commented Oct 4, 2008 at 22:29
  • To follow from this... String j = "foo";System.out.println(j=="foo"); //Prints out true
    – user798182
    Commented Nov 25, 2014 at 23:30
  • Rule of thumb: if the variable has an equals() method, use it.
    – noamtm
    Commented Jul 10, 2016 at 9:54
32

I think a very sneaky one is the String.substring method. This re-uses the same underlying char[] array as the original string with a different offset and length.

This can lead to very hard-to-see memory problems. For example, you may be parsing extremely large files (XML perhaps) for a few small bits. If you have converted the whole file to a String (rather than used a Reader to "walk" over the file) and use substring to grab the bits you want, you are still carrying around the full file-sized char[] array behind the scenes. I have seen this happen a number of times and it can be very difficult to spot.

In fact this is a perfect example of why interface can never be fully separated from implementation. And it was a perfect introduction (for me) a number of years ago as to why you should be suspicious of the quality of 3rd party code.

6
  • That is also very useful for saving memory, when you are going to be splitting a large String into a number of substrings. Commented Oct 4, 2008 at 11:06
  • The source code for Java's class library is always a fascinating read, whether for better or worse. ;) Commented Oct 4, 2008 at 13:52
  • One could imagine a VM optimization where such an array could be partially GC:ed if the parts could be proven to be inaccessible. Commented Mar 27, 2010 at 18:39
  • 11
    Please note that this answer is now partially obsolete. In newer JDK, substring doesn't act like this. Relevant related answer. Commented Jan 10, 2013 at 15:43
  • 2
    The change was in JDK 7u6, marked as bug no. 4513622.
    – FilipK
    Commented Dec 2, 2013 at 9:43
30

Overriding equals() but not hashCode()

It can have really unexpected results when using maps, sets or lists.

3
  • I did something stupid with hashmaps these days, I was using the hash of something as the key for a map, and not the object itself. At my first hash collision I got problems as the equals method for the integer would return true, even when the equals method for the object would return false. Commented Aug 2, 2009 at 19:42
  • The silly thing was reinventing the wheel (and possibly premature optimisation); java.util.HashMap effectively uses the hash of an object as the key (for efficiency purposes), but handles collisions properly using buckets. Always look for an existing class that has the desired functionality first! Commented Sep 9, 2009 at 14:49
  • 4
    Not to mention: overriding equals with the wrong signature. public boolean equals(MyStuff other) ... instead of public boolean equals(Object other) ...
    – Dirk
    Commented Jan 18, 2011 at 12:45
26

SimpleDateFormat is not thread safe.

0
22

There are two that annoy me quite a bit.

Date/Calendar

First, the Java Date and Calendar classes are seriously messed up. I know there are proposals to fix them, I just hope they succeed.

Calendar.get(Calendar.DAY_OF_MONTH) is 1-based
Calendar.get(Calendar.MONTH) is 0-based

Auto-boxing preventing thinking

The other one is Integer vs int (this goes for any primitive version of an object). This is specifically an annoyance caused by not thinking of Integer as different from int (since you can treat them the same much of the time due to auto-boxing).

int x = 5;
int y = 5;
Integer z = new Integer(5);
Integer t = new Integer(5);

System.out.println(5 == x);     // Prints true
System.out.println(x == y);     // Prints true
System.out.println(x == z);     // Prints true (auto-boxing can be so nice)
System.out.println(5 == z);     // Prints true
System.out.println(z == t);     // Prints SOMETHING

Since z and t are objects, even they though hold the same value, they are (most likely) different objects. What you really meant is:

System.out.println(z.equals(t));   // Prints true

This one can be a pain to track down. You go debugging something, everything looks fine, and you finally end up finding that your problem is that 5 != 5 when both are objects.

Being able to say

List<Integer> stuff = new ArrayList<Integer>();

stuff.add(5);

is so nice. It made Java so much more usable to not have to put all those "new Integer(5)"s and "((Integer) list.get(3)).intValue()" lines all over the place. But those benefits come with this gotcha.

5
  • 2
    It took me two 8-hour days to figure out why all of our dates were a month off... I was pulling my hair out!
    – Knobloch
    Commented Oct 5, 2008 at 12:25
  • 1
    0-based month is a POSIX (and C library) thing. Just because it's a standard, doesn't mean it should always be followed. Commented Oct 9, 2008 at 18:35
  • 6
    z == t is always false. Two separately-newed objects have different object identity. On the other hand, if you said Integer.valueOf(5) in both cases, then they'd be the same object: values between -128 and 127 are supposed to be cached values. Commented May 6, 2009 at 11:40
  • 1
    If x == z or 5 == z is true, it's because of auto-unboxing on the z, not of any sort of auto-boxing. Integer.valueOf(5) != new Integer(5) (remembering my previous comment about a new object having different identity to any other separately newed object). Commented May 6, 2009 at 11:41
  • 2
    -1. You are wrong about the z == t example, as @Chris Jester-Young describes. Maybe you are confusing this with a similar example in .NET where z == t can be true.
    – finnw
    Commented Jul 15, 2010 at 9:03
21

Try reading Java Puzzlers which is full of scary stuff, even if much of it is not stuff you bump into every day. But it will destroy much of your confidence in the language.

5
  • It's on my todo list of books to read.
    – Alan
    Commented Oct 4, 2008 at 6:03
  • 3
    It's a great book but most of the "bugs" in the puzzles are things that just do not happen in practice. They are extremely esoteric edge-cases which left me saying "who on earth would have written that anyway!" Commented Oct 4, 2008 at 11:45
  • 2
    Most of the bugs are from bug reports, so clearly people do come across these things, and then get very confused. (I wrote the last program in the book (other than the name), but deliberately.) Commented Oct 4, 2008 at 13:31
  • 1
    Don't take Java Puzzlers as a knock against Java. Most of the things in there are more like "Java is this far from perfect" rather than "Java is broken." Other languages can give you far more problem-causing confusion.
    – TREE
    Commented Oct 16, 2009 at 19:55
  • 2
    To paraphrase a conversation with Josh Blosh in 'Coders at Work'. JB: Why isn't there a book called 'C Puzzlers'? Author: Because it's all puzzlers. JB: that's right, every language has edge cases. It's a credit to Java that they can be listed in a single small book Commented Jan 20, 2013 at 18:25
20
List<Integer> list = new java.util.ArrayList<Integer>();
list.add(1);
list.remove(1); // throws...

The old APIs were not designed with boxing in mind, so overload with primitives and objects.

19

This one I just came across:

double[] aList = new double[400];

List l = Arrays.asList(aList);
//do intense stuff with l

Anyone see the problem?


What happens is, Arrays.asList() expects an array of object types (Double[], for example). It'd be nice if it just threw an error for the previous ocde. However, asList() can also take arguments like so:

Arrays.asList(1, 9, 4, 4, 20);

So what the code does is create a List with one element - a double[].

I should've figured when it took 0ms to sort a 750000 element array...

2
  • 3
    Doubles.asList from Guava (guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/…) does what you want. Similarly Ints.asList does the same for int[] etc.
    – finnw
    Commented Jul 15, 2010 at 10:02
  • You can do things without going through listification too: double[] sorted = aList.clone(); Arrays.sort(sorted); ... and Bob's your uncle. You can also stream it and do things that way if you want. java.util.Arrays has a lot of good stuff, it's not just asList. Commented Mar 19, 2018 at 8:41
16

this one has trumped me a few times and I've heard quite a few experienced java devs wasting a lot of time.

ClassNotFoundException --- you know that the class is in the classpath BUT you are NOT sure why the class is NOT getting loaded.

Actually, this class has a static block. There was an exception in the static block and someone ate the exception. they should NOT. They should be throwing ExceptionInInitializerError. So, always look for static blocks to trip you. It also helps to move any code in static blocks to go into static methods so that debugging the method is much more easier with a debugger.

1
  • This one got me once, but it took me minutes to figure it out, in a codebase of hundreds of thousands of lines - I don't know how an experienced Java dev was stumped by this Commented May 6, 2015 at 15:47
16

Floats

I don't know many times I've seen

floata == floatb

where the "correct" test should be

Math.abs(floata - floatb) < 0.001

I really wish BigDecimal with a literal syntax was the default decimal type...

6
  • 3
    This is not particular to Java, but regards the way that floating pointing numbers are represented. At least C, C++, Python and Perl have these problems and many others have this, probably.
    – rbrito
    Commented Aug 18, 2012 at 22:38
  • 1
    Just because every body else jumps of a cliff... Commented Oct 23, 2012 at 19:35
  • "correct" isn't really right for all cases (but that's the spirit). Otherwise I suppose Java would have provided a generic solution for this. I mean, your solution won't work for 1.001E-15 vs. 1.002E-15.
    – PhiLho
    Commented Jul 11, 2014 at 11:35
  • Having BigDecimal replace float or even double is a terrible idea. Using BigDecimal is a huge performance drain, and should only used when you are looking for precision. float and double are far better than BigDecimal if you're not creating some service that handles money. Commented May 6, 2015 at 15:45
  • I don't believe you could support "huge" if you do some research into real world, typical, java systems. In the type of applications where every calculation overhead is "huge" you wouldn't use java to begin with, and even if you did, you could always have special, non-default, types for lossy performance critical calculations instead. Besides I'm sure there's lots that could be done to make any performance difference not so huge even for performance critical applications. Better implementations plus hardware acceleration could do wonders. Commented May 6, 2015 at 22:31
14

Not really specific to Java, since many (but not all) languages implement it this way, but the % operator isn't a true modulo operator, as it works with negative numbers. This makes it a remainder operator, and can lead to some surprises if you aren't aware of it.

The following code would appear to print either "even" or "odd" but it doesn't.

public static void main(String[] args)
{
    String a = null;
    int n = "number".hashCode();

    switch( n % 2 ) {
        case 0:
            a = "even";
            break;
        case 1:
            a = "odd";
            break;
    }

    System.out.println( a );
}

The problem is that the hash code for "number" is negative, so the n % 2 operation in the switch is also negative. Since there's no case in the switch to deal with the negative result, the variable a never gets set. The program prints out null.

Make sure you know how the % operator works with negative numbers, no matter what language you're working in.

2
  • Shouldn't you do a ((n%2) == 0) means even else false?
    – user55776
    Commented Nov 25, 2009 at 1:59
  • +1 for »Make sure you know how the % operator works with negative numbers, no matter what language you're working in.« – Especially since nearly every language handles modulus differently.
    – Joey
    Commented May 17, 2011 at 18:30
8

Manipulating Swing components from outside the event dispatch thread can lead to bugs that are extremely hard to find. This is a thing even we (as seasoned programmers with 3 respective 6 years of java experience) forget frequently! Sometimes these bugs sneak in after having written code right and refactoring carelessly afterwards...

See this tutorial why you must.

0
8

Immutable strings, which means that certain methods don't change the original object but instead return a modified object copy. When starting with Java I used to forget this all the time and wondered why the replace method didn't seem to work on my string object.

String text = "foobar";
text.replace("foo", "super");
System.out.print(text); // still prints "foobar" instead of "superbar"
3
  • Note: strings are immutable in Python and C# as well. But I agree that whenever you first encounter it, this concept can be confusing, if you have a background working with mutable strings and thus are inclined to treat them basically as char arrays. Note also that for this reason sensitive things like passwords should be handled using char[], since there's no way to wipe a string. stackoverflow.com/questions/8881291/…
    – Jon Coombs
    Commented Jun 20, 2014 at 0:02
  • 1
    Your example is fairly trivial, although yes, it will stump you starting out. I would say a bigger thing that I've actually seen people do (which must not be experienced devs) related to this is synchronizing on an immutable non-final Object: <code> class Foo{ Long bar = new Long(0L); public void baz(){ synchronized(bar){ bar += 1L; } } } </code> In this example, two competing threads will never lock on the same Object, and 'bar' will likely never be what you want it to be (assuming the two threads don't have some valid synchronization up the stack). Commented May 6, 2015 at 15:55
  • @Jon Coombs You can in fact wipe a string. You can use Reflection or Unsafe. This allows for some crazy stuff, like changing a string literal so that trying to print the literal "foo" will actually print "bar" (because of the string pool) Commented Oct 1, 2019 at 2:00
8

I think i big gotcha that would always stump me when i was a young programmer, was the concurrent modification exception when removing from an array that you were iterating:

  List list = new ArrayList();
    Iterator it = list.iterator();
    while(it.hasNext()){
      //some code that does some stuff
      list.remove(0); //BOOM!
  }
7

if you have a method that has the same name as the constructor BUT has a return type. Although this method looks like a constructor(to a noob), it is NOT.

passing arguments to the main method -- it takes some time for noobs to get used to.

passing . as the argument to classpath for executing a program in the current directory.

Realizing that the name of an Array of Strings is not obvious

hashCode and equals : a lot of java developers with more than 5 years experience don't quite get it.

Set vs List

Till JDK 6, Java did not have NavigableSets to let you easily iterate through a Set and Map.

2
  • > Till JDK 6, Java did not have NavigableSets to let you easily iterate through a Set and Map. Regular Sets in Java are easily iterable. NavigableSets just add operations like "find the first element less-than-or-equal to X". Useful, but not necessary to merely iterate.
    – DrPizza
    Commented Oct 4, 2008 at 10:19
  • SortedSet (since Java 1.3) has the headSet and tailSet methods which provide most of that functionality.
    – finnw
    Commented Oct 4, 2008 at 12:10
7

Integer division

1/2 == 0 not 0.5
2
  • ...along with the general rules about type conversion/promotion/inference with the numbers. E.g. 1/2.0 does come out at 0.5, as does 1d/2, and I'm sure a few of the Java puzzlers are related to exactly when promotion happens and thus whether overflow occurs or not. Commented Sep 9, 2009 at 14:51
  • 3
    not java specific though
    – cmcginty
    Commented Sep 5, 2012 at 0:41
5

Using the ? generics wildcard.

People see it and think they have to, e.g. use a List<?> when they want a List they can add anything to, without stopping to think that a List<Object> already does that. Then they wonder why the compiler won't let them use add(), because a List<?> really means "a list of some specific type I don't know", so the only thing you can do with that List is get Object instances from it.

4

(un)Boxing and Long/long confusion. Contrary to pre-Java 5 experience, you can get a NullPointerException on the 2nd line below.

Long msec = getSleepMsec();
Thread.sleep(msec);

If getSleepTime() returns a null, unboxing throws.

1
  • Or you can use long instead of Long and you'll get the NPE one line earlier.
    – Tyler
    Commented Oct 15, 2011 at 6:05
4

The default hash is non-deterministic, so if used for objects in a HashMap, the ordering of entries in that map can change from run to run.

As a simple demonstration, the following program can give different results depending on how it is run:

public static void main(String[] args) {
    System.out.println(new Object().hashCode());
}

How much memory is allocated to the heap, or whether you're running it within a debugger, can both alter the result.

4
  • 3
    That is not a gotcha, it's expected behaviour for a hash map and there's a map class (LinkedHashMap) whose main purpose is to preserve iteration order.
    – finnw
    Commented Mar 27, 2010 at 18:10
  • 2
    @finnw, it was a gotcha for me, when trying to figure out what my program had done, and the next time I'd run it, with the same input, it gave different output. Eventually I discovered that Object.hashCode() can gives different values for even the first object I created. LinkedHashMap is useful, but in my case, I didn't need the insertion or access order preserved, and was trying to be extremely memory efficient, so though Object.hashCode() was fine for my algorithm, I over-rode it to simply gain determinism. Commented Mar 28, 2010 at 0:50
  • Even in C#, "hash code itself is not guaranteed to be stable. Hash codes for identical strings can differ across versions of the .NET Framework and across platforms (such as 32-bit and 64-bit) for a single version of the .NET Framework. In some cases, they can even differ by application domain. "As a result, hash codes should never be used outside of the application domain in which they were created, they should never be used as key fields in a collection, and they should never be persisted." msdn.microsoft.com/en-us/library/system.string.gethashcode.aspx Appears Java's even more so.
    – Jon Coombs
    Commented Jun 19, 2014 at 23:53
  • That is simply because Object's hashCode is its memory address (or a function of that address). This is consistent with class Object equals() method which compares memory addresses too. Any reasonable implementation of hashCode for a subclass will not depend on memory location and should instead depend on object contents.
    – nimrodm
    Commented Apr 19, 2020 at 10:04
4

When you create a duplicate or slice of a ByteBuffer, it does not inherit the value of the order property from the parent buffer, so code like this will not do what you expect:

ByteBuffer buffer1 = ByteBuffer.allocate(8);
buffer1.order(ByteOrder.LITTLE_ENDIAN);
buffer1.putInt(2, 1234);

ByteBuffer buffer2 = buffer1.duplicate();
System.out.println(buffer2.getInt(2));
// Output is "-771489792", not "1234" as expected
1
  • and moreover, they share the underlying buffer. duplicate() is meant to create different class for writing rather than creating a clone and forgetting its origin. Commented Jul 23, 2013 at 10:52
3

Among the common pitfalls, well known but still biting occasionally programmers, there is the classical if (a = b) which is found in all C-like languages.

In Java, it can work only if a and b are boolean, of course. But I see too often newbies testing like if (a == true) (while if (a) is shorter, more readable and safer...) and occasionally writing by mistake if (a = true), wondering why the test doesn't work.
For those not getting it: the last statement first assign true to a, then do the test, which always succeed!

-

One that bites lot of newbies, and even some distracted more experienced programmers (found it in our code), the if (str == "foo"). Note that I always wondered why Sun overrode the + sign for strings but not the == one, at least for simple cases (case sensitive).

For newbies: == compares references, not the content of the strings. You can have two strings of same content, stored in different objects (different references), so == will be false.

Simple example:

final String F = "Foo";
String a = F;
String b = F;
assert a == b; // Works! They refer to the same object
String c = "F" + F.substring(1); // Still "Foo"
assert c.equals(a); // Works
assert c == a; // Fails

-

And I also saw if (a == b & c == d) or something like that. It works (curiously) but we lost the logical operator shortcut (don't try to write: if (r != null & r.isSomething())!).

For newbies: when evaluating a && b, Java doesn't evaluate b if a is false. In a & b, Java evaluates both parts then do the operation; but the second part can fail.

[EDIT] Good suggestion from J Coombs, I updated my answer.

4
  • 2
    if (a = b) causes a compile time error unless a is of type either boolean or Boolean. Yay for strong typing. Boo for bad syntax. Commented Oct 9, 2008 at 18:34
  • 1
    PhiLho, you seem to have assumed that the reader already knows Java and knows what you mean. It would help to explain a bit more what is wrong here and what is right. (E.g. successful assignment vs. comparison; & vs. &&.)
    – Jon Coombs
    Commented Jun 20, 2014 at 0:07
  • Note: regarding (str == "foo"), the problem there is that the == operator, unlike in C#, is not overloaded for strings, so == only compares object IDs rather than comparing the strings.
    – Jon Coombs
    Commented Jun 20, 2014 at 0:24
  • @JCoombs Thanks for pointing that out, I updated my answer. Note that new programming languages like Scala, Dart or Ceylon do the proper thing for == (calling .equals behind the scene).
    – PhiLho
    Commented Jul 11, 2014 at 11:52
2

The non-unified type system contradicts the object orientation idea. Even though everything doesn't have to be heap-allocated objects, the programmer should still be allowed to treat primitive types by calling methods on them.

The generic type system implementation with type-erasure is horrible, and throws most students off when they learn about generics for the first in Java: Why do we still have to typecast if the type parameter is already supplied? Yes, they ensured backward-compatibility, but at a rather silly cost.

1

Going first, here's one I caught today. It had to do with Long/long confusion.

public void foo(Object obj) {
    if (grass.isGreen()) {
        Long id = grass.getId();
        foo(id);
    }
}
private void foo(long id) {
    Lawn lawn = bar.getLawn(id);
    if (lawn == null) {
        throw new IllegalStateException("grass should be associated with a lawn");
    }   
}

Obviously, the names have been changed to protect the innocent :)

1
  • It would help to explain the problem and the solution. I assume the issue here is that the method signature of foo() expects a primitive. Does the code even compile?
    – Jon Coombs
    Commented Jun 20, 2014 at 0:20
1

Another one I'd like to point out is the (too prevalent) drive to make APIs generic. Using well-designed generic code is fine. Designing your own is complicated. Very complicated!

Just look at the sorting/filtering functionality in the new Swing JTable. It's a complete nightmare. It's obvious that you are likely to want to chain filters in real life but I have found it impossible to do so without just using the raw typed version of the classes provided.

1
1
    System.out.println(Calendar.getInstance(TimeZone.getTimeZone("Asia/Hong_Kong")).getTime());
    System.out.println(Calendar.getInstance(TimeZone.getTimeZone("America/Jamaica")).getTime());

The output is the same.

1
  • 1
    Including an explanation would've been nice. Here's my attempt: in both cases, the current time in any location resolves to the same time in absolute terms, and what gets printed is actually based on your own time zone (e.g. UTC/GMT if you're in England).
    – Jon Coombs
    Commented Jun 19, 2014 at 23:45
1

I had some fun debugging a TreeSet once, as I was not aware of this information from the API:

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface. http://download.oracle.com/javase/1.4.2/docs/api/java/util/TreeSet.html

Objects with correct equals/hashcode implementations were being added and never seen again as the compareTo implementation was inconsistent with equals.

0

IMHO 1. Using vector.add(Collection) instead of vector.addall(Collection). The first adds the collection object to vector and second one adds the contents of collection. 2. Though not related to programming exactly, the use of xml parsers that come from multiple sources like xerces, jdom. Relying on different parsers and having their jars in the classpath is a nightmare.

2
  • 1
    That should be an old issue though. Vecor isn't actually used anymore. And with generic Lists that shouldn't be possible. Commented Oct 5, 2008 at 14:44
  • 1
    @John, Vector is also generic
    – finnw
    Commented Mar 27, 2010 at 18:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.