Welcome to Dream.In.Code
Become a Java Expert!

Join 136,912 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,731 people online right now. Registration is fast and FREE... Join Now!




Creating constants in Java

 
Reply to this topicStart new topic

> Creating constants in Java

bhandari
Group Icon



post 25 Mar, 2008 - 12:10 AM
Post #1


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.

e.g.

java

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:

java

public static final a = 2;


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

java

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:

java

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.

Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

herefishyfishy
Group Icon



post 3 Jun, 2008 - 04:51 PM
Post #2
If you mark it as private, no other program can modify your object. But no other program can USE your object either.
Go to the top of the page
+Quote Post


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 12/3/08 09:59PM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month