Constants in Java


I want to know the mechanism for implementing constants, since there is no predefined word here.

Author: angry, 2012-02-04

2 answers

public static final int MY_CONST_1 = 25;
private static final dobule MY_CONST_2 = 2.3;
 5
Author: Jakeroid, 2012-02-07 06:13:20

All literals and values that you use fall into the pool of class constants. If you want to commit something, use the final keyword.

public final int MY_CONST = 777;

Or a reference to the object

public final Object MY_OBJ = new Object();

But keep in mind that final only acts on the link itself, but does not act inside

public final AtomicInteger V = new AtomicInteger();

...
V.set(777);

Same with an array: you won't be able to override the array reference, but the values can change

 public final int[] MY_ARRAY = new int[1];
 5
Author: cy6erGn0m, 2012-02-04 21:02:57