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 Can a string be declared static Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Can a string be declared static" Watch "Can a string be declared static" New topic
Author

Can a string be declared static

ragi singh
Ranch Hand

Joined: Mar 10, 2010
Posts: 198

I have an example in which the String variable is declared static . The String variable is itself immutable , then how can we declare it as static . My class compiles successfully. CAn anyone explain ?
prakash pawar
Ranch Hand

Joined: Mar 11, 2010
Posts: 42
Hi

A String can be declared as static and there should no be any copilation error.

Declaring an static variable means there will be single copy of that instance variable and that will be shared by all the instance of a Class.

Saying String is immutable means you cannot change the value of a String object. for every new assignment of String variable it will create a new Object rather than overwriting on the existing Object.


Regards,
Prakash Pawar.
ragi singh
Ranch Hand

Joined: Mar 10, 2010
Posts: 198

ok thank you
Anbarasu Aladiyan
Ranch Hand

Joined: Jun 02, 2009
Posts: 182

maverick rick wrote:The String variable is itself immutable , then how can we declare it as static .
Immutable is applicable for objects (NOT variables).
Static is applicable for variables (To define the scope of a variable, which may refer to an object).


A.A.Anbarasu
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13869
    
  10

The keyword static has nothing to do with something being immutable or constant in any way.

If you make a variable static, then there will be only one instance of that variable that's shared among all instances of the class in which the variable exists. See Understanding Instance and Class Members in Sun's Java tutorial.

When a class is immutable, it means that the state of an instance of that class can't be changed after it has been created and initialised.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can a string be declared static
 
Similar Threads
Static final
static string
external variable in java
Static methods and static blocks
textbook page 217 error (from the classroom)