Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes Usage of Constant Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Usage of Constant" Watch "Usage of Constant" New topic

Usage of Constant

Badri Sarma
Ranch Hand

Joined: Apr 01, 2003
Posts: 72
1. public final String str="USA";
2. public static final String str="USA";

Can I use the keyword "constant" in either of these statements?

Thanks<br />Badri
Stefan Krompass
Ranch Hand

Joined: Apr 29, 2004
Posts: 75
Constants are declared like this:

There is no keyword constant in Java.


Badri Sarma
Ranch Hand

Joined: Apr 01, 2003
Posts: 72
Thank you Stefan.

I want to know the difference between the two statements I have mentioned. Can you help me?

Jon Poulton

Joined: Jun 09, 2004
Posts: 27
The only difference between the two is the usage of the "static" keyword. "static" means that there is only 1 instance of the the variable PER CLASS. So even if you create 10000000 objects there will only be 1 instance of a given static variable belonging to the class.

class A
private static int val = 0;
public A()
{ }

public printVal()

// Static method called by doing A.increment will
// increment val for all instances of A.
public static increment()

Every time you call A.increment is will increment the single static variable shared by all of the A objects. Thus, whenever printVal is called on A it simply prints out the number of times increment has been called.
I agree. Here's the link:
subject: Usage of Constant
It's not a secret anymore!