Java

Common Core Java Mistakes and How to Fix Them

Fix the core Java mistakes beginners make most: == on strings, integer division, overflow, null, list removal and equals without hashCode, with runnable code.

StringCompare.java1String b = new String("java");2// a == b -> false3// a.equals(b) -> true4if (a.equals(b)) { ... }
  • Java
  • Debugging
  • Beginners

Quick answer: The most common core Java mistakes are comparing strings with ==, losing decimals in integer division, int overflow, calling methods on null, removing items from a list inside a for-each loop, looping one step too far, overriding equals without hashCode, comparing Integer objects with ==, ignoring String immutability and empty catch blocks. Each has a simple fix.

Most core Java mistakes compile without a single warning. The program runs, and the answer is wrong, or it crashes when the input changes.

Below are ten bugs that beginners write again and again. Each one has a small class you can run, the real output, the reason and the fix. Every example was compiled and run on Java 17.

Core Java mistakes with values and types

1. Comparing strings with ==

public class StringCompare {
    public static void main(String[] args) {
        String a = "java";
        String b = new String("java");
        System.out.println(a == b);
        System.out.println(a.equals(b));
    }
}
false
true

Why it goes wrong: == checks if both variables point to the same object. new String makes a second object with the same text.

Fix: Use equals() for text, or equalsIgnoreCase() when case does not matter.

2. Expecting decimals from integer division

public class Average {
    public static void main(String[] args) {
        int total = 7, count = 2;
        System.out.println(total / count);
        System.out.println((double) total / count);
    }
}
3
3.5

Why it goes wrong: When both sides are int, Java does integer division and drops the decimal part.

Fix: Cast one side to double before dividing, not after.

3. Letting an int overflow

public class Overflow {
    public static void main(String[] args) {
        int perDay = 100_000;
        int days = 30_000;
        System.out.println(perDay * days);
        System.out.println((long) perDay * days);
    }
}
-1294967296
3000000000

Why it goes wrong: An int holds values up to about 2.1 billion. Past that, it wraps around to a negative number, with no error.

Fix: Use long for totals, money in paise and timestamps. Cast before you multiply.

4. Comparing Integer objects with ==

public class IntegerCache {
    public static void main(String[] args) {
        Integer x = 127, y = 127;
        Integer p = 128, q = 128;
        System.out.println(x == y);
        System.out.println(p == q);
        System.out.println(p.equals(q));
    }
}
true
false
true

Why it goes wrong: Java reuses Integer objects from -128 to 127. Outside that range, each value is a new object, so == compares two different objects.

Fix: Use equals() for wrapper types, or unbox to int first.

Interview note: This exact pair of lines is a popular guess-the-output question. Say "true, then false", and explain the cache in one sentence.

Core Java beginner mistakes with objects and null

5. Calling a method on null

public class NullCheck {
    public static void main(String[] args) {
        String city = null;
        System.out.println("Hyderabad".equals(city));
        System.out.println(city.length());
    }
}

The first line prints false. The second throws NullPointerException, and the stack trace points to that line.

Fix: Put the known value first, as in "Hyderabad".equals(city), check for null before use, or use Objects.equals(a, b). Do not return null from your own methods when an empty list will do.

6. Forgetting that strings never change

public class Immutable {
    public static void main(String[] args) {
        String name = "ravi";
        name.toUpperCase();
        System.out.println(name);
        name = name.toUpperCase();
        System.out.println(name);
    }
}
ravi
RAVI

Why it goes wrong: String methods return a new string. The old one stays the same.

Fix: Assign the result. When you join strings inside a loop, use StringBuilder instead of +.

7. Overriding equals without hashCode

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class Student {
    private final int roll;

    Student(int roll) { this.roll = roll; }

    @Override
    public boolean equals(Object o) {
        return o instanceof Student s && s.roll == roll;
    }

    // Remove this method and the set below holds 2 students.
    @Override
    public int hashCode() { return Objects.hash(roll); }

    public static void main(String[] args) {
        Set<Student> set = new HashSet<>();
        set.add(new Student(101));
        set.add(new Student(101));
        System.out.println(set.size());
    }
}
1

Why it goes wrong: HashSet and HashMap use hashCode() to find the bucket first. Without it, two equal students get different hash codes and both are stored.

Fix: Always override both together. Your IDE can generate them, or use a record, which writes both for you.

Mistakes with loops, collections and exceptions

8. Looping one step too far

for (int i = 0; i <= marks.length; i++)  // wrong: <=
for (int i = 0; i < marks.length; i++)   // right: <

Array indexes run from 0 to length - 1. The first loop throws ArrayIndexOutOfBoundsException on its last pass. Use the enhanced for (int m : marks) loop when you do not need the index.

9. Removing from a list inside a for-each loop

import java.util.ArrayList;
import java.util.List;

public class RemoveItems {
    public static void main(String[] args) {
        List<Integer> marks = new ArrayList<>(List.of(35, 80, 20, 90));
        // for (Integer m : marks) if (m < 40) marks.remove(m);
        // throws ConcurrentModificationException
        marks.removeIf(m -> m < 40);
        System.out.println(marks);
    }
}
[80, 90]

Why it goes wrong: The for-each loop uses a hidden iterator. When you change the list behind its back, the iterator notices and throws.

Fix: Use removeIf(), or an explicit Iterator with iterator.remove().

10. Hiding exceptions in an empty catch

try {
    int age = Integer.parseInt(input);
} catch (NumberFormatException e) {
    // nothing here
}

The program carries on as if nothing happened, and the real bug appears ten lines later. At least print or log the message. Better, catch it where you can do something useful, such as asking the user again.

Core Java debugging in five steps

Good core Java debugging is a routine, not luck:

  1. Read the stack trace from the top. Find the first line that names your own file and line number.
  2. Print the values used on that line, with their names: System.out.println("roll=" + roll).
  3. Use the debugger. In IntelliJ IDEA, click beside the line number to set a breakpoint, then run in Debug mode and step through.
  4. Shrink the input. Find the smallest input that still fails.
  5. Change one thing at a time, and run again after each change.
Error Usual cause First check
NullPointerException A variable holds null Which variable on that line is null?
ArrayIndexOutOfBoundsException <= in a loop, or empty array The loop condition
ConcurrentModificationException Changing a list while looping Any add or remove inside for-each
NumberFormatException Parsing text that is not a number Print the input with quotes around it

How to stop repeating core Java common errors

Most core Java common errors come from a few habits: comparing objects with ==, choosing int before checking the range, and testing only the happy path. Test every method with an empty input, a zero and a negative number.

Then cover the "why" lines above and explain each bug aloud. After that, work through our core Java practice problems, where these bugs appear quickly when you code without help. The Java string handling questions and exception handling questions go deeper on two of the topics above.

In CodeBegun's Java Full Stack with AI course, batches are capped at 27 students, so a trainer can read your code and point to the line that is wrong. The Java full stack course guide shows where Core Java fits in the full syllabus.

Frequently asked questions

Why does == not work for strings in Java?

The == operator checks whether two variables point to the same object in memory. Two strings with the same text can be different objects, so == can return false. Use equals() to compare the text.

What is the most common exception for Java beginners?

NullPointerException is the one most beginners meet first. It happens when you call a method or read a field on a variable that holds null. Read the stack trace, find the line, and check which variable on that line is null.

How do I remove items from an ArrayList while looping?

Use list.removeIf() with a condition, or loop with an Iterator and call iterator.remove(). Removing directly inside a for-each loop throws ConcurrentModificationException.

How should a beginner debug Java code?

Read the first line of the stack trace that points to your own file. Print the values used on that line, or set a breakpoint in IntelliJ IDEA and step through it. Change one thing at a time and run again.

Are these Java mistakes asked in interviews?

Yes. Fresher interviews often ask guess-the-output questions on == versus equals, Integer caching, integer division and String immutability. Knowing why each one happens is better than memorising the answer.


Want a trainer to find the bugs you cannot see? Book a free demo class in our Madhapur, Hyderabad classroom or live online, in a batch of at most 27 students.

Found this useful? Share it: LinkedIn Facebook WhatsApp

Written by

Siva Prasad Galaba

Staff Engineer & Founder, CodeBegun

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaching the next generation to code the way the industry actually works.

Back to all articles
Chat with us