• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

Usage of Constant  RSS feed

 
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?
 
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
 
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
Boost this thread!