2

I want to declare some static variables and use them a lot in my code, so in this example if I want to change the phone number I will change it in one place:

public class AppInformation{
    static String phone_number="44444444";
}

So now I could get the phone_number by calling the class : AppInformation.phone_number;

Another solution:

public class AppInformation {

    public static String get_phone_number(){
        return "44444444";
    } 
}

Now I could call the method: AppInformation.get_phone_number();

Actually I prefer the second method because it is thread safe!

Is this correct? Are there any other suggestions?

PurkkaKoodari
  • 6,703
  • 6
  • 37
  • 58
user3516596
  • 339
  • 5
  • 14
  • If the program doesn't change the number, the first one is thread-safe - although you can't prove it's thread-safe just by looking at it, which you can with the second. If the program does change the number, the second one won't work. – user253751 Apr 10 '14 at 11:05
  • so I should declare it as private static final string PHONE_NUMBER ! as mention below . – user3516596 Apr 10 '14 at 11:22

3 Answers3

5

Declare it as public static final String PHONE_NUMBER = "44444444". Since you can only read this variable, it is thread-safe.

Why I named it PHONE_NUMBER, not phoneNumber (or breaking all known to me Java conventions phone_number), is explained here.

Community
  • 1
  • 1
Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110
1

You can declare it as

static final String phone_number="44444444"; And do not worry about threadsafe anymore :)

VinhNT
  • 1,091
  • 8
  • 13
1

What you are saying is that you want a constant, which in Java, is commonly expressed like this:

public class AppInformation
{
  public static final String PHONE_NUMBER = "44444444";
}

Note, in your example you've missed:

  • the access modifier, which in the case of a class means the value would be package private.
  • the final keywork, which means the value could be modified when the program is running.
Nick Holt
  • 33,455
  • 4
  • 52
  • 58
  • should I declare it as public or private ?\ – user3516596 Apr 10 '14 at 11:20
  • Depends on where you want it to be visible - if `PHONE_NUMBER` is only used inside the class `AppInformation` then it should be `private`; however if you intend to use `PHONE_NUMBER` throughout your application then it should be `public`. The same logic follows, for `protected` and *package private* (see the access modifier link I put in my answer) – Nick Holt Apr 10 '14 at 11:28
  • yes thank you very much it is very helpful, so I think i will declare it as private ,because i just call it by the class them self, I mean AppInformation.PHONE_NUMBER . :) – user3516596 Apr 10 '14 at 11:32