Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Usage of Constant

 
Badri Sarma
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. public final String str="USA";
2. public static final String str="USA";

Can I use the keyword "constant" in either of these statements?
 
Stefan Krompass
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Constants are declared like this:

There is no keyword constant in Java.

cu

Stefan
 
Badri Sarma
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Stefan.

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

Badri
 
Jon Poulton
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic