0

I was coding on LeetCode and made a program to reverse the order of a number. For example, 123 becomes 321, etc.

I assumed that the integer variable "ans" would be automatically initialized to zero by default. However, when I use the uninitialized variable ans later in the program, I get an error.

Note : this program works perfectly fine if I do initialize ans to zero. But I was just wondering why not initializing ans would get me an error.

class Solution {
    public int reverse(int x) {
        int temp;
        int ans; //uninitialized!

        while(x != 0)
        {
            temp = x % 10;
            ans *= 10; //causes an error!
            ans += temp;
            x /= 10;
        }
        return ans;
    }
}
  • 1
    The duplicate Q was A'd by the master himself – Hovercraft Full Of Eels Apr 18 '20 at 03:13
  • 2
    *"I assumed that the integer variable "ans" would be automatically initialized to zero by default."* You know what they say about assumptions, right? --- *"I was just wondering why not initializing ans would get me an error."* Because the **language specification says so**. It spends an entire chapter on the topic ([Chapter 16. Definite Assignment](https://docs.oracle.com/javase/specs/jls/se14/html/jls-16.html)), which starts: *Each local variable and every blank `final` field must have a **definitely assigned** value when any access of its value occurs.* – Andreas Apr 18 '20 at 03:16
  • @HovercraftFullOfEels - I thought you meant James Gosling :-) – Stephen C Apr 18 '20 at 06:21

0 Answers0