2

Possible Duplicate:
#ifdef #ifndef in Java

I'm trying to implement some debug messages in my Android code by using something like this:

private static final boolean DEBUG = false;

if (DEBUG) {
// some code
}

However, upon compilation I keep getting "Illegal start of expression" errors. final boolean works, but neither static nor private work.

I'm declaring the DEBUG variable in methods. Would also appreciate if there's a way to make this global so that everything within the same Java file will see it rather than me having to declare it in every method that needs it.

Thanks!

Community
  • 1
  • 1
user1118764
  • 9,255
  • 18
  • 61
  • 113
  • just put the variable outside a method and everything can see it. – Serdalis Nov 01 '12 at 01:58
  • you can't create global variables in Java, it all need to be part of some class scope. Defining DEBUG as a private static final member of the class gives the class permission to read it. That means that every method in the class can read the member. – IllegalArgumentException Nov 01 '12 at 01:59

2 Answers2

5

You have to declare the variable at the class-level, if you want the variable to be visible to all the methods in that class.

If your doing the following inside a method:

private static final boolean DEBUG = false;

the problem is that the modifiers private and static are not allowed within a method.


Actually, you should be using logger for this kind of purpose.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
1

Just declare it at the top of your class (outside of methods but still in the class itself).

public class MyClass { 
    private static final boolean DEBUG = false;
    ... 
}

This way, you can access DEBUG from every method you define in MyClass. You receive an error because you cannot use the private/static modifiers when defining variables within methods, you can only use them with class fields (same goes for public and protected - you can use final anywhere, however).

arshajii
  • 127,459
  • 24
  • 238
  • 287