2

In Objective C, to declare a variable constant I use #define FILE_NAME @"file.data"in a file called Constants.h. I import this file when needed.

What is the Java equivalent?

gherkins
  • 14,603
  • 6
  • 44
  • 70
M Jesse
  • 2,213
  • 6
  • 31
  • 37

2 Answers2

3

A constant in Java is the following

public static final String FILE_NAME = "file.data";
zirkelc
  • 1,451
  • 1
  • 23
  • 49
3

There is no Java equivalent to the C #define because there is no Java pre-processor. But you can define constants in Java. Inside a class, say Constants

public static final String FILE_NAME = "file.data";

Then you can perform a static import in another class where you need the constant:

import static my.package.Constants.*;

...

doSomethingWithFile(FILE_NAME);
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • I beg to differ. There are Java preprocessors. Even the C preprocessor can be used for Java. The only difference is that in Java it's not so common to use it. In C, it's an important part of the compiler and you hardly can live without it. And anyone who was developing J2ME apps, had to use a Java preprocessor (e.g. antenna). – Sulthan Mar 14 '13 at 20:19
  • Hmmm, you learn something new every day. I stand corrected. But there is no built-in, JDK-supplied preprocessor for Java. – rgettman Mar 14 '13 at 20:26
  • Nowadays preprocessor is used mostly for portability. Java is supposed to be portable automatically. However, for J2ME applications it was normal to make 80+ versions, covering specific bugs, different performances, different screen sizes and size limits... That's why a preprocessor was a must, even Netbeans introduced a preprocessor as part of the Mobile package. One of the reasons why J2ME developers moved for Android/iOS development jobs really fast. – Sulthan Mar 14 '13 at 20:32