How to get the first and the last digit of a number in Java

2 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        int number = 87354;

        int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));
        System.out.println(firstDigit);
 
        int lastDigit = number % 10;
        System.out.println(lastDigit);       
    }
}
 
 
 
/*
run:
 
8
4

*/

 



answered Jun 3, 2020 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        int number = 87354;

        int firstDigit = number;
        while (firstDigit >= 10)  
            firstDigit /= 10; 
        System.out.println(firstDigit);
 
        int lastDigit = number % 10;
        System.out.println(lastDigit);       
    }
}
 
 
 
/*
run:
 
8
4

*/

 



answered Jun 3, 2020 by avibootz
edited Jun 3, 2020 by avibootz

Related questions

1 answer 114 views
1 answer 142 views
1 answer 126 views
1 answer 101 views
1 answer 108 views
1 answer 97 views
...