• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can a string be declared static

 
ragi singh
Ranch Hand
Posts: 198
Oracle Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
ragi singh
Ranch Hand
Posts: 198
Oracle Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok thank you
 
Anbarasu Aladiyan
Ranch Hand
Posts: 182
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15448
42
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic