To get the last digit of an integer in Java, you can use the modulus operator (%
) to obtain the remainder when the integer is divided by 10. The remainder will be the last digit of the integer.
Here's an example of how you could use the modulus operator to get the last digit of an integer:
int num = 12345; int lastDigit = num % 10; System.out.println("Last digit: " + lastDigit);
This code will output "Last digit: 5", because 5 is the remainder when 12345 is divided by 10.
You can also use the modulus operator to get the second-to-last digit of an integer by dividing the integer by 10 and taking the remainder, as shown in the following example:
int secondToLastDigit = (num / 10) % 10; System.out.println("Second-to-last digit: " + secondToLastDigit);
This code will output "Second-to-last digit: 4", because 4 is the remainder when 1234 is divided by 10.
Note that the modulus operator only works for integers, so if you want to get the last digit of a decimal number, you will need to use a different approach.