5 Most Common Java Pitfalls
- Not understanding that String is an immutable class:
The Java String class is immutable (Unmodifiable). This is because String objects are cached in a String pool. The object that a String is referencing to can change, but the String objects themselves cannot.Example:
publicclassMain {publicstaticvoidmain(String[] args){String str ="GeeksFor";// A new string will be returned, but the actual String will remain the samestr.concat("Geeks");// Prints inital value "GeeksFor"System.out.println(str);// Now we change the reference of "str" to point to the new String returnedstr = str.concat("Geeks");// Prints the new concatenated StringSystem.out.println(str);}}chevron_rightfilter_noneOutput : GeeksFor GeeksForGeeks - Memory Leaks:
One of the core benefits of Java is the Java Garbage Collector , which manages the objects memory on the heap. Whenever an object is unreachable it is automatically freed.However, a common slip for both new and experienced programmers is preventing the memory from being freed, by allowing objects to be reachable that are no longer in use. This can be a very big downside to a project since memory leaks block resources and degrades the application performance. It can even lead to java.lang.OutOfMemoryError.
Common Cases are:
- Static Fields Declaring a static field and forgetting to set it to null after its data is not longer needed
- Unclosed Streams The Java Virtual Machine allocates memory for every connection opened. Forgetting to close the connection consumes memory. Such connections can be: Input Streams, Database Connections, Sessions and others.
- The finalize() method When we override the finalize() method, the object of that class is not any more directly garbage collected. The Garbage Collector is then waiting for finalization, which is happening at a later point in time.
- Pre/Post Increment Operator and side-effects:
The evaluation order of operators in Java appear to be evaluated from left to right, the side effects can be seen instantly:publicclassMain {publicstaticvoidmain(String[] args){intnum =0;/* First case */// The increment operator happens after the value is pushed onto the stack and assignednum = num++;// Prints initial valueSystem.out.println(num);/* Second case */// Increment occurs first, and then it is pushed to the stack and assigned to numnum = ++num;System.out.println(num);}}chevron_rightfilter_noneOutput : 0 1The execution context of the first case is as follows:
- Store previous value of operand.
- Increment the value.
- Return the previous value
The execution context of the second case is as follows:
- Increment the value.
- Store value of operand (incremented)
- Return the value
- Using the relational operator “==” for Objects comparison.
Many novice programmers try to use the “==” operator to compare objects and when the behaviour of their code is not as expected they are confused. A thing to be aware of is that the relational operator “==” is making a reference comparison, it checks if both objects point to the same location in memory. Using the .equals() method will eliminate the problem since it compares the values inside the objects.publicclassMain {publicstaticvoidmain(String[] args){String s1 =newString("GeeksForGeeks");String s2 =newString("GeeksForGeeks");// Comparing using the relational operatorif(s1 == s2) {// falseSystem.out.println("Both objects point to the same memory location!");}// Comparing using the .equals()if(s1.equals(s2)) {// trueSystem.out.println("The value inside the object instances match!");}// Declaring a string with a reference to s1String s3 = s1;if(s3 == s1) {// trueSystem.out.println("Both objects point to the same memory location!");}}}chevron_rightfilter_noneOutput : The value inside the object instances match! Both objects point to the same memory location!Although sometimes the “==” operator will give the expected answer:
publicclassMain {publicstaticvoidmain(String[] args){String s1 ="GeeksForGeeks";String s2 ="GeeksForGeeks";// Comparing using the relational operatorif(s1 == s2) {// trueSystem.out.println("The two strings are the same!");}else{System.out.println("The two strings are the different!");}}}chevron_rightfilter_noneOutput : The two strings are the same!
The reason is in the Java Language Specification String Literals: ‘Literal strings within the same class in the same package represent references to the same String object’. The condition in the code is true because the literals are consisting of the same characters.
- Using raw types
Before Java started using generic types, there have not been alternatives to raw types (types that are not parametrized). For backward compatibility reasons, it is still possible to define these:publicclassMain {publicstaticvoidmain(String[] args){// Defining a raw list, without specifying its type parameterList geeksList =newArrayList();// Due to the unspecified type we can add any data type and the code will compilegeeksList.add(100);geeksList.add(200);geeksList.add("GeeksForGeeks");// When the second element is reached the compiler will throw a runtime error// because we are trying to cast a string to an integergeeksList.forEach(k -> System.out.println((int)k *2));}}chevron_rightfilter_noneOutput : 200 400 Exception in thread "main" java.lang.ClassCastException: java.base/java.lang.String cannot be cast to java.base/java.lang.IntegerThis issue can be prevented by defining the generic type of the List:
List geeksList = new ArrayList();
Now the code won’t compile since we are trying to add a String type to a collection of Integer types. Generic Types are created for a reason and prevent programmers from nasty bugs and overheads.
Recommended Posts:
- Find common elements in two ArrayLists in Java
- Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
- Java.util.concurrent.RecursiveAction class in Java with Examples
- Java.util.function.DoublePredicate interface in Java with Examples
- Java.util.concurrent.RecursiveTask class in Java with Examples
- Java lang.Long.numberOfTrailingZeros() method in Java with Examples
- Java.util.function.LongPredicate interface in Java with Examples
- Java.util.function.IntPredicate interface in Java with Examples
- Java lang.Long.lowestOneBit() method in Java with Examples
- Java.util.Collections.disjoint() Method in java with Examples
- Java.util.BitSet class methods in Java with Examples | Set 2
- Java lang.Long.reverse() method in Java with Examples
- Java.util.LinkedList.peek() , peekfirst(), peeklast() in Java
- Java.lang.Short toString() method in Java with Examples
- Java.util.LinkedList.offer(), offerFirst(), offerLast() in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




