• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

String Behaviour

 
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

public class HelloWorld{

    public static void main(String []args){
       System.out.println("Hello World");
       String p = new String("tempo");
       setString(p);
       System.out.println(p);
    }
   
    public static void setString(String p){
        p = new String("Raj");
    }
}

In the above program, no matter i say
p = new String("Raj"); (OR)
p = "Raj";

The above program prints temp only....

Can someone explains this ???

In many times when we set values to a object, the object value is changed....

Not sure why doesn't happen in the above.....

How to change it
 
Saloon Keeper
Posts: 9735
80
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Strings are "immutable", you can't change them. 'p' is a local reference to a String and you are reassigning this reference to refer to a different String, however that doesn't modify the the original String you passed in, only the local copy.

If 'p' were a member variable and not passed in as a parameter then what you are trying to do would work.
 
Marshal
Posts: 76862
366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This looks to me like a pass‑by‑value versus pass‑by‑reference problem. Remember that Java┬« doesn't support pass‑by‑reference.
 
Campbell Ritchie
Marshal
Posts: 76862
366
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This link might help about pass‑by‑value.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic