• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

doubt regarding final variables.

 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
when i put

final String s = "Java";
HashMap m = new HashMap();
m.put(s,"Java1");
m.put(s,"Java2");
System.out.println(m.get(s));//prints Java2

What i am not clear is how a final variable has been reassigned?Is that the object s reference alone changes and the object by itself is final?
 
Ranch Hand
Posts: 8945
Firefox Browser Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Hi all,
when i put

final String s = "Java";
HashMap m = new HashMap();
m.put(s,"Java1");
m.put(s,"Java2");
System.out.println(m.get(s));//prints Java2

What i am not clear is how a final variable has been reassigned?Is that the object s reference alone changes and the object by itself is final?



The final variable hasn't be reassigned. When you invoke hashmap.put(key1,value1) you are associating the value "vaule1" with the key "key1" so that when you do a get(key1) you will be returned the value "value1". When you invoke a put method you are not doing any assignment i.e. there is nothing like this happening - key1=value1.
 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Final variable has not changed in this case,
String s will remail "Java" only,
but in hashmap it takes key value pair,
so you first assign s i.e. Java key to Java1 value,
and again you assign same key to Java2,
in Hashmap key is unique thing

so thats why it is giving answer Java2
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic