Me very new to java prgmng and got to redesign a C proj in java. Might be very insane question but not for me.
My c poject has a file, called headerfile.h and the structure looks like this

define ID_File1 0x6F01

define ID_File2 0x6F02


likewise all constants r declared in this file nd the main C file will include this file.
Is there any way to declare such files in java, whr i have all my constants defined in my file and in future to amend this file rather than adding in main java file.
Help reqd.


Edited 3 Years Ago by rose_anne

You declare constants in Java as static final fields such as:

package mypackage;

public class MyClass {
    public static final int ID_File1 = 0x6F01;
    public static final int ID_File2 = 0x6F02;

As long as the fields are public you can access your constants outside of the class, and if your class is also public you can access your constants from anywhere. For example, mypackage.MyClass.ID_File1. You can also use an interface instead of a class, but it is impossible to declare constants that are not members of some class or interface.

Normally you would choose a class where the constants will be used heavily, especially a class that requires the constants to be given as arguments to its methods. If you cannot choose a class to hold your constants then you can make a new class that does nothing but hold your constants. For a class like that instances will probably be meaningless, so you should declare a private constructor to make it impossible to create instances of the class.

Edited 3 Years Ago by bguild

Thank u thanku so much bguild....Working on it now...Thanks once again

To make it more like a c header file full of defines, you can declare pubic static final members, as bguild explained, then at then start of any .java file you can
import static mypackage.MyClass.*;
Now you can simply use the public static member names in that file without needing to qualify them with the package/class names.
For example, the java.lang package contains the Math class, and that has the useful member
public static final double PI = 3.14159265358979323846;
so if you
import static java.lang.Math.*;
you can simply refer to it as PI in your code

ok.. understood d way it works now.

Thank u friends, have started my code and so far smooth progress. Thank u so much for timley help. Ciao soon ...


This article has been dead for over six months. Start a new discussion instead.