Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java constant examples (Create a java file having only constants)

Tags:

java

constants

What is the best practice to declare a java file having only constant?

public interface DeclareConstants {     String constant = "Test"; } 

OR

public abstract class DeclareConstants {     public static final String constant = "Test"; } 
like image 981
Shreyos Adikari Avatar asked Sep 20 '12 17:09

Shreyos Adikari


People also ask

How do you write a constant file in Java?

Syntax to assign a constant value in java:static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded. The final modifier makes the variable unchangeable.

What are constants in Java give an example?

Real constants consist of a sequence of digits with fractional parts or decimal points. These constants are also called floating-point constants. The valid examples of real constants are 2.3, 0.0034, -0.75, 56.7, etc. These numbers are shown in the decimal point notation.

How do you declare a string a constant in Java?

With final we can make the variable constant. Hence the best practice to define a constant variable is the following: private static final String YOUR_CONSTANT = "Some Value"; The access modifier can be private/public depending on the business logic.


2 Answers

Neither one. Use final class for Constants declare them as public static final and static import all constants wherever necessary.

public final class Constants {      private Constants() {             // restrict instantiation     }      public static final double PI = 3.14159;     public static final double PLANCK_CONSTANT = 6.62606896e-34; } 

Usage :

import static Constants.PLANCK_CONSTANT; import static Constants.PI;//import static Constants.*;  public class Calculations {          public double getReducedPlanckConstant() {                 return PLANCK_CONSTANT / (2 * PI);         } } 

See wiki link : http://en.wikipedia.org/wiki/Constant_interface

like image 167
Nandkumar Tekale Avatar answered Sep 22 '22 18:09

Nandkumar Tekale


- Create a Class with public static final fields.

- And then you can access these fields from any class using the Class_Name.Field_Name.

- You can declare the class as final, so that the class can't be extended(Inherited) and modify....

like image 24
Kumar Vivek Mitra Avatar answered Sep 22 '22 18:09

Kumar Vivek Mitra