Page 1 of 1

Creating constants in Java Rate Topic: -----

#1 bhandari  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 9
  • View blog
  • Posts: 754
  • Joined: 31-January 08

Post icon  Posted 25 March 2008 - 01:10 AM

Java has const as keyword for declaring constants (variables whose value can’t be changed after initialization). But const has not been implemented in any of the versions of JDK. const has been kept as reserved word which means that no identifier can be named as const in a program.

Then how should one go about declaring constants in Java?

Fortunately, the final keyword can be applied to variables in addition to classes as well as methods. The use of final keyword on variables makes sure that the value of the variable can’t be changed.


public final int a = 2;
a=3; //will flash compiler error

Once the final variable a has been initialized to 2, its value can’t be changed to 3.

But generally, constants are not associated to a particular instance of the class. So it is better to add static modifier also as:

public static final a = 2;

But wait there is a catch when using object references. Consider this:

public static final obj = new Object();
obj = new Object();  //compiler error as expected

The second line will make the compiler flash an error about changing the reference obj which was pointing to some other object.

But how about this:

public static final UserCar usrcar = new UserCar (“suzuki”);
usrcar.changeTo(“honda”);  // no compiler error

In the above case, no error is flashed by compiler because the final reference is still pointing to the same object as it was initialized. After second line, it’s the car object that has been modified and not the object reference “usrcar”.

So how would you go about making your object as final as opposed to object reference being final. Well, just make the object reference as “private” so that no other program can modify your object.

Is This A Good Question/Topic? 0
  • +

Replies To: Creating constants in Java

#2 herefishyfishy  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 7
  • View blog
  • Posts: 60
  • Joined: 01-May 08

Posted 03 June 2008 - 05:51 PM

If you mark it as private, no other program can modify your object. But no other program can USE your object either.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1