how to generate a long that is in the range of [0000,9999] (inclusive) by using the random class in java? The long has to be 4 digits.
            Asked
            
        
        
            Active
            
        
            Viewed 7.3k times
        
    2 Answers
52
            If you want to generate a number from range [0, 9999], you would use random.nextInt(10000). 
Adding leading zeros is just formatting:
String id = String.format("%04d", random.nextInt(10000));
 
    
    
        Grogi
        
- 2,099
- 17
- 13
- 
                    1It's in the previous answer, but don't forget: `Random random = new Random();` – CodeFinity Dec 22 '21 at 13:24
- 
                    @CodeFinity I don't see how anyone can forget to create the Random object.lol – Ojonugwa Jude Ochalifu Jan 06 '22 at 16:49
- 
                    Here what is mean by "%04", Also what can i do If I want to omit the 0 – Feezan Khattak Apr 21 '22 at 09:47
11
            
            
        A Java int will never have leading 0(s). You'll need a String for that. You could use String.format(String, Object...) or (PrintStream.printf(String, Object...)) like
Random rand = new Random();
System.out.printf("%04d%n", rand.nextInt(10000));
The format String %04d is for 0 filled 4 digits. And Random.nextInt(int) will be [0,10000) or [0,9999].
 
    
    
        Elliott Frisch
        
- 198,278
- 20
- 158
- 249
