File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Usage of Constant" Watch "Usage of Constant" New topic
Author

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.

cu

Stefan
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?

Badri
Jon Poulton
Greenhorn

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.
Example:

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

public printVal()
{
System.out.println(val);
}

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

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.
Jon
 
Don't get me started about those stupid light bulbs.
 
subject: Usage of Constant
 
Similar Threads
Declaring a string constant
compile time constants
Inconsistent Concepts from Two Different Mock Exams
what are compile time constant
how to convert from string("a") to char..