Posts

Showing posts from December, 2026

Java Integer 128 Trap: Why 100 == 100 Is True But 128 == 128 Is False

In Java, comparing two boxed Integer objects with == works for 100 —then mysteriously returns false for 128 . 1. The Counterexample public class IntegerCacheDemo { public static void main(String[] args) { Integer x = 100, y = 100; Integer a = 128, b = 128; System.out.println("100 == 100 : " + (x == y)); // true System.out.println("128 == 128 : " + (a == b)); // false! } } 2. Why Does This Happen? For object types like Integer , == compares memory references , not numeric values. Java's Integer.valueOf() caches values from -128 to 127 , so x and y point to the same cached object, whereas 128 allocates two separate objects. 3. The Fix: Use .equals() or Objects.equals() import java.util.Objects; public class IntegerEqualsFix { public static void main(String[] args) { Integer a = 128, b = 128; System.out.println(a.equals(b)); // true System.out.println(Objects.equals(a, b)...

Java Integer Overflow: Why Adding Positive Numbers Gives a Negative Sum

Have you ever summed a list of positive int values in Java and suddenly got a negative number —with no exception and no compiler warning? This happens because Java's 32-bit int overflows silently. Below is a minimal counterexample, why it fails, and the two clean ways to fix it. 1. The Counterexample (Passes Small Tests, Fails Large Inputs) With small sample numbers like 100 and 200 , this code looks completely fine. Pass two large positive values—such as 1,500,000,000 each—and the result turns negative: public class OverflowDemo { public static void main(String[] args) { int[] values = {1_500_000_000, 1_500_000_000}; int sum = 0; for (int x : values) { sum += x; } System.out.println("Sum = " + sum); } } Actual Output: Sum = -1294967296 2. Why Does This Happen? A Java int is a signed 32-bit integer whose maximum value is 2,147,483,647 ( Integer.MAX_VALUE ). When the running total crosses that limi...

C strtol Validation: Why atoi("abc") Returns 0 and How to Fix It

In C, atoi("0") returns 0 —and atoi("abc") also returns 0 . There is no error flag, no exception, and no way to tell whether the user typed a valid zero or complete garbage. 1. The Counterexample #include <stdio.h> #include <stdlib.h> int main(void) { printf("atoi(\"0\") = %d\n", atoi("0")); printf("atoi(\"abc\") = %d\n", atoi("abc")); printf("atoi(\"12x\") = %d\n", atoi("12x")); return 0; } Output: atoi("0") = 0 atoi("abc") = 0 atoi("12x") = 12 2. Why atoi() Is Unsafe Returns 0 on non-numeric input, indistinguishable from real "0" . Silently accepts trailing garbage like "12x" as 12 . Triggers undefined behavior on integer overflow. 3. The Right Fix: Use strtol() with endptr and errno #include <errno.h> #include <limits.h> #include <stdio.h> #include <stdlib.h...

Python CSV Monthly Totals: Stop Different Years From Merging Into One Month

Have you ever aggregated a multi-year transaction CSV by month and wondered why February's sales suddenly looked double ? Grouping by dt.month alone strips out the year—silently combining 2025-02 and 2026-02 into the same bucket. 1. Sample CSV ( sales.csv ) date,amount 2025-02-10,100 2026-02-14,120 2026-03-01,80 2. The Buggy Approach (Grouping by dt.month ) import csv from collections import defaultdict from datetime import datetime totals = defaultdict(int) with open("sales.csv", newline="", encoding="utf-8") as f: for row in csv.DictReader(f): dt = datetime.strptime(row["date"], "%Y-%m-%d") totals[dt.month] += int(row["amount"]) # BUG: loses the year! print(dict(totals)) # {2: 220, 3: 80} <-- 2025-02 and 2026-02 merged! 3. The Fix: Group by %Y-%m (Year + Month) import csv from collections import defaultdict from datetime import datetime totals = defaultdict(int) with open("sale...

Why Excel Breaks Your Python CSV (1-Word UTF-8 BOM Fix)

Your Python CSV looks completely clean in VS Code and the terminal—then you double-click it in Microsoft Excel and see Café , €50 , or broken non-ASCII text. Why? When Excel opens a CSV file directly, it expects a UTF-8 BOM (Byte Order Mark) to recognize UTF-8. Without it, Excel falls back to a legacy local codepage. 1. The Problem: Standard encoding="utf-8" import csv rows = [ ["Item", "Price", "City"], ["Café Latte", "€5", "Seoul"], ] with open("report_broken.csv", "w", encoding="utf-8", newline="") as f: csv.writer(f).writerows(rows) # Excel opens this as: Café Latte, €5, Seoul 2. The 1-Word Fix: encoding="utf-8-sig" import csv rows = [ ["Item", "Price", "City"], ["Café Latte", "€5", "Seoul"], ] with open("report_clean.csv", "w", encoding="utf-8...

C Min/Max Bug: Why Sample Tests Pass But Judge Gives Wrong Answer

Your C solution passes every sample test case—yet submitting it to an online judge returns Wrong Answer . One of the most common causes is initializing max_val = 0 (or min_val = 0 ), which silently breaks whenever all inputs are negative (or all positive). 1. The Buggy Code #include <stdio.h> int main(void) { int n, x; int max_val = 0; // BUG: fails if all inputs are negative! scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &x); if (x > max_val) max_val = x; } printf("%d\n", max_val); return 0; } Counterexample Input: 3 followed by -8 -2 -4 Expected: -2  |  Actual: 0 (not even in the input!) 2. The Fix: Initialize With the First Input Value #include <stdio.h> int main(void) { int n, x; if (scanf("%d", &n) != 1 || n <= 0) return 0; scanf("%d", &x); int min_val = x; int max_val = x; for (int i = 1; i ...