0

Sorry this look very childish question .But why my String value is not changing. my code is below

class Car{

public static void car(String name)
{
name="Bmw";
}
}

public static void main(String[] args) {    

String name="honda";

Car.car(name);

System.out.println(name);
    }

out put:-honda

I know java is pass by value . so i was thinking that honda will become bmw. Please give explaination on this.Thanks in advance!

Fajar Khan
  • 952
  • 1
  • 12
  • 30
FaisalAhmed
  • 3,469
  • 7
  • 46
  • 76
  • The explanation is in your question: Java uses pass-by-value. All you're doing in your `car` function is changing the value in the `name` **parameter** within the `car` function. That has no effect (and *can* have no effect) on the `name` **variable** in `main`. – T.J. Crowder Aug 07 '16 at 08:44
  • If you know java is pass-by-value, why do you think honda has to became bmv? – Andrew Tobilko Aug 07 '16 at 08:46
  • I was thinking honda will be passed . and name will be changed to bmw . – FaisalAhmed Aug 07 '16 at 08:47
  • 1
    Read the upvoted answers in the linked original. They answer this in detail. – T.J. Crowder Aug 07 '16 at 08:49
  • @FaisalAhmed, it is not logical, this behaviour you described should be in "pass-by-reference" scenario – Andrew Tobilko Aug 07 '16 at 08:50
  • Strings are immutable in Java. `name="Bmw"` does not *modify* the original string, it assigns a *new* string to the `name` variable, and since arguments are passed by value, the new value is invisible to the caller. – shmosel Aug 07 '16 at 10:18
  • Thanks friends i understood concept now – FaisalAhmed Aug 07 '16 at 10:29
  • http://stackoverflow.com/questions/38854909/can-fonts-and-its-size-can-be-changed-from-xml-in-android can anyone help me on this – FaisalAhmed Aug 09 '16 at 15:59

0 Answers0