Hello guys, Java is a versatile and powerful programming language, but it's not immune to common coding mistakes that developers may inadvertently make. These errors can lead to unexpected behavior, performance issues, and even security vulnerabilities. In this article, I am going to share 10 such common coding mistakes Java developers often encounter, provide examples of each mistake, explain why they are problematic, and offer solutions to correct them. I strongly recommend every Java developer whether he is beginner, intermediate or senior developer to go through the list once so that you are aware of these mistakes. If you have been coding in Java then most likely you would have also made the same mistake, if you do, let us know in comments so that we all can learn from each other.
10 Common Coding Mistakes Java Developers Make
Here is a list of common coding mistakes Java programmers make. While this is not the very exhaustive list it does contain many coding problems you will commonly see in existing Java code. By knowing them you can avoid the costly mistakes. It's also a good list for senior developers doing code reviews. Modern IDEs like IntelliJIDEA can also help you to identify these mistakes.
1. Comparing String using == rather than equals method
String str1 = "hello";
String str2 = new String("hello");
if (str1 == str2) {
// Incorrect comparison
}
Why it's bad: The == operator compares object references, not the actual content of the strings.
How to make it good: Use the equals method to compare string content:
if (str1.equals(str2)) {
// Correct comparison
}
2. Removing elements from a Collection during iteration without using Iterator's remove method
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
for (Integer num : numbers) {
numbers.remove(num); // ConcurrentModificationException
}
Why it's bad: Modifying a collection while iterating over it can lead to concurrent modification exceptions.
How to make it good: Use an Iterator to safely remove elements during iteration:
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
Integer num = iterator.next();
iterator.remove(); // Safe removal
}
3. Combining static and non-static synchronized methods
public class Example {
public synchronized void nonStaticMethod() {
// ...
}
public static synchronized void staticMethod() {
// ...
}
}
Why it's bad: Mixing static and non-static synchronized methods can lead to unexpected locking behavior.
How to make it good: Use separate locks for static and non-static methods or synchronize at different levels as needed.
4. Using float to store monetary values like price and amount
float price = 19.99f;
Why it's bad: Floating-point types like float are not precise for representing monetary values due to rounding errors.
How to make it good: Use BigDecimal for precise monetary calculations:
BigDecimal price = new BigDecimal("19.99");
5. Converting an array to an ArrayList using Arrays.asList() method:
String[] array = {"apple", "banana"};
List<String> list = Arrays.asList(array);
Why it's bad: The resulting List is fixed-size, and attempts to modify it (add or remove elements) will throw an UnsupportedOperationException.
How to make it good: Create a new ArrayList from the array:
List<String> list = new ArrayList<>(Arrays.asList(array));
These are the first five common coding mistakes; we'll continue with the next five in the next part.
6. Using concatenation operator instead of StringBuilder
String result = "";
for (int i = 0; i < 1000; i++) {
result += "value"; // Inefficient
}
Why it's bad: Repeatedly concatenating strings using the + operator can be highly inefficient due to string immutability.
How to make it good: Use StringBuilder for efficient string concatenation:
StringBuilder result = new StringBuilder();
for (int i = 0; i < 1000; i++) {
result.append("value"); // Efficient
}
7. Returning null instead of an empty Collection from a method
public List<String> getItems() {
if (someCondition) {
return null; // Bad practice
} else {
return items;
}
}
Why it's bad: Returning null can lead to NullPointerExceptions when clients expect a valid collection.
How to make it good: Always return an empty collection instead of null:
public List<String> getItems() {
if (someCondition) {
return Collections.emptyList(); // Good practice
} else {
return items;
}
}
8. Not using Generics
List myList = new ArrayList();
myList.add("hello");
String greeting = (String) myList.get(0); // Requires casting
Why it's bad: Using raw types like List can result in type-unsafe code, requiring explicit casting.
How to make it good: Use generics to ensure type safety:
List<String> myList = new ArrayList<>();
myList.add("hello");
String greeting = myList.get(0); // No casting required
9. Not closing streams or resources
InputStream inputStream = new FileInputStream("file.txt");
// Read from the stream
Why it's bad: Not closing streams or resources can lead to resource leaks and potential issues with file locks.
How to make it good: Use try-with-resources to automatically close streams and resources:
try (InputStream inputStream = new FileInputStream("file.txt")) {
// Read from the stream
} catch (IOException e) {
// Handle exceptions
}
10. Missing break keyword in switch case
int day = 2;
String dayName;
switch (day) {
case 1:
dayName = "Sunday";
case 2:
dayName = "Monday"; // Missing break
// ...
}
Why it's bad: Missing the break statement in a switch case can lead to fall-through behavior, where multiple cases are executed.
How to make it good: Always include the break statement to terminate each case:
int day = 2;
String dayName;
switch (day) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
// ...
}
These are the 10 common coding mistakes in our list. IF you like this article then let me know and I will share more of such coding mistakes. If you don't like it then also let me know that I can improve upon. We'll continue with the remaining 10 coding mistakes in the next part.
And Now is your turn? What is the coding mistakes of this list you have made in your code and how did you solve it? If you have any other coding mistakes which I or other Java developer should be aware of then please feel free to share it.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.