C
C
Clean Coder2020-07-07 17:25:52
Java
Clean Coder, 2020-07-07 17:25:52

Why is this code not working correctly?

Here is a simple program to reverse a number:

import java.util.Scanner;

public class Main {
    private static void invertDigits(Integer number) {
        Integer temp = 0;
        while (number != 0) {
            temp = temp * 10 + number % 10;
            number /= 10;
        }
        number = temp;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Integer number;
        System.out.print("Enter number: ");
        number = scanner.nextInt();
        invertDigits(number);
        System.out.println("Reverse digit order: " + number);
     }
}


Result:
Enter number: 123
Reverse digit order: 123


The question is, why hasn't number changed? After all, an Integer is passed to the function, and this is a reference type.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lyoshik, 2020-07-07
@HustleCoder

1. Integer - immutable.
2.https: //stackoverflow.com/a/40523

import java.util.Scanner;

public class Main {
    private static Integer invertDigits(Integer number) {
        Integer temp = 0;
        while (number != 0) {
            temp = temp * 10 + number % 10;
            number /= 10;
        }
        return temp;
    }

    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        Integer number;
        System.out.print("Enter number: ");
        number = scanner.nextInt();
        System.out.println("Reverse digit order: " + invertDigits(number));
    }
}

D
Denis Zagaevsky, 2020-07-07
@zagayevskiy

It doesn't work that way. If Integer were mutable and you changed its internals, then the changes would be visible.
Return a value from a method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question