-1

I am a new coder in Java and I'm encounter a tutorial about Palindrome that is giving me an error "The parameter 'num' should not be assigned in the highlighted line 16.

Can anyone take a look and offer some insight of what is causing this error?

The program runs correctly. but I am curious about this.

Thanks a lot! (See code below)

1 package javaTutorial;
2
3 public class IsPalindrome {
4
5   final static int num = 12321;
6
7   public static void main(String[] args) {
8       System.out.println(is_Palindrome(num));
9   }
10 
11  public static int reverse(int num) {
12      int rev_num = 0;
13      while (num > 0) {
14          int r = num % 10;
15          rev_num = rev_num * 10 + r;
16          num /= 10; *************  ERROR
17      }
18      return rev_num;
19  }
20 
21  public static boolean is_Palindrome(int num) {
22      if (num == reverse(num))
23          return true;
24      return false;
25  }
26 }
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
Samuel
  • 9
  • 2

2 Answers2

0

It's telling you that it's poor practice to reassign parameters.

Arguably, it's correct. Reassigning a parameter can make debugging slightly more difficult in some circumstances because after an iteration of the loop, you won't be able to see what data was passed into the function originally since you overwrote num. To fix it, create a secondary variable that you reassign:

public static int reverse(int num) {
    int rev_num = 0;
    int acc_num = num; // Here
    while (acc_num > 0) { //The use it instead 
        int r = acc_num % 10;
        rev_num = rev_num * 10 + r;
        acc_num /= 10; 
    }
    return rev_num;
}

Note how num never changes.

But no, this is not an actual error. It's just telling you what it considers to be best practice.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
-1

Type of your num variable is final, which, in java, means the value of a variable can't be changed. I suppose that's the reason for the error.

Wikipedia: in the Java programming language, the final keyword is used in several contexts to define an entity that can only be assigned once.

  • This isn't the case. The static `num` is shadowed by the parameter with the same name. The function is referring to the parameter, not the "global". – Carcigenicate Feb 20 '19 at 22:58
  • That is, however, not the reason the OP gets the warning. Local variables are shadowing class variables, and not the other way around. – MC Emperor Feb 20 '19 at 23:04