Welcome to Dream.In.Code
Getting Java Help is Easy!

Join 107,669 Java Programmers for FREE! Ask your question and get quick answers from experts. There are 1,042 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! 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 - 01: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 - 05: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: 8/29/08 11:03PM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month