How to keep leading zero when storing integer value with leading zero in Arraylist without using String?

I wish to store some phone number in arraylist and if the number contain leading zero ,i want to store in arraylist as it is, without removing leading zero. how can i achieve that .

ArrayList<Integer> Restrict = new ArrayList<Integer>();
cars.add(01);
cars.add(02);
cars.add(3);
cars.add(4);
System.out.println(cars.get(0));

output

1      

how can i get 01 instead of 1.

2 answers

  • answered 2020-11-20 11:20 fatma zehra güç

    You can store them as strings

    ArrayList<String> Restrict = new ArrayList<>();
            cars.add("01");
            cars.add("02");
            cars.add("3");
            cars.add("4");
    
        System.out.println(cars.get(0));
    

  • answered 2020-11-20 11:35 Arvind Kumar Avinash

    Integer is the wrong type for this requirement

    A phone number consists of a minimum of 10 digits (first digit from 1-9) and it can go well beyond the maximum limit of Integer which is 2147483647.

    Apart from this, the 0 at the beginning of an Integer means it's radix is 8 i.e. it represents an octal number e.g.

    public class Main {
        public static void main(String[] args) {
            int x = 0123;
            System.out.println(x);
        }
    }
    

    Output:

    83
    

    Note that (0123)8 = (83)10

    The right type for this requirement is String i.e. you should declare your List as follows:

    List<String> restrict = new ArrayList<>();
    

    and store the numbers as

    restrict.add("01234567890")
    restrict.add("1234567890")
    

    Also, always follow the Java naming conventions e.g. the name of the variable can be restrict but should not be named as Restrict (as in your code).