CL_ABAP_RANDOM¶
Generate random numbers in ABAP using a seedable pseudo-random number generator.
Purpose¶
CL_ABAP_RANDOM is the base class for random number generation. Use its subclasses for typed output:
| Class | Output type | Use for |
|---|---|---|
CL_ABAP_RANDOM_INT |
TYPE I |
Random integers |
CL_ABAP_RANDOM_FLOAT |
TYPE F |
Random floats 0.0–1.0 |
CL_ABAP_RANDOM_PACKED |
TYPE P |
Random packed decimals |
CL_ABAP_RANDOM_INT8 |
TYPE INT8 |
Large random integers |
Key methods¶
| Method | Description |
|---|---|
CREATE( seed min max ) |
Factory — create a generator with range and optional seed |
GET_NEXT( ) |
Return the next random value |
cl_abap_random=>seed( ) |
Static — returns a time-based seed value |
Examples¶
Random integer in a range¶
DATA(lo_rand) = cl_abap_random_int=>create(
seed = cl_abap_random=>seed( )
min = 1
max = 100 ).
DATA(lv_number) = lo_rand->get_next( ).
WRITE: / 'Random number:', lv_number.
Generate multiple random numbers¶
DATA(lo_rand) = cl_abap_random_int=>create(
seed = cl_abap_random=>seed( )
min = 1
max = 1000 ).
DO 5 TIMES.
WRITE: / lo_rand->get_next( ).
ENDDO.
Random float between 0 and 1¶
DATA(lo_float) = cl_abap_random_float=>create(
seed = cl_abap_random=>seed( ) ).
DATA(lv_chance) = lo_float->get_next( ). " e.g. 0.7341...
IF lv_chance < '0.3'.
" 30% probability branch
ENDIF.
Pick a random element from an internal table¶
DATA lt_items TYPE STANDARD TABLE OF string.
APPEND 'Alpha' TO lt_items.
APPEND 'Beta' TO lt_items.
APPEND 'Gamma' TO lt_items.
DATA(lo_rand) = cl_abap_random_int=>create(
seed = cl_abap_random=>seed( )
min = 1
max = lines( lt_items ) ).
DATA(lv_index) = lo_rand->get_next( ).
DATA(lv_picked) = lt_items[ lv_index ].
WRITE: / 'Picked:', lv_picked.
Reproducible sequence (fixed seed for testing)¶
" Fixed seed produces the same sequence every run — useful for unit tests
DATA(lo_rand) = cl_abap_random_int=>create(
seed = 42
min = 1
max = 100 ).
Not cryptographically secure
CL_ABAP_RANDOM uses a simple pseudo-random algorithm suitable for simulations and test data generation. Do not use it for security-sensitive purposes (tokens, session IDs, password generation). Use CL_ABAP_HMAC with a secure entropy source for those cases.
See also¶
CL_ABAP_HMAC— cryptographic hashing