-2

if I call any method and i passes string as parameter. for example,

****some code***
somemethod("rohit");

*****some code ****

somemethod(String name){ 

  ***some code***
}

Now in this case how many string object will be created? means, hardcoded "rohit" also created as an object and argument name also creates one more object.

Kaushal28
  • 4,823
  • 4
  • 30
  • 57
  • Method parameters are just new variables pointing to the same object/instance. Using string literals (quotation marks) to create strings will use string interning. That means that it comes out of an internal cache. So writing `"huhu"` 100 times in your code only leads to one string `"huhu"` being created and the rest comes out of the cache, pointing to the same object. – Zabuzard Jul 24 '19 at 06:41
  • Cache means String pool right? @Zabuza – Kaushal28 Jul 24 '19 at 06:42
  • Yes. Just google "String interning", its a common technique. Wikipedia has a nice explanation. – Zabuzard Jul 24 '19 at 11:55

2 Answers2

2

When you write rohit, it will create a new String object. But when you pass it to a method argument, another variable (here name) will just point to that previously created object. It won't create a new object. So in total, only one String object will be created in your case. Refer this: https://stackoverflow.com/a/12429953/5353128

Kaushal28
  • 4,823
  • 4
  • 30
  • 57
  • somemethod("rohit"); such method i called many times in my java application. is this reduce performance of application? – rohit_mhetre Jul 24 '19 at 06:21
  • If it's "rohit" every time, then no new object will be created because of String pool in Java. See this: https://stackoverflow.com/questions/3801343/what-is-string-pool-in-java If name changes every time, create a variable with a name and then pass variable to all the methods instead of hard coding the values – Kaushal28 Jul 24 '19 at 06:23
  • @rohit_mhetre you can accept the answer if this is what you were looking for! – Kaushal28 Jul 24 '19 at 08:49
-1

Strings can be created as a reference object or at String pool. If We declare it as Objects it will consider about the value and only one object will created.Here when you code it as rohit it will create new object. But if you pass it as parameter reference it won't create any new objects

  • It's exactly the reverse of what you're saying. Using a literal string like "rohit" here only ever creates one object because it is looked up through the pool. – Erwin Bolwidt Jul 24 '19 at 07:50